text
stringlengths
54
60.6k
<commit_before>/*========================================================================= Library: TubeTK Copyright 2010 Kitware Inc. 28 Corporate Drive, Clifton Park, NY, 12065, USA. All rights reserved. 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. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #include <cstdlib> #include <tubeCLIProgressReporter.h> void cliProgressReporterTestCallbackFunction( void * data ) { if( data ) { std::cout << "cliProgressReporterTestCallbackFunction with pointer: " << data << std::endl; } else { std::cout << "cliProgressReporterTestCallbackFunction with pointer: NULL" << std::endl; } } int tubeCLIProgressReporterTest(int argc, char *itkNotUsed(argv)[] ) { if( argc != 1 ) { std::cerr << "Usage: " << std::endl; return EXIT_FAILURE; } ModuleProcessInformation CLPProcessInfo; CLPProcessInfo.Initialize(); CLPProcessInfo.SetProgressCallback( cliProgressReporterTestCallbackFunction, NULL ); std::string processName("tubeCLIProgressReporterTest"); tube::CLIProgressReporter reporter( processName.c_str(), &CLPProcessInfo, true ); reporter.Start( ); reporter.Report( 0.0 ); reporter.Report( 0.5 ); CLPProcessInfo.Abort = 1; reporter.Report( 1.0 ); reporter.End( ); if( reporter.GetProcess( ) != processName ) { std::cerr << "Process name does not match." << std::endl; std::cerr << reporter.GetProcess() << " != " << processName << std::endl; } if( reporter.GetProcessInformation( ) != &CLPProcessInfo ) { std::cerr << "Process info does not match." << std::endl; } return EXIT_SUCCESS; } <commit_msg>STYLE: lines now under 90 characters.<commit_after>/*========================================================================= Library: TubeTK Copyright 2010 Kitware Inc. 28 Corporate Drive, Clifton Park, NY, 12065, USA. All rights reserved. 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. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #include <cstdlib> #include <tubeCLIProgressReporter.h> void cliProgressReporterTestCallbackFunction( void * data ) { if( data ) { std::cout << "cliProgressReporterTestCallbackFunction with pointer: " << data << std::endl; } else { std::cout << "cliProgressReporterTestCallbackFunction with pointer: NULL" << std::endl; } } int tubeCLIProgressReporterTest(int argc, char *itkNotUsed(argv)[] ) { if( argc != 1 ) { std::cerr << "Usage: " << std::endl; return EXIT_FAILURE; } ModuleProcessInformation CLPProcessInfo; CLPProcessInfo.Initialize(); CLPProcessInfo.SetProgressCallback( cliProgressReporterTestCallbackFunction, NULL ); std::string processName("tubeCLIProgressReporterTest"); tube::CLIProgressReporter reporter( processName.c_str(), &CLPProcessInfo, true ); reporter.Start( ); reporter.Report( 0.0 ); reporter.Report( 0.5 ); CLPProcessInfo.Abort = 1; reporter.Report( 1.0 ); reporter.End( ); if( reporter.GetProcess( ) != processName ) { std::cerr << "Process name does not match." << std::endl; std::cerr << reporter.GetProcess() << " != " << processName << std::endl; } if( reporter.GetProcessInformation( ) != &CLPProcessInfo ) { std::cerr << "Process info does not match." << std::endl; } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: DllMain.cpp,v $ * * $Revision: 1.6 $ * * last change: $Author: vg $ $Date: 2006-09-25 13:16:02 $ * * 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 * ************************************************************************/ #define WIN32_LEAN_AND_MEAN #pragma warning(push,1) // disable warnings within system headers #include <windows.h> #pragma warning(pop) #include <malloc.h> #define _MBCS #include <tchar.h> HMODULE UWINAPI_BaseAddress = NULL; const CHAR szUnicowsModuleName[] = "UNICOWS.DLL"; static HMODULE WINAPI _LoadUnicowsLibrary(VOID) { CHAR szModulePath[MAX_PATH]; HMODULE hModuleUnicows = NULL; // First search in the same directory as UWINAPI.DLL was loaded from. This is because // UWINAPI.DLL not always resides in the same directory as the actual application. if ( UWINAPI_BaseAddress && GetModuleFileNameA( UWINAPI_BaseAddress, szModulePath, MAX_PATH ) ) { char *lpLastBkSlash = _tcsrchr( szModulePath, '\\' ); if ( lpLastBkSlash ) { size_t nParentDirSize = (size_t) (_tcsinc( lpLastBkSlash ) - szModulePath); LPSTR lpUnicowsModulePath = (LPTSTR)_alloca( nParentDirSize + sizeof(szUnicowsModuleName) ); if ( lpUnicowsModulePath ) { _tcsncpy( lpUnicowsModulePath, szModulePath, nParentDirSize ); _tcscpy( lpUnicowsModulePath + nParentDirSize, szUnicowsModuleName ); hModuleUnicows = LoadLibraryA( lpUnicowsModulePath ); } } } // Search at the common places if ( !hModuleUnicows ) hModuleUnicows = LoadLibraryA(szUnicowsModuleName); return hModuleUnicows; } static HMODULE WINAPI LoadUnicowsLibrary(VOID) { HMODULE hModuleUnicows; int idMsg = IDOK; do { hModuleUnicows = _LoadUnicowsLibrary(); if ( !hModuleUnicows ) { LPVOID lpMsgBuf; FormatMessageA( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, ERROR_DLL_NOT_FOUND /* GetLastError() */, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language (LPSTR)&lpMsgBuf, 0, NULL ); // Process any inserts in lpMsgBuf. CHAR szModuleFileName[MAX_PATH]; GetModuleFileNameA( NULL, szModuleFileName, sizeof(szModuleFileName) ); LPSTR lpMessage = (LPSTR)_alloca( strlen( (LPCSTR)lpMsgBuf ) + sizeof(szUnicowsModuleName) + 1 ); strcpy( lpMessage, (LPCSTR)lpMsgBuf ); strcat( lpMessage, "\n" ); strcat( lpMessage, szUnicowsModuleName ); // Free the buffer. LocalFree( lpMsgBuf ); // Display the string. idMsg = MessageBoxA( NULL, lpMessage, szModuleFileName, MB_ABORTRETRYIGNORE | MB_ICONERROR | MB_TASKMODAL ); if ( IDABORT == idMsg ) TerminateProcess( GetCurrentProcess(), 255 ); } } while ( !hModuleUnicows && IDRETRY == idMsg ); return hModuleUnicows; } extern "C" FARPROC _PfnLoadUnicows = (FARPROC)LoadUnicowsLibrary; extern "C" BOOL WINAPI DllMain( HMODULE hModule, DWORD dwReason, LPVOID ) { switch ( dwReason ) { case DLL_PROCESS_ATTACH: UWINAPI_BaseAddress = hModule; return DisableThreadLibraryCalls( hModule ); default: return TRUE; } } <commit_msg>INTEGRATION: CWS mingwport03 (1.5.30); FILE MERGED 2006/11/08 14:02:27 vg 1.5.30.2: RESYNC: (1.5-1.6); FILE MERGED 2006/09/18 14:38:39 vg 1.5.30.1: #i53572# MinGW port<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: DllMain.cpp,v $ * * $Revision: 1.7 $ * * last change: $Author: vg $ $Date: 2007-03-26 14:26:11 $ * * 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 * ************************************************************************/ #define WIN32_LEAN_AND_MEAN #pragma warning(push,1) // disable warnings within system headers #include <windows.h> #pragma warning(pop) #include <malloc.h> #define _MBCS #include <tchar.h> HMODULE UWINAPI_BaseAddress = NULL; const CHAR szUnicowsModuleName[] = "UNICOWS.DLL"; static HMODULE WINAPI _LoadUnicowsLibrary(VOID) { CHAR szModulePath[MAX_PATH]; HMODULE hModuleUnicows = NULL; // First search in the same directory as UWINAPI.DLL was loaded from. This is because // UWINAPI.DLL not always resides in the same directory as the actual application. if ( UWINAPI_BaseAddress && GetModuleFileNameA( UWINAPI_BaseAddress, szModulePath, MAX_PATH ) ) { char *lpLastBkSlash = _tcsrchr( szModulePath, '\\' ); if ( lpLastBkSlash ) { size_t nParentDirSize = (size_t) (_tcsinc( lpLastBkSlash ) - szModulePath); LPSTR lpUnicowsModulePath = (LPTSTR)_alloca( nParentDirSize + sizeof(szUnicowsModuleName) ); if ( lpUnicowsModulePath ) { _tcsncpy( lpUnicowsModulePath, szModulePath, nParentDirSize ); _tcscpy( lpUnicowsModulePath + nParentDirSize, szUnicowsModuleName ); hModuleUnicows = LoadLibraryA( lpUnicowsModulePath ); } } } // Search at the common places if ( !hModuleUnicows ) hModuleUnicows = LoadLibraryA(szUnicowsModuleName); return hModuleUnicows; } static HMODULE WINAPI LoadUnicowsLibrary(VOID) { HMODULE hModuleUnicows; int idMsg = IDOK; do { hModuleUnicows = _LoadUnicowsLibrary(); if ( !hModuleUnicows ) { LPVOID lpMsgBuf; FormatMessageA( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, ERROR_DLL_NOT_FOUND /* GetLastError() */, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language (LPSTR)&lpMsgBuf, 0, NULL ); // Process any inserts in lpMsgBuf. CHAR szModuleFileName[MAX_PATH]; GetModuleFileNameA( NULL, szModuleFileName, sizeof(szModuleFileName) ); LPSTR lpMessage = (LPSTR)_alloca( strlen( (LPCSTR)lpMsgBuf ) + sizeof(szUnicowsModuleName) + 1 ); strcpy( lpMessage, (LPCSTR)lpMsgBuf ); strcat( lpMessage, "\n" ); strcat( lpMessage, szUnicowsModuleName ); // Free the buffer. LocalFree( lpMsgBuf ); // Display the string. idMsg = MessageBoxA( NULL, lpMessage, szModuleFileName, MB_ABORTRETRYIGNORE | MB_ICONERROR | MB_TASKMODAL ); if ( IDABORT == idMsg ) TerminateProcess( GetCurrentProcess(), 255 ); } } while ( !hModuleUnicows && IDRETRY == idMsg ); return hModuleUnicows; } extern "C" { FARPROC _PfnLoadUnicows = (FARPROC)LoadUnicowsLibrary; } #ifdef __MINGW32__ extern "C" { typedef void (*func_ptr) (void); extern func_ptr __CTOR_LIST__[]; extern func_ptr __DTOR_LIST__[]; static void do_startup(void); static void do_cleanup(void); HMODULE hModuleUnicowsDLL; void __do_global_dtors (void) { static func_ptr *p = __DTOR_LIST__ + 1; /* * Call each destructor in the destructor list until a null pointer * is encountered. */ while (*p) { (*(p)) (); p++; } } void __do_global_ctors (void) { unsigned long nptrs = (unsigned long) __CTOR_LIST__[0]; unsigned i; /* * If the first entry in the constructor list is -1 then the list * is terminated with a null entry. Otherwise the first entry was * the number of pointers in the list. */ if (nptrs == static_cast<unsigned long>(-1)) { for (nptrs = 0; __CTOR_LIST__[nptrs + 1] != 0; nptrs++) ; } /* * Go through the list backwards calling constructors. */ for (i = nptrs; i >= 1; i--) { __CTOR_LIST__[i] (); } /* * Register the destructors for processing on exit. */ atexit (__do_global_dtors); } static int initialized = 0; void __main (void) { if (!initialized) { initialized = 1; do_startup(); __do_global_ctors (); } } static void do_startup( void ) { if (((LONG)GetVersion()&0x800000ff) == 0x80000004) { hModuleUnicowsDLL = LoadUnicowsLibrary(); if (hModuleUnicowsDLL) atexit(do_cleanup); } } void do_cleanup( void ) { FreeLibrary(hModuleUnicowsDLL); } } #endif extern "C" BOOL WINAPI DllMain( HMODULE hModule, DWORD dwReason, LPVOID ) { switch ( dwReason ) { case DLL_PROCESS_ATTACH: UWINAPI_BaseAddress = hModule; return DisableThreadLibraryCalls( hModule ); default: return TRUE; } } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: ChartTypeTemplate.hxx,v $ * * $Revision: 1.6 $ * * last change: $Author: bm $ $Date: 2004-01-26 09:12:50 $ * * 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: 2003 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef CHART_CHARTTYPETEMPLATE_HXX #define CHART_CHARTTYPETEMPLATE_HXX #ifndef _CPPUHELPER_IMPLBASE2_HXX_ #include <cppuhelper/implbase2.hxx> #endif #include "ServiceMacros.hxx" #ifndef _COM_SUN_STAR_UNO_XCOMPONENTCONTEXT_HPP_ #include <com/sun/star/uno/XComponentContext.hpp> #endif #ifndef _COM_SUN_STAR_CHART2_XCHARTTYPETEMPLATE_HPP_ #include <com/sun/star/chart2/XChartTypeTemplate.hpp> #endif #ifndef _COM_SUN_STAR_CHART2_XAXISCONTAINER_HPP_ #include <com/sun/star/chart2/XAxisContainer.hpp> #endif #ifndef _COM_SUN_STAR_CHART2_STACKMODE_HPP_ #include <com/sun/star/chart2/StackMode.hpp> #endif #ifndef _COM_SUN_STAR_CHART2_XGRIDCONTAINER_HPP_ #include <com/sun/star/chart2/XGridContainer.hpp> #endif #ifndef _COM_SUN_STAR_CHART2_XBOUNDEDCOORDINATESYSTEMCONTAINER_HPP_ #include <com/sun/star/chart2/XBoundedCoordinateSystemContainer.hpp> #endif #ifndef _COM_SUN_STAR_CHART2_XLEGEND_HPP_ #include <com/sun/star/chart2/XLegend.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSERVICENAME_HPP_ #include <com/sun/star/lang/XServiceName.hpp> #endif #ifndef _COM_SUN_STAR_CHART2_XCHARTTYPE_HPP_ #include <com/sun/star/chart2/XChartType.hpp> #endif namespace chart { class ChartTypeTemplate : public ::cppu::WeakImplHelper2< ::com::sun::star::chart2::XChartTypeTemplate, ::com::sun::star::lang::XServiceName > { public: explicit ChartTypeTemplate( ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > const & xContext, const ::rtl::OUString & rServiceName ); virtual ~ChartTypeTemplate(); APPHELPER_XSERVICEINFO_DECL() /// establish methods for factory instatiation // APPHELPER_SERVICE_FACTORY_HELPER( ChartTypeTemplate ) protected: // ____ XChartTypeTemplate ____ virtual ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XDiagram > SAL_CALL createDiagram( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XDataSeries > >& aSeriesSeq ) throw (::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL matchesTemplate( const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XDiagram >& xDiagram ) throw (::com::sun::star::uno::RuntimeException); // ____ XServiceName ____ virtual ::rtl::OUString SAL_CALL getServiceName() throw (::com::sun::star::uno::RuntimeException); // Methods to overload for automatic creation // ------------------------------------------ /// returns 2 by default. Supported are 2 and 3 virtual sal_Int32 getDimension() const; /** returns StackMode_NONE by default. For a column/bar chart you would want to return StackMode_STACKED here. */ virtual ::com::sun::star::chart2::StackMode getXStackMode() const; /** returns StackMode_NONE by default. This is a global flag used for all series if createDataSeriesTree() is not overloaded */ virtual ::com::sun::star::chart2::StackMode getYStackMode() const; /** returns StackMode_NONE by default. For a column/bar chart you would want to return StackMode_STACKED here. */ virtual ::com::sun::star::chart2::StackMode getZStackMode() const; virtual ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XChartType > getDefaultChartType() throw (::com::sun::star::uno::RuntimeException); // Methods for creating the diagram piecewise // ------------------------------------------ /** Creates a 2d or 3d cartesian coordinate system with mathematically oriented, linear scales with auto-min/max. <p>The dimension depends on the property "ChartStyle".</p> @param xCoordSysCnt If this container is valid, the coordinate system is added to it. */ virtual ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XBoundedCoordinateSystem > createCoordinateSystem( const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XBoundedCoordinateSystemContainer > & xCoordSysCnt ); /** create axes and add them to the given container. <p>As default, this method creates as many axes as there are dimensions in the given coordinate system. Each of the axis represents one of the dimensions of the coordinate system.</p> */ virtual void createAndAddAxes( const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XBoundedCoordinateSystem > & rCoordSys, const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XAxisContainer > & rOutAxisCnt ); /** create grids and add them to the given container. <p>As default, this method creates a major grid for the second coordinate of the coordinate system.</p> */ virtual void createAndAddGrids( const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XBoundedCoordinateSystem > & rCoordSys, const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XGridContainer > & rOutGridCnt ); /** create a data series tree, that fits the requirements of the chart type. <p>As default, this creates a tree with the following structure:</p> <pre> root | +-- chart type | +-- category (DiscreteStackableScaleGroup using scale 0) | +-- values (ContinuousStackableScaleGroup using scale 1) | +-- series 0 | +-- series 1 | ... | +.. series n-1 </pre> <p>If there are less than two scales available the returned tree is empty.</p> */ virtual ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XDataSeriesTreeParent > createDataSeriesTree( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XDataSeries > >& aSeriesSeq, const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XBoundedCoordinateSystem > & rCoordSys ); // helper methods // -------------- ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XDataSeriesTreeParent > createRootNode(); ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XDataSeriesTreeNode > createChartTypeGroup( const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XChartType > & xChartType ); ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XDataSeriesTreeNode > createScaleGroup( bool bIsDiscrete, bool bIsStackable, ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XBoundedCoordinateSystem > xCoordSys, sal_Int32 nRepresentedDimension, ::com::sun::star::chart2::StackMode eStackMode = ::com::sun::star::chart2::StackMode_NONE ); void addDataSeriesToGroup( const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XDataSeriesTreeNode > & rParent, const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XDataSeries > > & rDataSeries ); /** Finds the first ContinuousScaleGroup in the tree and sets the stacking mode there if it is a stackable group */ void setStackModeAtTree( const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XDataSeriesTreeParent > & rTree, ::com::sun::star::chart2::StackMode eMode ); void attachNodeToNode( const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XDataSeriesTreeNode > & rParent, const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XDataSeriesTreeNode > & rChild ); ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > GetComponentContext() const; private: ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > m_xContext; const ::rtl::OUString m_aServiceName; /** modifies the given diagram */ void FillDiagram( const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XDiagram > & xDiagram, const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XDataSeries > >& aSeriesSeq ); }; } // namespace chart // CHART_CHARTTYPETEMPLATE_HXX #endif <commit_msg>INTEGRATION: CWS ooo19126 (1.6.110); FILE MERGED 2005/09/05 18:43:20 rt 1.6.110.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: ChartTypeTemplate.hxx,v $ * * $Revision: 1.7 $ * * last change: $Author: rt $ $Date: 2005-09-08 01:19:16 $ * * 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 CHART_CHARTTYPETEMPLATE_HXX #define CHART_CHARTTYPETEMPLATE_HXX #ifndef _CPPUHELPER_IMPLBASE2_HXX_ #include <cppuhelper/implbase2.hxx> #endif #include "ServiceMacros.hxx" #ifndef _COM_SUN_STAR_UNO_XCOMPONENTCONTEXT_HPP_ #include <com/sun/star/uno/XComponentContext.hpp> #endif #ifndef _COM_SUN_STAR_CHART2_XCHARTTYPETEMPLATE_HPP_ #include <com/sun/star/chart2/XChartTypeTemplate.hpp> #endif #ifndef _COM_SUN_STAR_CHART2_XAXISCONTAINER_HPP_ #include <com/sun/star/chart2/XAxisContainer.hpp> #endif #ifndef _COM_SUN_STAR_CHART2_STACKMODE_HPP_ #include <com/sun/star/chart2/StackMode.hpp> #endif #ifndef _COM_SUN_STAR_CHART2_XGRIDCONTAINER_HPP_ #include <com/sun/star/chart2/XGridContainer.hpp> #endif #ifndef _COM_SUN_STAR_CHART2_XBOUNDEDCOORDINATESYSTEMCONTAINER_HPP_ #include <com/sun/star/chart2/XBoundedCoordinateSystemContainer.hpp> #endif #ifndef _COM_SUN_STAR_CHART2_XLEGEND_HPP_ #include <com/sun/star/chart2/XLegend.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSERVICENAME_HPP_ #include <com/sun/star/lang/XServiceName.hpp> #endif #ifndef _COM_SUN_STAR_CHART2_XCHARTTYPE_HPP_ #include <com/sun/star/chart2/XChartType.hpp> #endif namespace chart { class ChartTypeTemplate : public ::cppu::WeakImplHelper2< ::com::sun::star::chart2::XChartTypeTemplate, ::com::sun::star::lang::XServiceName > { public: explicit ChartTypeTemplate( ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > const & xContext, const ::rtl::OUString & rServiceName ); virtual ~ChartTypeTemplate(); APPHELPER_XSERVICEINFO_DECL() /// establish methods for factory instatiation // APPHELPER_SERVICE_FACTORY_HELPER( ChartTypeTemplate ) protected: // ____ XChartTypeTemplate ____ virtual ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XDiagram > SAL_CALL createDiagram( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XDataSeries > >& aSeriesSeq ) throw (::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL matchesTemplate( const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XDiagram >& xDiagram ) throw (::com::sun::star::uno::RuntimeException); // ____ XServiceName ____ virtual ::rtl::OUString SAL_CALL getServiceName() throw (::com::sun::star::uno::RuntimeException); // Methods to overload for automatic creation // ------------------------------------------ /// returns 2 by default. Supported are 2 and 3 virtual sal_Int32 getDimension() const; /** returns StackMode_NONE by default. For a column/bar chart you would want to return StackMode_STACKED here. */ virtual ::com::sun::star::chart2::StackMode getXStackMode() const; /** returns StackMode_NONE by default. This is a global flag used for all series if createDataSeriesTree() is not overloaded */ virtual ::com::sun::star::chart2::StackMode getYStackMode() const; /** returns StackMode_NONE by default. For a column/bar chart you would want to return StackMode_STACKED here. */ virtual ::com::sun::star::chart2::StackMode getZStackMode() const; virtual ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XChartType > getDefaultChartType() throw (::com::sun::star::uno::RuntimeException); // Methods for creating the diagram piecewise // ------------------------------------------ /** Creates a 2d or 3d cartesian coordinate system with mathematically oriented, linear scales with auto-min/max. <p>The dimension depends on the property "ChartStyle".</p> @param xCoordSysCnt If this container is valid, the coordinate system is added to it. */ virtual ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XBoundedCoordinateSystem > createCoordinateSystem( const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XBoundedCoordinateSystemContainer > & xCoordSysCnt ); /** create axes and add them to the given container. <p>As default, this method creates as many axes as there are dimensions in the given coordinate system. Each of the axis represents one of the dimensions of the coordinate system.</p> */ virtual void createAndAddAxes( const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XBoundedCoordinateSystem > & rCoordSys, const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XAxisContainer > & rOutAxisCnt ); /** create grids and add them to the given container. <p>As default, this method creates a major grid for the second coordinate of the coordinate system.</p> */ virtual void createAndAddGrids( const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XBoundedCoordinateSystem > & rCoordSys, const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XGridContainer > & rOutGridCnt ); /** create a data series tree, that fits the requirements of the chart type. <p>As default, this creates a tree with the following structure:</p> <pre> root | +-- chart type | +-- category (DiscreteStackableScaleGroup using scale 0) | +-- values (ContinuousStackableScaleGroup using scale 1) | +-- series 0 | +-- series 1 | ... | +.. series n-1 </pre> <p>If there are less than two scales available the returned tree is empty.</p> */ virtual ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XDataSeriesTreeParent > createDataSeriesTree( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XDataSeries > >& aSeriesSeq, const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XBoundedCoordinateSystem > & rCoordSys ); // helper methods // -------------- ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XDataSeriesTreeParent > createRootNode(); ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XDataSeriesTreeNode > createChartTypeGroup( const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XChartType > & xChartType ); ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XDataSeriesTreeNode > createScaleGroup( bool bIsDiscrete, bool bIsStackable, ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XBoundedCoordinateSystem > xCoordSys, sal_Int32 nRepresentedDimension, ::com::sun::star::chart2::StackMode eStackMode = ::com::sun::star::chart2::StackMode_NONE ); void addDataSeriesToGroup( const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XDataSeriesTreeNode > & rParent, const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XDataSeries > > & rDataSeries ); /** Finds the first ContinuousScaleGroup in the tree and sets the stacking mode there if it is a stackable group */ void setStackModeAtTree( const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XDataSeriesTreeParent > & rTree, ::com::sun::star::chart2::StackMode eMode ); void attachNodeToNode( const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XDataSeriesTreeNode > & rParent, const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XDataSeriesTreeNode > & rChild ); ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > GetComponentContext() const; private: ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > m_xContext; const ::rtl::OUString m_aServiceName; /** modifies the given diagram */ void FillDiagram( const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XDiagram > & xDiagram, const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XDataSeries > >& aSeriesSeq ); }; } // namespace chart // CHART_CHARTTYPETEMPLATE_HXX #endif <|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 "chrome/browser/chromeos/cros/cryptohome_library.h" #include "base/hash_tables.h" #include "base/message_loop.h" #include "chrome/browser/chrome_thread.h" #include "chrome/browser/chromeos/cros/cros_library.h" namespace chromeos { // This class handles the interaction with the ChromeOS cryptohome library APIs. class CryptohomeLibraryImpl : public CryptohomeLibrary { public: CryptohomeLibraryImpl() { if (CrosLibrary::Get()->EnsureLoaded()) Init(); } virtual ~CryptohomeLibraryImpl() {} bool CheckKey(const std::string& user_email, const std::string& passhash) { return chromeos::CryptohomeCheckKey(user_email.c_str(), passhash.c_str()); } bool AsyncCheckKey(const std::string& user_email, const std::string& passhash, Delegate* d) { return CacheCallback( chromeos::CryptohomeAsyncCheckKey(user_email.c_str(), passhash.c_str()), d, "Couldn't initiate async check of user's key."); } bool MigrateKey(const std::string& user_email, const std::string& old_hash, const std::string& new_hash) { return chromeos::CryptohomeMigrateKey(user_email.c_str(), old_hash.c_str(), new_hash.c_str()); } bool AsyncMigrateKey(const std::string& user_email, const std::string& old_hash, const std::string& new_hash, Delegate* d) { return CacheCallback( chromeos::CryptohomeAsyncMigrateKey(user_email.c_str(), old_hash.c_str(), new_hash.c_str()), d, "Couldn't initiate aync migration of user's key"); } bool Mount(const std::string& user_email, const std::string& passhash, int* error_code) { return chromeos::CryptohomeMountAllowFail(user_email.c_str(), passhash.c_str(), error_code); } bool AsyncMount(const std::string& user_email, const std::string& passhash, Delegate* d) { return CacheCallback( chromeos::CryptohomeAsyncMount(user_email.c_str(), passhash.c_str()), d, "Couldn't initiate async mount of cryptohome."); } bool MountForBwsi(int* error_code) { return chromeos::CryptohomeMountGuest(error_code); } bool AsyncMountForBwsi(Delegate* d) { return CacheCallback(chromeos::CryptohomeAsyncMountGuest(), d, "Couldn't initiate async mount of cryptohome."); } bool Remove(const std::string& user_email) { return chromeos::CryptohomeRemove(user_email.c_str()); } bool AsyncRemove(const std::string& user_email, Delegate* d) { return CacheCallback( chromeos::CryptohomeAsyncRemove(user_email.c_str()), d, "Couldn't initiate async removal of cryptohome."); } bool IsMounted() { return chromeos::CryptohomeIsMounted(); } CryptohomeBlob GetSystemSalt() { return chromeos::CryptohomeGetSystemSalt(); } private: static void Handler(const chromeos::CryptohomeAsyncCallStatus& event, void* cryptohome_library) { CryptohomeLibraryImpl* library = reinterpret_cast<CryptohomeLibraryImpl*>(cryptohome_library); library->Dispatch(event); } void Init() { cryptohome_connection_ = chromeos::CryptohomeMonitorSession(&Handler, this); } void Dispatch(const chromeos::CryptohomeAsyncCallStatus& event) { callback_map_[event.async_id]->OnComplete(event.return_status, event.return_code); callback_map_[event.async_id] = NULL; } bool CacheCallback(int async_id, Delegate* d, const char* error) { if (async_id == 0) { LOG(ERROR) << error; return false; } callback_map_[async_id] = d; return true; } typedef base::hash_map<int, Delegate*> CallbackMap; mutable CallbackMap callback_map_; void* cryptohome_connection_; DISALLOW_COPY_AND_ASSIGN(CryptohomeLibraryImpl); }; class CryptohomeLibraryStubImpl : public CryptohomeLibrary { public: CryptohomeLibraryStubImpl() {} virtual ~CryptohomeLibraryStubImpl() {} bool CheckKey(const std::string& user_email, const std::string& passhash) { return true; } bool AsyncCheckKey(const std::string& user_email, const std::string& passhash, Delegate* callback) { ChromeThread::PostTask( ChromeThread::UI, FROM_HERE, NewRunnableFunction(&DoStubCallback, callback)); return true; } bool MigrateKey(const std::string& user_email, const std::string& old_hash, const std::string& new_hash) { return true; } bool AsyncMigrateKey(const std::string& user_email, const std::string& old_hash, const std::string& new_hash, Delegate* callback) { ChromeThread::PostTask( ChromeThread::UI, FROM_HERE, NewRunnableFunction(&DoStubCallback, callback)); return true; } bool Remove(const std::string& user_email) { return true; } bool AsyncRemove(const std::string& user_email, Delegate* callback) { ChromeThread::PostTask( ChromeThread::UI, FROM_HERE, NewRunnableFunction(&DoStubCallback, callback)); return true; } bool Mount(const std::string& user_email, const std::string& passhash, int* error_code) { return true; } bool AsyncMount(const std::string& user_email, const std::string& passhash, Delegate* callback) { ChromeThread::PostTask( ChromeThread::UI, FROM_HERE, NewRunnableFunction(&DoStubCallback, callback)); return true; } bool MountForBwsi(int* error_code) { return true; } bool AsyncMountForBwsi(Delegate* callback) { ChromeThread::PostTask( ChromeThread::UI, FROM_HERE, NewRunnableFunction(&DoStubCallback, callback)); return true; } bool IsMounted() { return true; } CryptohomeBlob GetSystemSalt() { CryptohomeBlob salt = CryptohomeBlob(); salt.push_back(0); salt.push_back(0); return salt; } private: static void DoStubCallback(Delegate* callback) { callback->OnComplete(true, kCryptohomeMountErrorNone); } DISALLOW_COPY_AND_ASSIGN(CryptohomeLibraryStubImpl); }; // static CryptohomeLibrary* CryptohomeLibrary::GetImpl(bool stub) { if (stub) return new CryptohomeLibraryStubImpl(); else return new CryptohomeLibraryImpl(); } } // namespace chromeos <commit_msg>[Chrome OS] Update to use new CryptohomeAsyncMount function signature<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 "chrome/browser/chromeos/cros/cryptohome_library.h" #include "base/hash_tables.h" #include "base/message_loop.h" #include "chrome/browser/chrome_thread.h" #include "chrome/browser/chromeos/cros/cros_library.h" namespace chromeos { // This class handles the interaction with the ChromeOS cryptohome library APIs. class CryptohomeLibraryImpl : public CryptohomeLibrary { public: CryptohomeLibraryImpl() { if (CrosLibrary::Get()->EnsureLoaded()) Init(); } virtual ~CryptohomeLibraryImpl() {} bool CheckKey(const std::string& user_email, const std::string& passhash) { return chromeos::CryptohomeCheckKey(user_email.c_str(), passhash.c_str()); } bool AsyncCheckKey(const std::string& user_email, const std::string& passhash, Delegate* d) { return CacheCallback( chromeos::CryptohomeAsyncCheckKey(user_email.c_str(), passhash.c_str()), d, "Couldn't initiate async check of user's key."); } bool MigrateKey(const std::string& user_email, const std::string& old_hash, const std::string& new_hash) { return chromeos::CryptohomeMigrateKey(user_email.c_str(), old_hash.c_str(), new_hash.c_str()); } bool AsyncMigrateKey(const std::string& user_email, const std::string& old_hash, const std::string& new_hash, Delegate* d) { return CacheCallback( chromeos::CryptohomeAsyncMigrateKey(user_email.c_str(), old_hash.c_str(), new_hash.c_str()), d, "Couldn't initiate aync migration of user's key"); } bool Mount(const std::string& user_email, const std::string& passhash, int* error_code) { return chromeos::CryptohomeMountAllowFail(user_email.c_str(), passhash.c_str(), error_code); } bool AsyncMount(const std::string& user_email, const std::string& passhash, Delegate* d) { return CacheCallback( chromeos::CryptohomeAsyncMount(user_email.c_str(), passhash.c_str(), true, "", std::vector<std::string>()), d, "Couldn't initiate async mount of cryptohome."); } bool MountForBwsi(int* error_code) { return chromeos::CryptohomeMountGuest(error_code); } bool AsyncMountForBwsi(Delegate* d) { return CacheCallback(chromeos::CryptohomeAsyncMountGuest(), d, "Couldn't initiate async mount of cryptohome."); } bool Remove(const std::string& user_email) { return chromeos::CryptohomeRemove(user_email.c_str()); } bool AsyncRemove(const std::string& user_email, Delegate* d) { return CacheCallback( chromeos::CryptohomeAsyncRemove(user_email.c_str()), d, "Couldn't initiate async removal of cryptohome."); } bool IsMounted() { return chromeos::CryptohomeIsMounted(); } CryptohomeBlob GetSystemSalt() { return chromeos::CryptohomeGetSystemSalt(); } private: static void Handler(const chromeos::CryptohomeAsyncCallStatus& event, void* cryptohome_library) { CryptohomeLibraryImpl* library = reinterpret_cast<CryptohomeLibraryImpl*>(cryptohome_library); library->Dispatch(event); } void Init() { cryptohome_connection_ = chromeos::CryptohomeMonitorSession(&Handler, this); } void Dispatch(const chromeos::CryptohomeAsyncCallStatus& event) { callback_map_[event.async_id]->OnComplete(event.return_status, event.return_code); callback_map_[event.async_id] = NULL; } bool CacheCallback(int async_id, Delegate* d, const char* error) { if (async_id == 0) { LOG(ERROR) << error; return false; } callback_map_[async_id] = d; return true; } typedef base::hash_map<int, Delegate*> CallbackMap; mutable CallbackMap callback_map_; void* cryptohome_connection_; DISALLOW_COPY_AND_ASSIGN(CryptohomeLibraryImpl); }; class CryptohomeLibraryStubImpl : public CryptohomeLibrary { public: CryptohomeLibraryStubImpl() {} virtual ~CryptohomeLibraryStubImpl() {} bool CheckKey(const std::string& user_email, const std::string& passhash) { return true; } bool AsyncCheckKey(const std::string& user_email, const std::string& passhash, Delegate* callback) { ChromeThread::PostTask( ChromeThread::UI, FROM_HERE, NewRunnableFunction(&DoStubCallback, callback)); return true; } bool MigrateKey(const std::string& user_email, const std::string& old_hash, const std::string& new_hash) { return true; } bool AsyncMigrateKey(const std::string& user_email, const std::string& old_hash, const std::string& new_hash, Delegate* callback) { ChromeThread::PostTask( ChromeThread::UI, FROM_HERE, NewRunnableFunction(&DoStubCallback, callback)); return true; } bool Remove(const std::string& user_email) { return true; } bool AsyncRemove(const std::string& user_email, Delegate* callback) { ChromeThread::PostTask( ChromeThread::UI, FROM_HERE, NewRunnableFunction(&DoStubCallback, callback)); return true; } bool Mount(const std::string& user_email, const std::string& passhash, int* error_code) { return true; } bool AsyncMount(const std::string& user_email, const std::string& passhash, Delegate* callback) { ChromeThread::PostTask( ChromeThread::UI, FROM_HERE, NewRunnableFunction(&DoStubCallback, callback)); return true; } bool MountForBwsi(int* error_code) { return true; } bool AsyncMountForBwsi(Delegate* callback) { ChromeThread::PostTask( ChromeThread::UI, FROM_HERE, NewRunnableFunction(&DoStubCallback, callback)); return true; } bool IsMounted() { return true; } CryptohomeBlob GetSystemSalt() { CryptohomeBlob salt = CryptohomeBlob(); salt.push_back(0); salt.push_back(0); return salt; } private: static void DoStubCallback(Delegate* callback) { callback->OnComplete(true, kCryptohomeMountErrorNone); } DISALLOW_COPY_AND_ASSIGN(CryptohomeLibraryStubImpl); }; // static CryptohomeLibrary* CryptohomeLibrary::GetImpl(bool stub) { if (stub) return new CryptohomeLibraryStubImpl(); else return new CryptohomeLibraryImpl(); } } // namespace chromeos <|endoftext|>
<commit_before><commit_msg>Do not show network settings menu option for login. BUG=1683 TEST=none Review URL: http://codereview.chromium.org/793001<commit_after><|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 "chrome/browser/extensions/extension_tts_api.h" #include <atlbase.h> #include <atlcom.h> #include <sapi.h> #include "base/scoped_comptr_win.h" #include "base/singleton.h" #include "base/string_number_conversions.h" #include "base/utf_string_conversions.h" #include "base/values.h" namespace util = extension_tts_api_util; class ExtensionTtsPlatformImplWin : public ExtensionTtsPlatformImpl { public: virtual bool Speak( const std::string& utterance, const std::string& language, const std::string& gender, double rate, double pitch, double volume); virtual bool StopSpeaking(); virtual bool IsSpeaking(); // Get the single instance of this class. static ExtensionTtsPlatformImplWin* GetInstance(); private: ExtensionTtsPlatformImplWin(); virtual ~ExtensionTtsPlatformImplWin() {} ScopedComPtr<ISpVoice> speech_synthesizer_; bool paused_; friend struct DefaultSingletonTraits<ExtensionTtsPlatformImplWin>; DISALLOW_COPY_AND_ASSIGN(ExtensionTtsPlatformImplWin); }; // static ExtensionTtsPlatformImpl* ExtensionTtsPlatformImpl::GetInstance() { return ExtensionTtsPlatformImplWin::GetInstance(); } bool ExtensionTtsPlatformImplWin::Speak( const std::string& src_utterance, const std::string& language, const std::string& gender, double rate, double pitch, double volume) { std::wstring utterance = UTF8ToUTF16(src_utterance); if (!speech_synthesizer_) return false; // Speech API equivalents for kGenderKey and kLanguageNameKey do not // exist and thus are not supported. if (rate >= 0.0) { // The TTS api allows a range of -10 to 10 for speech rate. speech_synthesizer_->SetRate(static_cast<int32>(rate * 20 - 10)); } if (pitch >= 0.0) { // The TTS api allows a range of -10 to 10 for speech pitch. // TODO(dtseng): cleanup if we ever use any other properties that // require xml. std::wstring pitch_value = base::IntToString16(static_cast<int>(pitch * 20 - 10)); utterance = L"<pitch absmiddle=\"" + pitch_value + L"\">" + utterance + L"</pitch>"; } if (volume >= 0.0) { // The TTS api allows a range of 0 to 100 for speech volume. speech_synthesizer_->SetVolume(static_cast<uint16>(volume * 100)); } if (paused_) { speech_synthesizer_->Resume(); paused_ = false; } speech_synthesizer_->Speak( utterance.c_str(), SPF_ASYNC | SPF_PURGEBEFORESPEAK, NULL); return true; } bool ExtensionTtsPlatformImplWin::StopSpeaking() { if (speech_synthesizer_ && !paused_) { speech_synthesizer_->Pause(); paused_ = true; } return true; } bool ExtensionTtsPlatformImplWin::IsSpeaking() { if (speech_synthesizer_ && !paused_) { SPVOICESTATUS status; HRESULT result = speech_synthesizer_->GetStatus(&status, NULL); if (result == S_OK && status.dwRunningState == SPRS_IS_SPEAKING) return true; } return false; } ExtensionTtsPlatformImplWin::ExtensionTtsPlatformImplWin() : speech_synthesizer_(NULL), paused_(false) { CoCreateInstance( CLSID_SpVoice, NULL, CLSCTX_SERVER, IID_ISpVoice, reinterpret_cast<void**>(&speech_synthesizer_)); } // static ExtensionTtsPlatformImplWin* ExtensionTtsPlatformImplWin::GetInstance() { return Singleton<ExtensionTtsPlatformImplWin>::get(); } <commit_msg>Another Windows TTS fix; handle the case where we call GetStatus while it's still waiting to speak.<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 "chrome/browser/extensions/extension_tts_api.h" #include <atlbase.h> #include <atlcom.h> #include <sapi.h> #include "base/scoped_comptr_win.h" #include "base/singleton.h" #include "base/string_number_conversions.h" #include "base/utf_string_conversions.h" #include "base/values.h" namespace util = extension_tts_api_util; class ExtensionTtsPlatformImplWin : public ExtensionTtsPlatformImpl { public: virtual bool Speak( const std::string& utterance, const std::string& language, const std::string& gender, double rate, double pitch, double volume); virtual bool StopSpeaking(); virtual bool IsSpeaking(); // Get the single instance of this class. static ExtensionTtsPlatformImplWin* GetInstance(); private: ExtensionTtsPlatformImplWin(); virtual ~ExtensionTtsPlatformImplWin() {} ScopedComPtr<ISpVoice> speech_synthesizer_; bool paused_; friend struct DefaultSingletonTraits<ExtensionTtsPlatformImplWin>; DISALLOW_COPY_AND_ASSIGN(ExtensionTtsPlatformImplWin); }; // static ExtensionTtsPlatformImpl* ExtensionTtsPlatformImpl::GetInstance() { return ExtensionTtsPlatformImplWin::GetInstance(); } bool ExtensionTtsPlatformImplWin::Speak( const std::string& src_utterance, const std::string& language, const std::string& gender, double rate, double pitch, double volume) { std::wstring utterance = UTF8ToUTF16(src_utterance); if (!speech_synthesizer_) return false; // Speech API equivalents for kGenderKey and kLanguageNameKey do not // exist and thus are not supported. if (rate >= 0.0) { // The TTS api allows a range of -10 to 10 for speech rate. speech_synthesizer_->SetRate(static_cast<int32>(rate * 20 - 10)); } if (pitch >= 0.0) { // The TTS api allows a range of -10 to 10 for speech pitch. // TODO(dtseng): cleanup if we ever use any other properties that // require xml. std::wstring pitch_value = base::IntToString16(static_cast<int>(pitch * 20 - 10)); utterance = L"<pitch absmiddle=\"" + pitch_value + L"\">" + utterance + L"</pitch>"; } if (volume >= 0.0) { // The TTS api allows a range of 0 to 100 for speech volume. speech_synthesizer_->SetVolume(static_cast<uint16>(volume * 100)); } if (paused_) { speech_synthesizer_->Resume(); paused_ = false; } speech_synthesizer_->Speak( utterance.c_str(), SPF_ASYNC | SPF_PURGEBEFORESPEAK, NULL); return true; } bool ExtensionTtsPlatformImplWin::StopSpeaking() { if (speech_synthesizer_ && !paused_) { speech_synthesizer_->Pause(); paused_ = true; } return true; } bool ExtensionTtsPlatformImplWin::IsSpeaking() { if (speech_synthesizer_ && !paused_) { SPVOICESTATUS status; HRESULT result = speech_synthesizer_->GetStatus(&status, NULL); if (result == S_OK) { if (status.dwRunningState == 0 || // 0 == waiting to speak status.dwRunningState == SPRS_IS_SPEAKING) { return true; } } } return false; } ExtensionTtsPlatformImplWin::ExtensionTtsPlatformImplWin() : speech_synthesizer_(NULL), paused_(false) { CoCreateInstance( CLSID_SpVoice, NULL, CLSCTX_SERVER, IID_ISpVoice, reinterpret_cast<void**>(&speech_synthesizer_)); } // static ExtensionTtsPlatformImplWin* ExtensionTtsPlatformImplWin::GetInstance() { return Singleton<ExtensionTtsPlatformImplWin>::get(); } <|endoftext|>
<commit_before>// Copyright (c) 2012 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/first_run/try_chrome_dialog_view.h" #include <shellapi.h> #include "base/logging.h" #include "base/message_loop.h" #include "base/string16.h" #include "chrome/browser/process_singleton.h" #include "chrome/installer/util/browser_distribution.h" #include "grit/chromium_strings.h" #include "grit/generated_resources.h" #include "grit/theme_resources.h" #include "grit/ui_resources.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/resource/resource_bundle.h" #include "ui/gfx/image/image.h" #include "ui/views/controls/button/checkbox.h" #include "ui/views/controls/button/image_button.h" #include "ui/views/controls/button/radio_button.h" #include "ui/views/controls/button/text_button.h" #include "ui/views/controls/image_view.h" #include "ui/views/controls/link.h" #include "ui/views/layout/grid_layout.h" #include "ui/views/layout/layout_constants.h" #include "ui/views/widget/widget.h" namespace { const wchar_t kHelpCenterUrl[] = L"https://www.google.com/support/chrome/bin/answer.py?answer=150752"; enum ButtonTags { BT_NONE, BT_CLOSE_BUTTON, BT_OK_BUTTON, BT_TRY_IT_RADIO, BT_DONT_BUG_RADIO }; } // namespace // static TryChromeDialogView::Result TryChromeDialogView::Show( size_t flavor, ProcessSingleton* process_singleton) { if (flavor > 10000) { // This is a test value. We want to make sure we exercise // returning this early. See TryChromeDialogBrowserTest test. return NOT_NOW; } TryChromeDialogView dialog(flavor); return dialog.ShowModal(process_singleton); } TryChromeDialogView::TryChromeDialogView(size_t flavor) : flavor_(flavor), popup_(NULL), try_chrome_(NULL), kill_chrome_(NULL), dont_try_chrome_(NULL), make_default_(NULL), result_(COUNT) { } TryChromeDialogView::~TryChromeDialogView() { } TryChromeDialogView::Result TryChromeDialogView::ShowModal( ProcessSingleton* process_singleton) { ResourceBundle& rb = ResourceBundle::GetSharedInstance(); views::ImageView* icon = new views::ImageView(); icon->SetImage(rb.GetNativeImageNamed(IDR_PRODUCT_LOGO_32).ToImageSkia()); gfx::Size icon_size = icon->GetPreferredSize(); // An approximate window size. After Layout() we'll get better bounds. popup_ = new views::Widget; if (!popup_) { NOTREACHED(); return DIALOG_ERROR; } views::Widget::InitParams params(views::Widget::InitParams::TYPE_POPUP); params.can_activate = true; params.bounds = gfx::Rect(310, 160); popup_->Init(params); views::View* root_view = popup_->GetRootView(); // The window color is a tiny bit off-white. root_view->set_background( views::Background::CreateSolidBackground(0xfc, 0xfc, 0xfc)); views::GridLayout* layout = views::GridLayout::CreatePanel(root_view); if (!layout) { NOTREACHED(); return DIALOG_ERROR; } root_view->SetLayoutManager(layout); views::ColumnSet* columns; // First row: [icon][pad][text][button]. columns = layout->AddColumnSet(0); columns->AddColumn(views::GridLayout::LEADING, views::GridLayout::LEADING, 0, views::GridLayout::FIXED, icon_size.width(), icon_size.height()); columns->AddPaddingColumn(0, views::kRelatedControlHorizontalSpacing); columns->AddColumn(views::GridLayout::FILL, views::GridLayout::FILL, 1, views::GridLayout::USE_PREF, 0, 0); columns->AddColumn(views::GridLayout::TRAILING, views::GridLayout::FILL, 1, views::GridLayout::USE_PREF, 0, 0); // Optional second row: [pad][pad][radio 1]. columns = layout->AddColumnSet(1); columns->AddPaddingColumn(0, icon_size.width()); columns->AddPaddingColumn(0, views::kRelatedControlHorizontalSpacing); columns->AddColumn(views::GridLayout::LEADING, views::GridLayout::FILL, 1, views::GridLayout::USE_PREF, 0, 0); // Third row: [pad][pad][radio 2]. columns = layout->AddColumnSet(2); columns->AddPaddingColumn(0, icon_size.width()); columns->AddPaddingColumn(0, views::kRelatedControlHorizontalSpacing); columns->AddColumn(views::GridLayout::LEADING, views::GridLayout::FILL, 1, views::GridLayout::USE_PREF, 0, 0); // Fourth row: [pad][pad][button][pad][button]. columns = layout->AddColumnSet(3); columns->AddPaddingColumn(0, icon_size.width()); columns->AddColumn(views::GridLayout::LEADING, views::GridLayout::FILL, 0, views::GridLayout::USE_PREF, 0, 0); columns->AddPaddingColumn(0, views::kRelatedButtonHSpacing); columns->AddColumn(views::GridLayout::LEADING, views::GridLayout::FILL, 0, views::GridLayout::USE_PREF, 0, 0); // Fifth row: [pad][pad][link]. columns = layout->AddColumnSet(4); columns->AddPaddingColumn(0, icon_size.width()); columns->AddPaddingColumn(0, views::kRelatedControlHorizontalSpacing); columns->AddColumn(views::GridLayout::LEADING, views::GridLayout::FILL, 1, views::GridLayout::USE_PREF, 0, 0); // Optional fourth row: [button]. columns = layout->AddColumnSet(5); columns->AddColumn(views::GridLayout::CENTER, views::GridLayout::FILL, 1, views::GridLayout::USE_PREF, 0, 0); // Optional fourth row: [pad][pad][checkbox]. columns = layout->AddColumnSet(6); columns->AddPaddingColumn(0, icon_size.width()); columns->AddPaddingColumn(0, views::kRelatedControlHorizontalSpacing + views::kPanelHorizIndentation); columns->AddColumn(views::GridLayout::LEADING, views::GridLayout::FILL, 1, views::GridLayout::USE_PREF, 0, 0); // First row views. layout->StartRow(0, 0); layout->AddView(icon); // Find out what experiment we are conducting. BrowserDistribution* dist = BrowserDistribution::GetDistribution(); if (!dist) { NOTREACHED() << "Cannot determine browser distribution"; return DIALOG_ERROR; } BrowserDistribution::UserExperiment experiment; if (!dist->GetExperimentDetails(&experiment, flavor_) || !experiment.heading) { NOTREACHED() << "Cannot determine which headline to show."; return DIALOG_ERROR; } string16 heading = l10n_util::GetStringUTF16(experiment.heading); views::Label* label = new views::Label(heading); label->SetFont(rb.GetFont(ResourceBundle::MediumBoldFont)); label->SetMultiLine(true); label->SizeToFit(200); label->SetHorizontalAlignment(views::Label::ALIGN_LEFT); layout->AddView(label); // The close button is custom. views::ImageButton* close_button = new views::ImageButton(this); close_button->SetImage(views::CustomButton::BS_NORMAL, rb.GetNativeImageNamed(IDR_CLOSE_BAR).ToImageSkia()); close_button->SetImage(views::CustomButton::BS_HOT, rb.GetNativeImageNamed(IDR_CLOSE_BAR_H).ToImageSkia()); close_button->SetImage(views::CustomButton::BS_PUSHED, rb.GetNativeImageNamed(IDR_CLOSE_BAR_P).ToImageSkia()); close_button->set_tag(BT_CLOSE_BUTTON); layout->AddView(close_button); // Second row views. const string16 try_it(l10n_util::GetStringUTF16(IDS_TRY_TOAST_TRY_OPT)); layout->StartRowWithPadding(0, 1, 0, 10); try_chrome_ = new views::RadioButton(try_it, 1); try_chrome_->SetChecked(true); try_chrome_->set_tag(BT_TRY_IT_RADIO); try_chrome_->set_listener(this); layout->AddView(try_chrome_); // Decide if the don't bug me is a button or a radio button. bool dont_bug_me_button = ((experiment.flags & BrowserDistribution::kDontBugMeAsButton) != 0); // Optional third and fourth row views. if (!dont_bug_me_button) { layout->StartRow(0, 1); const string16 decline(l10n_util::GetStringUTF16(IDS_TRY_TOAST_CANCEL)); dont_try_chrome_ = new views::RadioButton(decline, 1); dont_try_chrome_->set_tag(BT_DONT_BUG_RADIO); dont_try_chrome_->set_listener(this); layout->AddView(dont_try_chrome_); } if (experiment.flags & BrowserDistribution::kUninstall) { layout->StartRow(0, 2); const string16 kill_it(l10n_util::GetStringUTF16(IDS_UNINSTALL_CHROME)); kill_chrome_ = new views::RadioButton(kill_it, 1); layout->AddView(kill_chrome_); } if (experiment.flags & BrowserDistribution::kMakeDefault) { layout->StartRow(0, 6); const string16 default_text( l10n_util::GetStringUTF16(IDS_TRY_TOAST_SET_DEFAULT)); make_default_ = new views::Checkbox(default_text); gfx::Font font = make_default_->font().DeriveFont(0, gfx::Font::ITALIC); make_default_->SetFont(font); make_default_->SetChecked(true); layout->AddView(make_default_); } // Button row, the last or next to last depending on the 'why?' link. const string16 ok_it(l10n_util::GetStringUTF16(IDS_OK)); views::Button* accept_button = new views::NativeTextButton(this, ok_it); accept_button->set_tag(BT_OK_BUTTON); layout->StartRowWithPadding(0, dont_bug_me_button ? 3 : 5, 0, 10); layout->AddView(accept_button); if (dont_bug_me_button) { // The bubble needs a "Don't bug me" as a button or as a radio button, this // this the button case. const string16 cancel_it(l10n_util::GetStringUTF16(IDS_TRY_TOAST_CANCEL)); views::Button* cancel_button = new views::NativeTextButton(this, cancel_it); cancel_button->set_tag(BT_CLOSE_BUTTON); layout->AddView(cancel_button); } if (experiment.flags & BrowserDistribution::kWhyLink) { layout->StartRowWithPadding(0, 4, 0, 10); const string16 why_this(l10n_util::GetStringUTF16(IDS_TRY_TOAST_WHY)); views::Link* link = new views::Link(why_this); link->set_listener(this); layout->AddView(link); } // We resize the window according to the layout manager. This takes into // account the differences between XP and Vista fonts and buttons. layout->Layout(root_view); gfx::Size preferred = layout->GetPreferredSize(root_view); gfx::Rect pos = ComputeWindowPosition(preferred.width(), preferred.height(), base::i18n::IsRTL()); popup_->SetBounds(pos); // Carve the toast shape into the window. SetToastRegion(popup_->GetNativeView(), preferred.width(), preferred.height()); // Time to show the window in a modal loop. The ProcessSingleton should // already be locked and it will not process WM_COPYDATA requests. Change the // window to bring to foreground if a request arrives. CHECK(process_singleton->locked()); process_singleton->SetForegroundWindow(popup_->GetNativeView()); popup_->Show(); MessageLoop::current()->Run(); process_singleton->SetForegroundWindow(NULL); return result_; } gfx::Rect TryChromeDialogView::ComputeWindowPosition(int width, int height, bool is_RTL) { // The 'Shell_TrayWnd' is the taskbar. We like to show our window in that // monitor if we can. This code works even if such window is not found. HWND taskbar = ::FindWindowW(L"Shell_TrayWnd", NULL); HMONITOR monitor = ::MonitorFromWindow(taskbar, MONITOR_DEFAULTTOPRIMARY); MONITORINFO info = {sizeof(info)}; if (!GetMonitorInfoW(monitor, &info)) { // Quite unexpected. Do a best guess at a visible rectangle. return gfx::Rect(20, 20, width + 20, height + 20); } // The |rcWork| is the work area. It should account for the taskbars that // are in the screen when we called the function. int left = is_RTL ? info.rcWork.left : info.rcWork.right - width; int top = info.rcWork.bottom - height; return gfx::Rect(left, top, width, height); } void TryChromeDialogView::SetToastRegion(HWND window, int w, int h) { static const POINT polygon[] = { {0, 4}, {1, 2}, {2, 1}, {4, 0}, // Left side. {w-4, 0}, {w-2, 1}, {w-1, 2}, {w, 4}, // Right side. {w, h}, {0, h} }; HRGN region = ::CreatePolygonRgn(polygon, arraysize(polygon), WINDING); ::SetWindowRgn(window, region, FALSE); } void TryChromeDialogView::ButtonPressed(views::Button* sender, const ui::Event& event) { if (sender->tag() == BT_DONT_BUG_RADIO) { if (make_default_) { make_default_->SetChecked(false); make_default_->SetState(views::CustomButton::BS_DISABLED); } return; } else if (sender->tag() == BT_TRY_IT_RADIO) { if (make_default_) { make_default_->SetChecked(true); make_default_->SetState(views::CustomButton::BS_NORMAL); } return; } else if (sender->tag() == BT_CLOSE_BUTTON) { // The user pressed cancel or the [x] button. result_ = NOT_NOW; } else if (!try_chrome_) { // We don't have radio buttons, the user pressed ok. result_ = TRY_CHROME; } else { // The outcome is according to the selected radio button. if (try_chrome_->checked()) result_ = TRY_CHROME; else if (dont_try_chrome_ && dont_try_chrome_->checked()) result_ = NOT_NOW; else if (kill_chrome_ && kill_chrome_->checked()) result_ = UNINSTALL_CHROME; else NOTREACHED() << "Unknown radio button selected"; } if (make_default_) { if ((result_ == TRY_CHROME) && make_default_->checked()) result_ = TRY_CHROME_AS_DEFAULT; } popup_->Close(); MessageLoop::current()->Quit(); } void TryChromeDialogView::LinkClicked(views::Link* source, int event_flags) { ::ShellExecuteW(NULL, L"open", kHelpCenterUrl, NULL, NULL, SW_SHOW); } <commit_msg>first_run: Avoid some unnecessary temp variables in TryChromeDialogView.<commit_after>// Copyright (c) 2012 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/first_run/try_chrome_dialog_view.h" #include <shellapi.h> #include "base/logging.h" #include "base/message_loop.h" #include "base/string16.h" #include "chrome/browser/process_singleton.h" #include "chrome/installer/util/browser_distribution.h" #include "grit/chromium_strings.h" #include "grit/generated_resources.h" #include "grit/theme_resources.h" #include "grit/ui_resources.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/resource/resource_bundle.h" #include "ui/gfx/image/image.h" #include "ui/views/controls/button/checkbox.h" #include "ui/views/controls/button/image_button.h" #include "ui/views/controls/button/radio_button.h" #include "ui/views/controls/button/text_button.h" #include "ui/views/controls/image_view.h" #include "ui/views/controls/link.h" #include "ui/views/layout/grid_layout.h" #include "ui/views/layout/layout_constants.h" #include "ui/views/widget/widget.h" namespace { const wchar_t kHelpCenterUrl[] = L"https://www.google.com/support/chrome/bin/answer.py?answer=150752"; enum ButtonTags { BT_NONE, BT_CLOSE_BUTTON, BT_OK_BUTTON, BT_TRY_IT_RADIO, BT_DONT_BUG_RADIO }; const int kRadioGroupID = 1; } // namespace // static TryChromeDialogView::Result TryChromeDialogView::Show( size_t flavor, ProcessSingleton* process_singleton) { if (flavor > 10000) { // This is a test value. We want to make sure we exercise // returning this early. See TryChromeDialogBrowserTest test. return NOT_NOW; } TryChromeDialogView dialog(flavor); return dialog.ShowModal(process_singleton); } TryChromeDialogView::TryChromeDialogView(size_t flavor) : flavor_(flavor), popup_(NULL), try_chrome_(NULL), kill_chrome_(NULL), dont_try_chrome_(NULL), make_default_(NULL), result_(COUNT) { } TryChromeDialogView::~TryChromeDialogView() { } TryChromeDialogView::Result TryChromeDialogView::ShowModal( ProcessSingleton* process_singleton) { ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance(); views::ImageView* icon = new views::ImageView(); icon->SetImage(rb.GetNativeImageNamed(IDR_PRODUCT_LOGO_32).ToImageSkia()); gfx::Size icon_size = icon->GetPreferredSize(); // An approximate window size. After Layout() we'll get better bounds. popup_ = new views::Widget; if (!popup_) { NOTREACHED(); return DIALOG_ERROR; } views::Widget::InitParams params(views::Widget::InitParams::TYPE_POPUP); params.can_activate = true; params.bounds = gfx::Rect(310, 160); popup_->Init(params); views::View* root_view = popup_->GetRootView(); // The window color is a tiny bit off-white. root_view->set_background( views::Background::CreateSolidBackground(0xfc, 0xfc, 0xfc)); views::GridLayout* layout = views::GridLayout::CreatePanel(root_view); if (!layout) { NOTREACHED(); return DIALOG_ERROR; } root_view->SetLayoutManager(layout); views::ColumnSet* columns; // First row: [icon][pad][text][button]. columns = layout->AddColumnSet(0); columns->AddColumn(views::GridLayout::LEADING, views::GridLayout::LEADING, 0, views::GridLayout::FIXED, icon_size.width(), icon_size.height()); columns->AddPaddingColumn(0, views::kRelatedControlHorizontalSpacing); columns->AddColumn(views::GridLayout::FILL, views::GridLayout::FILL, 1, views::GridLayout::USE_PREF, 0, 0); columns->AddColumn(views::GridLayout::TRAILING, views::GridLayout::FILL, 1, views::GridLayout::USE_PREF, 0, 0); // Optional second row: [pad][pad][radio 1]. columns = layout->AddColumnSet(1); columns->AddPaddingColumn(0, icon_size.width()); columns->AddPaddingColumn(0, views::kRelatedControlHorizontalSpacing); columns->AddColumn(views::GridLayout::LEADING, views::GridLayout::FILL, 1, views::GridLayout::USE_PREF, 0, 0); // Third row: [pad][pad][radio 2]. columns = layout->AddColumnSet(2); columns->AddPaddingColumn(0, icon_size.width()); columns->AddPaddingColumn(0, views::kRelatedControlHorizontalSpacing); columns->AddColumn(views::GridLayout::LEADING, views::GridLayout::FILL, 1, views::GridLayout::USE_PREF, 0, 0); // Fourth row: [pad][pad][button][pad][button]. columns = layout->AddColumnSet(3); columns->AddPaddingColumn(0, icon_size.width()); columns->AddColumn(views::GridLayout::LEADING, views::GridLayout::FILL, 0, views::GridLayout::USE_PREF, 0, 0); columns->AddPaddingColumn(0, views::kRelatedButtonHSpacing); columns->AddColumn(views::GridLayout::LEADING, views::GridLayout::FILL, 0, views::GridLayout::USE_PREF, 0, 0); // Fifth row: [pad][pad][link]. columns = layout->AddColumnSet(4); columns->AddPaddingColumn(0, icon_size.width()); columns->AddPaddingColumn(0, views::kRelatedControlHorizontalSpacing); columns->AddColumn(views::GridLayout::LEADING, views::GridLayout::FILL, 1, views::GridLayout::USE_PREF, 0, 0); // Optional fourth row: [button]. columns = layout->AddColumnSet(5); columns->AddColumn(views::GridLayout::CENTER, views::GridLayout::FILL, 1, views::GridLayout::USE_PREF, 0, 0); // Optional fourth row: [pad][pad][checkbox]. columns = layout->AddColumnSet(6); columns->AddPaddingColumn(0, icon_size.width()); columns->AddPaddingColumn(0, views::kRelatedControlHorizontalSpacing + views::kPanelHorizIndentation); columns->AddColumn(views::GridLayout::LEADING, views::GridLayout::FILL, 1, views::GridLayout::USE_PREF, 0, 0); // First row. layout->StartRow(0, 0); layout->AddView(icon); // Find out what experiment we are conducting. BrowserDistribution* dist = BrowserDistribution::GetDistribution(); if (!dist) { NOTREACHED() << "Cannot determine browser distribution"; return DIALOG_ERROR; } BrowserDistribution::UserExperiment experiment; if (!dist->GetExperimentDetails(&experiment, flavor_) || !experiment.heading) { NOTREACHED() << "Cannot determine which headline to show."; return DIALOG_ERROR; } views::Label* label = new views::Label( l10n_util::GetStringUTF16(experiment.heading)); label->SetFont(rb.GetFont(ui::ResourceBundle::MediumBoldFont)); label->SetMultiLine(true); label->SizeToFit(200); label->SetHorizontalAlignment(views::Label::ALIGN_LEFT); layout->AddView(label); // The close button is custom. views::ImageButton* close_button = new views::ImageButton(this); close_button->SetImage(views::CustomButton::BS_NORMAL, rb.GetNativeImageNamed(IDR_CLOSE_BAR).ToImageSkia()); close_button->SetImage(views::CustomButton::BS_HOT, rb.GetNativeImageNamed(IDR_CLOSE_BAR_H).ToImageSkia()); close_button->SetImage(views::CustomButton::BS_PUSHED, rb.GetNativeImageNamed(IDR_CLOSE_BAR_P).ToImageSkia()); close_button->set_tag(BT_CLOSE_BUTTON); layout->AddView(close_button); // Second row. layout->StartRowWithPadding(0, 1, 0, 10); try_chrome_ = new views::RadioButton( l10n_util::GetStringUTF16(IDS_TRY_TOAST_TRY_OPT), kRadioGroupID); try_chrome_->SetChecked(true); try_chrome_->set_tag(BT_TRY_IT_RADIO); try_chrome_->set_listener(this); layout->AddView(try_chrome_); // Decide if the don't bug me is a button or a radio button. bool dont_bug_me_button = ((experiment.flags & BrowserDistribution::kDontBugMeAsButton) != 0); // Optional third and fourth row. if (!dont_bug_me_button) { layout->StartRow(0, 1); dont_try_chrome_ = new views::RadioButton( l10n_util::GetStringUTF16(IDS_TRY_TOAST_CANCEL), kRadioGroupID); dont_try_chrome_->set_tag(BT_DONT_BUG_RADIO); dont_try_chrome_->set_listener(this); layout->AddView(dont_try_chrome_); } if (experiment.flags & BrowserDistribution::kUninstall) { layout->StartRow(0, 2); kill_chrome_ = new views::RadioButton( l10n_util::GetStringUTF16(IDS_UNINSTALL_CHROME), kRadioGroupID); layout->AddView(kill_chrome_); } if (experiment.flags & BrowserDistribution::kMakeDefault) { layout->StartRow(0, 6); make_default_ = new views::Checkbox( l10n_util::GetStringUTF16(IDS_TRY_TOAST_SET_DEFAULT)); make_default_->SetFont( make_default_->font().DeriveFont(0, gfx::Font::ITALIC)); make_default_->SetChecked(true); layout->AddView(make_default_); } // Button row, the last or next to last depending on the 'why?' link. views::Button* accept_button = new views::NativeTextButton( this, l10n_util::GetStringUTF16(IDS_OK)); accept_button->set_tag(BT_OK_BUTTON); layout->StartRowWithPadding(0, dont_bug_me_button ? 3 : 5, 0, 10); layout->AddView(accept_button); if (dont_bug_me_button) { // The bubble needs a "Don't bug me" as a button or as a radio button, this // this the button case. views::Button* cancel_button = new views::NativeTextButton( this, l10n_util::GetStringUTF16(IDS_TRY_TOAST_CANCEL)); cancel_button->set_tag(BT_CLOSE_BUTTON); layout->AddView(cancel_button); } if (experiment.flags & BrowserDistribution::kWhyLink) { layout->StartRowWithPadding(0, 4, 0, 10); views::Link* link = new views::Link( l10n_util::GetStringUTF16(IDS_TRY_TOAST_WHY)); link->set_listener(this); layout->AddView(link); } // We resize the window according to the layout manager. This takes into // account the differences between XP and Vista fonts and buttons. layout->Layout(root_view); gfx::Size preferred = layout->GetPreferredSize(root_view); gfx::Rect pos = ComputeWindowPosition(preferred.width(), preferred.height(), base::i18n::IsRTL()); popup_->SetBounds(pos); // Carve the toast shape into the window. SetToastRegion(popup_->GetNativeView(), preferred.width(), preferred.height()); // Time to show the window in a modal loop. The ProcessSingleton should // already be locked and it will not process WM_COPYDATA requests. Change the // window to bring to foreground if a request arrives. CHECK(process_singleton->locked()); process_singleton->SetForegroundWindow(popup_->GetNativeView()); popup_->Show(); MessageLoop::current()->Run(); process_singleton->SetForegroundWindow(NULL); return result_; } gfx::Rect TryChromeDialogView::ComputeWindowPosition(int width, int height, bool is_RTL) { // The 'Shell_TrayWnd' is the taskbar. We like to show our window in that // monitor if we can. This code works even if such window is not found. HWND taskbar = ::FindWindowW(L"Shell_TrayWnd", NULL); HMONITOR monitor = ::MonitorFromWindow(taskbar, MONITOR_DEFAULTTOPRIMARY); MONITORINFO info = {sizeof(info)}; if (!GetMonitorInfoW(monitor, &info)) { // Quite unexpected. Do a best guess at a visible rectangle. return gfx::Rect(20, 20, width + 20, height + 20); } // The |rcWork| is the work area. It should account for the taskbars that // are in the screen when we called the function. int left = is_RTL ? info.rcWork.left : info.rcWork.right - width; int top = info.rcWork.bottom - height; return gfx::Rect(left, top, width, height); } void TryChromeDialogView::SetToastRegion(HWND window, int w, int h) { static const POINT polygon[] = { {0, 4}, {1, 2}, {2, 1}, {4, 0}, // Left side. {w-4, 0}, {w-2, 1}, {w-1, 2}, {w, 4}, // Right side. {w, h}, {0, h} }; HRGN region = ::CreatePolygonRgn(polygon, arraysize(polygon), WINDING); ::SetWindowRgn(window, region, FALSE); } void TryChromeDialogView::ButtonPressed(views::Button* sender, const ui::Event& event) { if (sender->tag() == BT_DONT_BUG_RADIO) { if (make_default_) { make_default_->SetChecked(false); make_default_->SetState(views::CustomButton::BS_DISABLED); } return; } else if (sender->tag() == BT_TRY_IT_RADIO) { if (make_default_) { make_default_->SetChecked(true); make_default_->SetState(views::CustomButton::BS_NORMAL); } return; } else if (sender->tag() == BT_CLOSE_BUTTON) { // The user pressed cancel or the [x] button. result_ = NOT_NOW; } else if (!try_chrome_) { // We don't have radio buttons, the user pressed ok. result_ = TRY_CHROME; } else { // The outcome is according to the selected radio button. if (try_chrome_->checked()) result_ = TRY_CHROME; else if (dont_try_chrome_ && dont_try_chrome_->checked()) result_ = NOT_NOW; else if (kill_chrome_ && kill_chrome_->checked()) result_ = UNINSTALL_CHROME; else NOTREACHED() << "Unknown radio button selected"; } if (make_default_) { if ((result_ == TRY_CHROME) && make_default_->checked()) result_ = TRY_CHROME_AS_DEFAULT; } popup_->Close(); MessageLoop::current()->Quit(); } void TryChromeDialogView::LinkClicked(views::Link* source, int event_flags) { ::ShellExecuteW(NULL, L"open", kHelpCenterUrl, NULL, NULL, SW_SHOW); } <|endoftext|>
<commit_before><commit_msg>Make more things clickable in the bookmark bar menus:<commit_after><|endoftext|>
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Copyright (c) 2010, Intel Corporation. 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/meegotouch/js_modal_dialog_qt.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/message_box_flags.h" #include "base/logging.h" #include "base/utf_string_conversions.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/browser_list.h" #include "chrome/browser/ui/meegotouch/qt_util.h" #include "chrome/browser/ui/app_modal_dialogs/js_modal_dialog.h" #include "grit/generated_resources.h" #include "grit/locale_settings.h" /*************************************************************************** * JSModalDialogQt */ JSModalDialogQt::JSModalDialogQt(JavaScriptAppModalDialog* dialog, gfx::NativeWindow parent_window) : jsDialog_(dialog) { int flag = jsDialog_->dialog_flags(); DialogQt::DLG_TYPE type; if(flag == ui::MessageBoxFlags::kIsJavascriptAlert) { type = DialogQt::DLG_ALERT; } else if (flag == ui::MessageBoxFlags::kIsJavascriptConfirm) { type = DialogQt::DLG_CONFIRM; } else if (flag == ui::MessageBoxFlags::kIsJavascriptPrompt) { type = DialogQt::DLG_PROMPT; } else { type = DialogQt::DLG_ALERT; } qDlgModel_ = new DialogQtModel(type, jsDialog_->display_suppress_checkbox(), WideToUTF8(jsDialog_->title()).c_str(), WideToUTF8(jsDialog_->message_text()).c_str(), WideToUTF8(jsDialog_->default_prompt_text()).c_str(), jsDialog_->is_before_unload_dialog()); } JSModalDialogQt::~JSModalDialogQt() { delete qDlgModel_; } int JSModalDialogQt::GetAppModalDialogButtons() const { switch (jsDialog_->dialog_flags()) { case ui::MessageBoxFlags::kIsJavascriptAlert: return ui::MessageBoxFlags::DIALOGBUTTON_OK; case ui::MessageBoxFlags::kIsJavascriptConfirm: return ui::MessageBoxFlags::DIALOGBUTTON_OK | ui::MessageBoxFlags::DIALOGBUTTON_CANCEL; case ui::MessageBoxFlags::kIsJavascriptPrompt: return ui::MessageBoxFlags::DIALOGBUTTON_OK; default: NOTREACHED(); return 0; } } void JSModalDialogQt::ShowAppModalDialog() { Browser* browser = BrowserList::GetLastActive(); BrowserWindowQt* browser_window = (BrowserWindowQt*)browser->window(); browser_window->ShowDialog(qDlgModel_, this); } void JSModalDialogQt::ActivateAppModalDialog() { //qDlg_->activateWindow(); //qDlg_->raise(); } void JSModalDialogQt::CloseAppModalDialog() { HandleDialogResponse(DialogQt::Rejected, NULL); } void JSModalDialogQt::AcceptAppModalDialog() { HandleDialogResponse(DialogQt::Accepted, NULL); } void JSModalDialogQt::CancelAppModalDialog() { HandleDialogResponse(DialogQt::Rejected, NULL); } void JSModalDialogQt::HandleDialogResponse(int response_id, QString input, bool isSuppress) { switch (response_id) { case DialogQt::Accepted: if (ui::MessageBoxFlags::kIsJavascriptPrompt == jsDialog_->dialog_flags() && input != NULL) { jsDialog_->OnAccept(input.toStdWString(), isSuppress); }else { jsDialog_->OnAccept(std::wstring(), isSuppress); } break; case DialogQt::Rejected: jsDialog_->OnCancel(true); break; default: NOTREACHED(); } // Now that the dialog is gone, delete itselt here. delete this; } void JSModalDialogQt::OnDialogResponse(int response_id, QString input1, QString input2, bool isSuppress) { HandleDialogResponse(response_id, input1, isSuppress); } /*************************************************************************** * NativeAppModalDialog, static: */ NativeAppModalDialog* NativeAppModalDialog::CreateNativeJavaScriptPrompt( JavaScriptAppModalDialog* dialog, gfx::NativeWindow parent_window) { return new JSModalDialogQt(dialog, parent_window); } <commit_msg>Select "Cancel" will prevent the page create new dialog<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Copyright (c) 2010, Intel Corporation. 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/meegotouch/js_modal_dialog_qt.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/message_box_flags.h" #include "base/logging.h" #include "base/utf_string_conversions.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/browser_list.h" #include "chrome/browser/ui/meegotouch/qt_util.h" #include "chrome/browser/ui/app_modal_dialogs/js_modal_dialog.h" #include "grit/generated_resources.h" #include "grit/locale_settings.h" /*************************************************************************** * JSModalDialogQt */ JSModalDialogQt::JSModalDialogQt(JavaScriptAppModalDialog* dialog, gfx::NativeWindow parent_window) : jsDialog_(dialog) { int flag = jsDialog_->dialog_flags(); DialogQt::DLG_TYPE type; if(flag == ui::MessageBoxFlags::kIsJavascriptAlert) { type = DialogQt::DLG_ALERT; } else if (flag == ui::MessageBoxFlags::kIsJavascriptConfirm) { type = DialogQt::DLG_CONFIRM; } else if (flag == ui::MessageBoxFlags::kIsJavascriptPrompt) { type = DialogQt::DLG_PROMPT; } else { type = DialogQt::DLG_ALERT; } qDlgModel_ = new DialogQtModel(type, jsDialog_->display_suppress_checkbox(), WideToUTF8(jsDialog_->title()).c_str(), WideToUTF8(jsDialog_->message_text()).c_str(), WideToUTF8(jsDialog_->default_prompt_text()).c_str(), jsDialog_->is_before_unload_dialog()); } JSModalDialogQt::~JSModalDialogQt() { delete qDlgModel_; } int JSModalDialogQt::GetAppModalDialogButtons() const { switch (jsDialog_->dialog_flags()) { case ui::MessageBoxFlags::kIsJavascriptAlert: return ui::MessageBoxFlags::DIALOGBUTTON_OK; case ui::MessageBoxFlags::kIsJavascriptConfirm: return ui::MessageBoxFlags::DIALOGBUTTON_OK | ui::MessageBoxFlags::DIALOGBUTTON_CANCEL; case ui::MessageBoxFlags::kIsJavascriptPrompt: return ui::MessageBoxFlags::DIALOGBUTTON_OK; default: NOTREACHED(); return 0; } } void JSModalDialogQt::ShowAppModalDialog() { Browser* browser = BrowserList::GetLastActive(); BrowserWindowQt* browser_window = (BrowserWindowQt*)browser->window(); browser_window->ShowDialog(qDlgModel_, this); } void JSModalDialogQt::ActivateAppModalDialog() { //qDlg_->activateWindow(); //qDlg_->raise(); } void JSModalDialogQt::CloseAppModalDialog() { HandleDialogResponse(DialogQt::Rejected, NULL); } void JSModalDialogQt::AcceptAppModalDialog() { HandleDialogResponse(DialogQt::Accepted, NULL); } void JSModalDialogQt::CancelAppModalDialog() { HandleDialogResponse(DialogQt::Rejected, NULL); } void JSModalDialogQt::HandleDialogResponse(int response_id, QString input, bool isSuppress) { switch (response_id) { case DialogQt::Accepted: if (ui::MessageBoxFlags::kIsJavascriptPrompt == jsDialog_->dialog_flags() && input != NULL) { jsDialog_->OnAccept(input.toStdWString(), isSuppress); }else { jsDialog_->OnAccept(std::wstring(), isSuppress); } break; case DialogQt::Rejected: jsDialog_->OnCancel(isSuppress); break; default: NOTREACHED(); } // Now that the dialog is gone, delete itselt here. delete this; } void JSModalDialogQt::OnDialogResponse(int response_id, QString input1, QString input2, bool isSuppress) { HandleDialogResponse(response_id, input1, isSuppress); } /*************************************************************************** * NativeAppModalDialog, static: */ NativeAppModalDialog* NativeAppModalDialog::CreateNativeJavaScriptPrompt( JavaScriptAppModalDialog* dialog, gfx::NativeWindow parent_window) { return new JSModalDialogQt(dialog, parent_window); } <|endoftext|>
<commit_before>// Copyright 2009, Squish Tech, LLC. #include "libxmljs.h" #include <v8.h> #include <string> #include "natives.h" #include "object_wrap.h" #include "document.h" #include "element.h" #include "attribute.h" #include "namespace.h" #include "parser.h" #include "sax_parser.h" namespace libxmljs { namespace { // Called by libxml whenever it constructs something, // such as a node or attribute. // This allows us to create a C++ instance for every C instance. void on_libxml_construct(xmlNode* node) { switch (node->type) { case XML_ATTRIBUTE_NODE: BUILD_NODE(Attribute, xmlNode, attr, node); break; case XML_DOCUMENT_NODE: BUILD_NODE(Document, xmlDoc, doc, node->doc); break; case XML_ELEMENT_NODE: BUILD_NODE(Element, xmlNode, elem, node); break; default: NULL; // nothing. just silence the compiler warnings } } } // namespace LibXMLJS::LibXMLJS() { xmlInitParser(); // Not always necessary, but necessary for thread safety. xmlRegisterNodeDefault(on_libxml_construct); // xmlDeregisterNodeDefault(on_libxml_destruct); xmlThrDefRegisterNodeDefault(on_libxml_construct); // xmlThrDefDeregisterNodeDefault(on_libxml_destruct); } LibXMLJS::~LibXMLJS() { xmlCleanupParser(); // As per xmlInitParser(), or memory leak will happen. } LibXMLJS LibXMLJS::init_; static void OnFatalError(const char* location, const char* message) { #define FATAL_ERROR "\033[1;31mV8 FATAL ERROR.\033[m" if (location) fprintf(stderr, FATAL_ERROR " %s %s\n", location, message); else fprintf(stderr, FATAL_ERROR " %s\n", message); exit(1); } // Extracts a C str from a V8 Utf8Value. const char * ToCString(const v8::String::Utf8Value& value) { return *value ? *value : "<str conversion failed>"; } static void ReportException(v8::TryCatch* try_catch) { v8::Handle<v8::Message> message = try_catch->Message(); if (message.IsEmpty()) { fprintf(stderr, "Error: (no message)\n"); fflush(stderr); return; } v8::Handle<v8::Value> error = try_catch->Exception(); v8::Handle<v8::String> stack; if (error->IsObject()) { v8::Handle<v8::Object> obj = v8::Handle<v8::Object>::Cast(error); v8::Handle<v8::Value> raw_stack = obj->Get(v8::String::New("stack")); if (raw_stack->IsString()) stack = v8::Handle<v8::String>::Cast(raw_stack); } if (stack.IsEmpty()) { v8::String::Utf8Value exception(error); // Print (filename):(line number): (message). v8::String::Utf8Value filename(message->GetScriptResourceName()); const char* filename_string = ToCString(filename); int linenum = message->GetLineNumber(); fprintf(stderr, "%s:%i: %s\n", filename_string, linenum, *exception); // Print line of source code. v8::String::Utf8Value sourceline(message->GetSourceLine()); const char* sourceline_string = ToCString(sourceline); fprintf(stderr, "%s\n", sourceline_string); // Print wavy underline (GetUnderline is deprecated). int start = message->GetStartColumn(); for (int i = 0; i < start; i++) { fprintf(stderr, " "); } int end = message->GetEndColumn(); for (int i = start; i < end; i++) { fprintf(stderr, "^"); } fprintf(stderr, "\n"); message->PrintCurrentStackTrace(stderr); } else { v8::String::Utf8Value trace(stack); fprintf(stderr, "%s\n", *trace); } fflush(stderr); } // Executes a str within the current v8 context. v8::Handle<v8::Value> ExecuteString(v8::Handle<v8::String> source, v8::Handle<v8::Value> filename) { v8::HandleScope scope; v8::TryCatch try_catch; v8::Handle<v8::Script> script = v8::Script::Compile(source, filename); if (script.IsEmpty()) { ReportException(&try_catch); exit(1); } v8::Handle<v8::Value> result = script->Run(); if (result.IsEmpty()) { ReportException(&try_catch); exit(1); } return scope.Close(result); } static void ExecuteNativeJS(const char* filename, const char* data) { v8::HandleScope scope; v8::TryCatch try_catch; ExecuteString(v8::String::New(data), v8::String::New(filename)); if (try_catch.HasCaught()) { puts("There is an error in Node's built-in javascript"); puts("This should be reported as a bug!"); ReportException(&try_catch); exit(1); } } void InitializeLibXMLJS(v8::Handle<v8::Object> target) { v8::HandleScope scope; Document::Initialize(target); Parser::Initialize(target); SaxParser::Initialize(target); v8::Handle<v8::ObjectTemplate> global = v8::ObjectTemplate::New(); v8::Handle<v8::Context> context = v8::Context::New(NULL, global); v8::Context::Scope context_scope(context); context->Global()->Set(v8::String::NewSymbol("libxml"), target); ExecuteNativeJS("sax_parser.js", native_sax_parser); ExecuteNativeJS("document.js", native_document); ExecuteNativeJS("element.js", native_element); } // used by node.js to initialize libraries extern "C" void init(v8::Handle<v8::Object> target) { v8::HandleScope scope; InitializeLibXMLJS(target); } int main(int argc, char* argv[]) { v8::V8::SetFlagsFromCommandLine(&argc, argv, true); v8::V8::Initialize(); v8::V8::SetFatalErrorHandler(OnFatalError); // Create a stack-allocated handle scope. v8::HandleScope handle_scope; // Create a new context. v8::Handle<v8::Context> context = v8::Context::New(); // Enter the created context for compiling and // running the hello world script. v8::Context::Scope context_scope(context); v8::Local<v8::Object> global_obj = v8::Context::GetCurrent()->Global(); v8::Local<v8::Object> libxml_obj = v8::Object::New(); InitializeLibXMLJS(libxml_obj); global_obj->Set(v8::String::NewSymbol("libxml"), libxml_obj); // for (int i = 1; i < argc; i++) { // // Create a string containing the JavaScript source code. // Handle<String> source = ReadFile(argv[i]); // // Compile the source code. // Handle<Script> script = Script::Compile(source); // // Run the script to get the result. // Handle<Value> result = script->Run(); // } v8::V8::Dispose(); return 0; } } // namespace libxmljs <commit_msg>Only build document nodes with RegisterNodeDefault (breaks everything)<commit_after>// Copyright 2009, Squish Tech, LLC. #include "libxmljs.h" #include <v8.h> #include <string> #include "natives.h" #include "object_wrap.h" #include "document.h" #include "element.h" #include "attribute.h" #include "namespace.h" #include "parser.h" #include "sax_parser.h" namespace libxmljs { namespace { // Called by libxml whenever it constructs something, // such as a node or attribute. // This allows us to create a C++ instance for every C instance. void on_libxml_construct(xmlNode* node) { switch (node->type) { // case XML_ATTRIBUTE_NODE: // BUILD_NODE(Attribute, xmlNode, attr, node); // break; case XML_DOCUMENT_NODE: BUILD_NODE(Document, xmlDoc, doc, node->doc); break; // case XML_ELEMENT_NODE: // BUILD_NODE(Element, xmlNode, elem, node); // break; default: NULL; // nothing. just silence the compiler warnings } } } // namespace LibXMLJS::LibXMLJS() { xmlInitParser(); // Not always necessary, but necessary for thread safety. xmlRegisterNodeDefault(on_libxml_construct); // xmlDeregisterNodeDefault(on_libxml_destruct); xmlThrDefRegisterNodeDefault(on_libxml_construct); // xmlThrDefDeregisterNodeDefault(on_libxml_destruct); } LibXMLJS::~LibXMLJS() { xmlCleanupParser(); // As per xmlInitParser(), or memory leak will happen. } LibXMLJS LibXMLJS::init_; static void OnFatalError(const char* location, const char* message) { #define FATAL_ERROR "\033[1;31mV8 FATAL ERROR.\033[m" if (location) fprintf(stderr, FATAL_ERROR " %s %s\n", location, message); else fprintf(stderr, FATAL_ERROR " %s\n", message); exit(1); } // Extracts a C str from a V8 Utf8Value. const char * ToCString(const v8::String::Utf8Value& value) { return *value ? *value : "<str conversion failed>"; } static void ReportException(v8::TryCatch* try_catch) { v8::Handle<v8::Message> message = try_catch->Message(); if (message.IsEmpty()) { fprintf(stderr, "Error: (no message)\n"); fflush(stderr); return; } v8::Handle<v8::Value> error = try_catch->Exception(); v8::Handle<v8::String> stack; if (error->IsObject()) { v8::Handle<v8::Object> obj = v8::Handle<v8::Object>::Cast(error); v8::Handle<v8::Value> raw_stack = obj->Get(v8::String::New("stack")); if (raw_stack->IsString()) stack = v8::Handle<v8::String>::Cast(raw_stack); } if (stack.IsEmpty()) { v8::String::Utf8Value exception(error); // Print (filename):(line number): (message). v8::String::Utf8Value filename(message->GetScriptResourceName()); const char* filename_string = ToCString(filename); int linenum = message->GetLineNumber(); fprintf(stderr, "%s:%i: %s\n", filename_string, linenum, *exception); // Print line of source code. v8::String::Utf8Value sourceline(message->GetSourceLine()); const char* sourceline_string = ToCString(sourceline); fprintf(stderr, "%s\n", sourceline_string); // Print wavy underline (GetUnderline is deprecated). int start = message->GetStartColumn(); for (int i = 0; i < start; i++) { fprintf(stderr, " "); } int end = message->GetEndColumn(); for (int i = start; i < end; i++) { fprintf(stderr, "^"); } fprintf(stderr, "\n"); message->PrintCurrentStackTrace(stderr); } else { v8::String::Utf8Value trace(stack); fprintf(stderr, "%s\n", *trace); } fflush(stderr); } // Executes a str within the current v8 context. v8::Handle<v8::Value> ExecuteString(v8::Handle<v8::String> source, v8::Handle<v8::Value> filename) { v8::HandleScope scope; v8::TryCatch try_catch; v8::Handle<v8::Script> script = v8::Script::Compile(source, filename); if (script.IsEmpty()) { ReportException(&try_catch); exit(1); } v8::Handle<v8::Value> result = script->Run(); if (result.IsEmpty()) { ReportException(&try_catch); exit(1); } return scope.Close(result); } static void ExecuteNativeJS(const char* filename, const char* data) { v8::HandleScope scope; v8::TryCatch try_catch; ExecuteString(v8::String::New(data), v8::String::New(filename)); if (try_catch.HasCaught()) { puts("There is an error in Node's built-in javascript"); puts("This should be reported as a bug!"); ReportException(&try_catch); exit(1); } } void InitializeLibXMLJS(v8::Handle<v8::Object> target) { v8::HandleScope scope; Document::Initialize(target); Parser::Initialize(target); SaxParser::Initialize(target); v8::Handle<v8::ObjectTemplate> global = v8::ObjectTemplate::New(); v8::Handle<v8::Context> context = v8::Context::New(NULL, global); v8::Context::Scope context_scope(context); context->Global()->Set(v8::String::NewSymbol("libxml"), target); ExecuteNativeJS("sax_parser.js", native_sax_parser); ExecuteNativeJS("document.js", native_document); ExecuteNativeJS("element.js", native_element); } // used by node.js to initialize libraries extern "C" void init(v8::Handle<v8::Object> target) { v8::HandleScope scope; InitializeLibXMLJS(target); } int main(int argc, char* argv[]) { v8::V8::SetFlagsFromCommandLine(&argc, argv, true); v8::V8::Initialize(); v8::V8::SetFatalErrorHandler(OnFatalError); // Create a stack-allocated handle scope. v8::HandleScope handle_scope; // Create a new context. v8::Handle<v8::Context> context = v8::Context::New(); // Enter the created context for compiling and // running the hello world script. v8::Context::Scope context_scope(context); v8::Local<v8::Object> global_obj = v8::Context::GetCurrent()->Global(); v8::Local<v8::Object> libxml_obj = v8::Object::New(); InitializeLibXMLJS(libxml_obj); global_obj->Set(v8::String::NewSymbol("libxml"), libxml_obj); // for (int i = 1; i < argc; i++) { // // Create a string containing the JavaScript source code. // Handle<String> source = ReadFile(argv[i]); // // Compile the source code. // Handle<Script> script = Script::Compile(source); // // Run the script to get the result. // Handle<Value> result = script->Run(); // } v8::V8::Dispose(); return 0; } } // namespace libxmljs <|endoftext|>
<commit_before>/** * makedot.cpp - * @author: Jonathan Beard * @version: Sun Oct 4 09:15:09 2020 * * Copyright 2020 Jonathan Beard * * 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 <ostream> #include <sstream> #include <ios> #include <iostream> #include "makedot.hpp" #include "common.hpp" #include "map.hpp" #include "graphtools.hpp" #include "ringbuffertypes.hpp" raft::make_dot::make_dot( raft::map &map ) : all_kernels( map.all_kernels ), source_kernels( map.source_kernels ) { //nothing else to d //nothing else to doo } void raft::make_dot::_run( std::ostream &stream ) { //make dot header generate_preamble( stream ); //run over all kernels to make header generate_vertex_list( stream ); //run through graph edges to build edge list generate_edge_list( stream ); //dot close format generate_close( stream ); return; } void raft::make_dot::generate_preamble( std::ostream &stream ) { stream << "digraph G{\n"; stream << "\t"; stream << raft::make_dot::generate_field( "size", height, width ) << ";\n"; return; } void raft::make_dot::generate_vertex_list( std::ostream &stream ) { auto &c( all_kernels.acquire() ); for( auto &k /** kernel **/ : c /** in container **/ ) { stream << "\t" << k->get_id(); stream << "["; stream << raft::make_dot::generate_field( "label", common::printClassName( *k ) ); stream << ", "; stream << raft::make_dot::generate_field( "shape", "ellipse" ) << ", "; stream << raft::make_dot::generate_field( "fontname", "Helvetica" ); stream << "];\n"; } all_kernels.release(); return; } void raft::make_dot::generate_edge_list( std::ostream &stream ) { (void)stream; auto dot_func = [&]( PortInfo &a, PortInfo &b, void *data ) -> void { auto *stream_ptr( reinterpret_cast< std::ostream* >( data ) ); (*stream_ptr) << "\t" << a.my_kernel->get_id() << " -> "; (*stream_ptr) << b.my_kernel->get_id(); (*stream_ptr) << "["; std::stringstream ss; ss << a.my_name << " to " << b.my_name << " ("; ss << common::printClassNameFromStr( a.type.name() ) + ")"; ss << "\n"; ss << "OoO=" << std::boolalpha << a.out_of_order << "\n"; ss << "custom allocator=" << std::boolalpha << a.use_my_allocator << "\n"; ss << "queue type=" << Type::type_prints[ a.mem ] << "\n"; if( a.existing_buffer != nullptr ) { ss << "existing_buffer\n"; ss << "\tsize: " << a.nitems << "\n"; ss << "\tstart_offset: " << a.start_index << "\n"; ss << "\tfixed_buffer_size: " << a.fixed_buffer_size << "\n"; } (*stream_ptr) << raft::make_dot::generate_field( "label", ss.str() ); (*stream_ptr) << "];\n"; }; auto &c( source_kernels.acquire() ); GraphTools::BFS( c, dot_func, (void*) &stream ); source_kernels.release(); return; } void raft::make_dot::generate_close( std::ostream &stream ) { stream << "}\n"; return; } <commit_msg>updates<commit_after>/** * makedot.cpp - * @author: Jonathan Beard * @version: Sun Oct 4 09:15:09 2020 * * Copyright 2020 Jonathan Beard * * 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 <ostream> #include <sstream> #include <ios> #include <iostream> #include <cstdlib> #include <string> #include "makedot.hpp" #include "common.hpp" #include "map.hpp" #include "graphtools.hpp" #include "ringbuffertypes.hpp" raft::make_dot::make_dot( raft::map &map ) : all_kernels( map.all_kernels ), source_kernels( map.source_kernels ) { auto *height_env( std::getenv( "GEN_DOT_HEIGHT" ) ); if( height_env != nullptr ) { height = std::stoi( height_env ); } auto *width_env( std::getenv( "GEN_DOT_WIDTH" ) ); if( width_env != nullptr ) { width = std::stoi( width_env ); } } void raft::make_dot::_run( std::ostream &stream ) { //make dot header generate_preamble( stream ); //run over all kernels to make header generate_vertex_list( stream ); //run through graph edges to build edge list generate_edge_list( stream ); //dot close format generate_close( stream ); return; } void raft::make_dot::generate_preamble( std::ostream &stream ) { stream << "digraph G{\n"; stream << "\t"; stream << raft::make_dot::generate_field( "size", height, width ) << ";\n"; return; } void raft::make_dot::generate_vertex_list( std::ostream &stream ) { auto &c( all_kernels.acquire() ); for( auto &k /** kernel **/ : c /** in container **/ ) { stream << "\t" << k->get_id(); stream << "["; stream << raft::make_dot::generate_field( "label", common::printClassName( *k ) ); stream << ", "; stream << raft::make_dot::generate_field( "shape", "ellipse" ) << ", "; stream << raft::make_dot::generate_field( "fontname", "Helvetica" ); stream << "];\n"; } all_kernels.release(); return; } void raft::make_dot::generate_edge_list( std::ostream &stream ) { (void)stream; auto dot_func = [&]( PortInfo &a, PortInfo &b, void *data ) -> void { auto *stream_ptr( reinterpret_cast< std::ostream* >( data ) ); (*stream_ptr) << "\t" << a.my_kernel->get_id() << " -> "; (*stream_ptr) << b.my_kernel->get_id(); (*stream_ptr) << "["; std::stringstream ss; ss << a.my_name << " to " << b.my_name << " ("; ss << common::printClassNameFromStr( a.type.name() ) + ")"; ss << "\n"; ss << "OoO=" << std::boolalpha << a.out_of_order << "\n"; ss << "custom allocator=" << std::boolalpha << a.use_my_allocator << "\n"; ss << "queue type=" << Type::type_prints[ a.mem ] << "\n"; if( a.existing_buffer != nullptr ) { ss << "existing_buffer\n"; ss << "\tsize: " << a.nitems << "\n"; ss << "\tstart_offset: " << a.start_index << "\n"; ss << "\tfixed_buffer_size: " << a.fixed_buffer_size << "\n"; } (*stream_ptr) << raft::make_dot::generate_field( "label", ss.str() ); (*stream_ptr) << "];\n"; }; auto &c( source_kernels.acquire() ); GraphTools::BFS( c, dot_func, (void*) &stream ); source_kernels.release(); return; } void raft::make_dot::generate_close( std::ostream &stream ) { stream << "}\n"; return; } <|endoftext|>
<commit_before>/// \file liburbi/uclient.cc #include <cstdlib> #include <cerrno> #include <locale.h> #include <libport/unistd.h> #include <libport/sys/time.h> #if !defined WIN32 # include <time.h> # include <signal.h> #endif #include <libport/cstdio> #include <libport/sys/select.h> #include <libport/arpa/inet.h> #include <libport/netdb.h> #include <libport/errors.hh> #include <libport/lockable.hh> #include <libport/thread.hh> #include <libport/utime.hh> #include <urbi/uclient.hh> #include <urbi/utag.hh> namespace urbi { /*! Establish the connection with the server. Spawn a new thread that will listen to the socket, parse the incoming URBI messages, and notify the appropriate callbacks. */ UClient::UClient(const std::string& host, int port, int buflen, bool server) : UAbstractClient(host, port, buflen, server) , thread(0) , pingInterval(0) { int pos = 0; setlocale(LC_NUMERIC, "C"); control_fd[0] = control_fd[1] = -1; #ifndef WIN32 if (::pipe(control_fd) == -1) { rc = -1; libport::perror("UClient::UClient failed to create pipe"); return; } //block sigpipe signal(SIGPIPE, SIG_IGN); #endif // Address resolution stage. struct sockaddr_in sa; // Internet address struct memset(&sa, 0, sizeof sa); #ifdef WIN32 WSADATA wsaData; WORD wVersionRequested; wVersionRequested = MAKEWORD(1, 1); WSAStartup(wVersionRequested, &wsaData); #endif sa.sin_family = AF_INET; sa.sin_port = htons(port); // host-to-IP translation struct hostent* hen = gethostbyname(host_.c_str()); if (!hen) { // maybe it is an IP address sa.sin_addr.s_addr = inet_addr(host_.c_str()); if (sa.sin_addr.s_addr == INADDR_NONE) { std::cerr << "UClient::UClient cannot resolve host name." << std::endl; rc = -1; return; } } else memcpy(&sa.sin_addr.s_addr, hen->h_addr_list[0], hen->h_length); sd = socket(AF_INET, SOCK_STREAM, 0); if (sd < 0) { rc = -1; libport::perror("UClient::UClient socket"); return; } if (!server_) { // Connect on given host and port rc = connect(sd, (struct sockaddr *) &sa, sizeof sa); // If we attempt to connect too fast to aperios ipstack it will fail. if (rc) { usleep(20000); rc = connect(sd, (struct sockaddr *) &sa, sizeof sa); } // Check there was no error. if (rc) { rc = -1; libport::perror("UClient::UClient connect"); return; } // Check that it really worked. while (!pos) pos = ::recv(sd, recvBuffer, buflen, 0); if (pos < 0) { rc = -1; libport::perror("UClient::UClient recv"); return; } } else { // Allow to rebind on the same port shortly after having used it. { int one = 1; rc = setsockopt(sd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof one); if (rc) { rc = -1; libport::perror("UClient::UClient cannot use setsockopt"); return; } } // Bind socket rc = bind (sd, (struct sockaddr *) &sa, sizeof sa); if (rc) { rc = -1; libport::perror("UClient::UClient cannot bind"); return; } // Activate listen/passive mode, do not allow queued connections rc = listen (sd, 0); if (rc) { rc = -1; libport::perror("UClient::UClient cannot listen"); return; } // Create a thread waiting for incoming connection. // This must not be blocking in case of a remote server. // FIXME: block if normal remote ? init_ = false; thread = libport::startThread(this, &UClient::acceptThread); } recvBufferPosition = pos; recvBuffer[recvBufferPosition] = 0; // Do not create thread if one is already waiting for incoming connection if (!thread) thread = libport::startThread(this, &UClient::listenThread); if (!defaultClient) defaultClient = this; } UClient::~UClient() { if (libport::closeSocket(sd) == -1) libport::perror ("cannot close sd"); sd = -1; if (control_fd[1] != -1 && ::write(control_fd[1], "a", 1) == -1) libport::perror ("cannot write to control_fd[1]"); // If the connection has failed while building the client, the // thread is not created. if (thread) // Must wait for listen thread to terminate. libport::joinThread(thread); if (control_fd[1] != -1 && close(control_fd[1]) == -1) libport::perror ("cannot close controlfd[1]"); if (control_fd[0] != -1 && close(control_fd[0]) == -1) libport::perror ("cannot close controlfd[0]"); } bool UClient::canSend(int) { return true; } int UClient::effectiveSend(const void* buffer, int size) { #if DEBUG char output[size+1]; memcpy (static_cast<void*> (output), buffer, size); output[size]=0; std::cerr << ">>>> SENT : [" << output << "]" << std::endl; #endif if (rc) return -1; int pos = 0; while (pos != size) { int retval = ::send(sd, (char *) buffer + pos, size-pos, 0); if (retval< 0) { rc = retval; clientError("send error", rc); return rc; } pos += retval; } return 0; } void UClient::acceptThread() { // Accept one connection struct sockaddr_in saClient; socklen_t addrlenClient; int acceptFD = 0; acceptFD = accept (sd, (struct sockaddr *) &saClient, &addrlenClient); if (acceptFD < 0) { libport::perror("UClient::UClient cannot accept"); rc = -1; return; } // Store client connection info host_ = inet_ntoa (saClient.sin_addr); port_ = saClient.sin_port; // Do not listen anymore. close (sd); // Redirect send/receive on accepted connection. sd = acceptFD; // FIXME: leaking ? thread = libport::startThread(this, &UClient::listenThread); init_ = true; // Stop this thread, the listen one is the real thing. return; } void UClient::listenThread() { int maxfd = 1 + std::max(sd, control_fd[0]); waitingPong = false; // Declare ping channel for kernel that requires it. send("if (isdef(Channel)) var lobby.%s = Channel.new(\"%s\");", internalPongTag.c_str(), internalPongTag.c_str()); while (true) { if (sd == -1) return; fd_set rfds; fd_set efds; FD_ZERO(&rfds); FD_ZERO(&efds); LIBPORT_FD_SET(sd, &rfds); LIBPORT_FD_SET(sd, &efds); #ifndef WIN32 LIBPORT_FD_SET(control_fd[0], &rfds); #endif int selectReturn; if (pingInterval != 0) { const unsigned delay = waitingPong ? pongTimeout : pingInterval; struct timeval timeout = { delay / 1000, (delay % 1000) * 1000}; selectReturn = ::select(maxfd + 1, &rfds, NULL, &efds, &timeout); } else { selectReturn = ::select(maxfd + 1, &rfds, NULL, &efds, NULL); } // Treat error if (selectReturn < 0 && errno != EINTR) { rc = -1; clientError("Connection error : ", errno); notifyCallbacks(UMessage(*this, 0, connectionTimeoutTag.c_str(), "!!! Connection error", std::list<BinaryData>() )); return; } if (selectReturn < 0) // ::select catch a signal (errno == EINTR) continue; // timeout if (selectReturn == 0) { if (waitingPong) // Timeout while waiting PONG { rc = -1; // FIXME: Choose between two differents way to alert user program clientError("Lost connection with server"); notifyCallbacks(UMessage(*this, 0, connectionTimeoutTag.c_str(), "!!! Lost connection with server", std::list<BinaryData>() )); return; } else // Timeout : Ping_interval { send("%s << 1,", internalPongTag.c_str()); waitingPong = true; } } if (selectReturn > 0) { // We receive data, at least the "1" value sent through the pong tag // channel so we are no longer waiting for a pong. waitingPong = false; int count = ::recv(sd, &recvBuffer[recvBufferPosition], buflen - recvBufferPosition - 1, 0); if (count <= 0) { std::string errorMsg; int errorCode = 0; if (count < 0) { #ifdef WIN32 errorCode = WSAGetLastError(); #else errorCode = errno; #endif errorMsg = "!!! Connection error"; } else // count == 0 => Connection close { errorMsg = "!!! Connection closed"; } rc = -1; clientError(errorMsg.c_str(), errorCode); notifyCallbacks(UMessage(*this, 0, connectionTimeoutTag.c_str(), errorMsg.c_str(), std::list<BinaryData>() )); return; } recvBufferPosition += count; recvBuffer[recvBufferPosition] = 0; processRecvBuffer(); } } } void UClient::printf(const char * format, ...) { va_list arg; va_start(arg, format); vfprintf(stderr, format, arg); va_end(arg); } unsigned int UClient::getCurrentTime() const { // FIXME: Put this into libport. #ifdef WIN32 return GetTickCount(); #else struct timeval tv; gettimeofday(&tv, NULL); return tv.tv_sec*1000+tv.tv_usec/1000; #endif } void execute() { while (true) sleep(100); } void exit(int code) { ::exit(code); } UClient& connect(const std::string& host) { return *new UClient(host); } void disconnect(UClient &client) { delete &client; } void UClient::setKeepAliveCheck(const unsigned pingInterval, const unsigned pongTimeout) { this->pingInterval = pingInterval; this->pongTimeout = pongTimeout; } } // namespace urbi <commit_msg>UClient, Enhance fd test.<commit_after>/// \file liburbi/uclient.cc #include <cstdlib> #include <cerrno> #include <locale.h> #include <libport/unistd.h> #include <libport/sys/time.h> #if !defined WIN32 # include <time.h> # include <signal.h> #endif #include <libport/cstdio> #include <libport/sys/select.h> #include <libport/arpa/inet.h> #include <libport/netdb.h> #include <libport/errors.hh> #include <libport/lockable.hh> #include <libport/thread.hh> #include <libport/utime.hh> #include <urbi/uclient.hh> #include <urbi/utag.hh> namespace urbi { /*! Establish the connection with the server. Spawn a new thread that will listen to the socket, parse the incoming URBI messages, and notify the appropriate callbacks. */ UClient::UClient(const std::string& host, int port, int buflen, bool server) : UAbstractClient(host, port, buflen, server) , thread(0) , pingInterval(0) { int pos = 0; setlocale(LC_NUMERIC, "C"); control_fd[0] = control_fd[1] = -1; #ifndef WIN32 if (::pipe(control_fd) == -1) { rc = -1; libport::perror("UClient::UClient failed to create pipe"); return; } //block sigpipe signal(SIGPIPE, SIG_IGN); #endif // Address resolution stage. struct sockaddr_in sa; // Internet address struct memset(&sa, 0, sizeof sa); #ifdef WIN32 WSADATA wsaData; WORD wVersionRequested; wVersionRequested = MAKEWORD(1, 1); WSAStartup(wVersionRequested, &wsaData); #endif sa.sin_family = AF_INET; sa.sin_port = htons(port); // host-to-IP translation struct hostent* hen = gethostbyname(host_.c_str()); if (!hen) { // maybe it is an IP address sa.sin_addr.s_addr = inet_addr(host_.c_str()); if (sa.sin_addr.s_addr == INADDR_NONE) { std::cerr << "UClient::UClient cannot resolve host name." << std::endl; rc = -1; return; } } else memcpy(&sa.sin_addr.s_addr, hen->h_addr_list[0], hen->h_length); sd = socket(AF_INET, SOCK_STREAM, 0); if (sd < 0) { rc = -1; libport::perror("UClient::UClient socket"); return; } if (!server_) { // Connect on given host and port rc = connect(sd, (struct sockaddr *) &sa, sizeof sa); // If we attempt to connect too fast to aperios ipstack it will fail. if (rc) { usleep(20000); rc = connect(sd, (struct sockaddr *) &sa, sizeof sa); } // Check there was no error. if (rc) { rc = -1; libport::perror("UClient::UClient connect"); return; } // Check that it really worked. while (!pos) pos = ::recv(sd, recvBuffer, buflen, 0); if (pos < 0) { rc = -1; libport::perror("UClient::UClient recv"); return; } } else { // Allow to rebind on the same port shortly after having used it. { int one = 1; rc = setsockopt(sd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof one); if (rc) { rc = -1; libport::perror("UClient::UClient cannot use setsockopt"); return; } } // Bind socket rc = bind (sd, (struct sockaddr *) &sa, sizeof sa); if (rc) { rc = -1; libport::perror("UClient::UClient cannot bind"); return; } // Activate listen/passive mode, do not allow queued connections rc = listen (sd, 0); if (rc) { rc = -1; libport::perror("UClient::UClient cannot listen"); return; } // Create a thread waiting for incoming connection. // This must not be blocking in case of a remote server. // FIXME: block if normal remote ? init_ = false; thread = libport::startThread(this, &UClient::acceptThread); } recvBufferPosition = pos; recvBuffer[recvBufferPosition] = 0; // Do not create thread if one is already waiting for incoming connection if (!thread) thread = libport::startThread(this, &UClient::listenThread); if (!defaultClient) defaultClient = this; } UClient::~UClient() { if (sd >= 0 && libport::closeSocket(sd) == -1) libport::perror ("cannot close sd"); sd = -1; if (control_fd[1] != -1 && ::write(control_fd[1], "a", 1) == -1) libport::perror ("cannot write to control_fd[1]"); // If the connection has failed while building the client, the // thread is not created. if (thread) // Must wait for listen thread to terminate. libport::joinThread(thread); if (control_fd[1] != -1 && close(control_fd[1]) == -1) libport::perror ("cannot close controlfd[1]"); if (control_fd[0] != -1 && close(control_fd[0]) == -1) libport::perror ("cannot close controlfd[0]"); } bool UClient::canSend(int) { return true; } int UClient::effectiveSend(const void* buffer, int size) { #if DEBUG char output[size+1]; memcpy (static_cast<void*> (output), buffer, size); output[size]=0; std::cerr << ">>>> SENT : [" << output << "]" << std::endl; #endif if (rc) return -1; int pos = 0; while (pos != size) { int retval = ::send(sd, (char *) buffer + pos, size-pos, 0); if (retval< 0) { rc = retval; clientError("send error", rc); return rc; } pos += retval; } return 0; } void UClient::acceptThread() { // Accept one connection struct sockaddr_in saClient; socklen_t addrlenClient; int acceptFD = 0; acceptFD = accept (sd, (struct sockaddr *) &saClient, &addrlenClient); if (acceptFD < 0) { libport::perror("UClient::UClient cannot accept"); rc = -1; return; } // Store client connection info host_ = inet_ntoa (saClient.sin_addr); port_ = saClient.sin_port; // Do not listen anymore. close (sd); // Redirect send/receive on accepted connection. sd = acceptFD; // FIXME: leaking ? thread = libport::startThread(this, &UClient::listenThread); init_ = true; // Stop this thread, the listen one is the real thing. return; } void UClient::listenThread() { int maxfd = 1 + std::max(sd, control_fd[0]); waitingPong = false; // Declare ping channel for kernel that requires it. send("if (isdef(Channel)) var lobby.%s = Channel.new(\"%s\");", internalPongTag.c_str(), internalPongTag.c_str()); while (true) { if (sd == -1) return; fd_set rfds; fd_set efds; FD_ZERO(&rfds); FD_ZERO(&efds); LIBPORT_FD_SET(sd, &rfds); LIBPORT_FD_SET(sd, &efds); #ifndef WIN32 LIBPORT_FD_SET(control_fd[0], &rfds); #endif int selectReturn; if (pingInterval != 0) { const unsigned delay = waitingPong ? pongTimeout : pingInterval; struct timeval timeout = { delay / 1000, (delay % 1000) * 1000}; selectReturn = ::select(maxfd + 1, &rfds, NULL, &efds, &timeout); } else { selectReturn = ::select(maxfd + 1, &rfds, NULL, &efds, NULL); } // Treat error if (selectReturn < 0 && errno != EINTR) { rc = -1; clientError("Connection error : ", errno); notifyCallbacks(UMessage(*this, 0, connectionTimeoutTag.c_str(), "!!! Connection error", std::list<BinaryData>() )); return; } if (selectReturn < 0) // ::select catch a signal (errno == EINTR) continue; // timeout if (selectReturn == 0) { if (waitingPong) // Timeout while waiting PONG { rc = -1; // FIXME: Choose between two differents way to alert user program clientError("Lost connection with server"); notifyCallbacks(UMessage(*this, 0, connectionTimeoutTag.c_str(), "!!! Lost connection with server", std::list<BinaryData>() )); return; } else // Timeout : Ping_interval { send("%s << 1,", internalPongTag.c_str()); waitingPong = true; } } if (selectReturn > 0) { // We receive data, at least the "1" value sent through the pong tag // channel so we are no longer waiting for a pong. waitingPong = false; int count = ::recv(sd, &recvBuffer[recvBufferPosition], buflen - recvBufferPosition - 1, 0); if (count <= 0) { std::string errorMsg; int errorCode = 0; if (count < 0) { #ifdef WIN32 errorCode = WSAGetLastError(); #else errorCode = errno; #endif errorMsg = "!!! Connection error"; } else // count == 0 => Connection close { errorMsg = "!!! Connection closed"; } rc = -1; clientError(errorMsg.c_str(), errorCode); notifyCallbacks(UMessage(*this, 0, connectionTimeoutTag.c_str(), errorMsg.c_str(), std::list<BinaryData>() )); return; } recvBufferPosition += count; recvBuffer[recvBufferPosition] = 0; processRecvBuffer(); } } } void UClient::printf(const char * format, ...) { va_list arg; va_start(arg, format); vfprintf(stderr, format, arg); va_end(arg); } unsigned int UClient::getCurrentTime() const { // FIXME: Put this into libport. #ifdef WIN32 return GetTickCount(); #else struct timeval tv; gettimeofday(&tv, NULL); return tv.tv_sec*1000+tv.tv_usec/1000; #endif } void execute() { while (true) sleep(100); } void exit(int code) { ::exit(code); } UClient& connect(const std::string& host) { return *new UClient(host); } void disconnect(UClient &client) { delete &client; } void UClient::setKeepAliveCheck(const unsigned pingInterval, const unsigned pongTimeout) { this->pingInterval = pingInterval; this->pongTimeout = pongTimeout; } } // namespace urbi <|endoftext|>
<commit_before> #include <string> #include <list> #include <iostream> #include <algorithm> #include <stdio.h> #include <string.h> #include <windows.h> #include <stdint.h> using std::string; using std::list; using std::cout; using std::cerr; using std::endl; #ifdef _MSC_VER #pragma warning(disable: 4996) #endif #ifndef min #define min(a, b) ((a) >= (b)? (a) : (b)) #endif #define HEADER_LEN 8 #define NUM_ENTRIES 512 #define ENTRY_SIZE (12 + 4 + 4) #define START_OFFSET (HEADER_LEN + NUM_ENTRIES * ENTRY_SIZE) typedef struct { string name; uint32_t offset; uint32_t size; } d2_entry; void usage() { cerr << "Usage: d2 dir file" << endl; } int make_d2(string dir, string file) { list<d2_entry> entries; bool limit_reached = false; WIN32_FIND_DATA wfd; uint64_t offset = START_OFFSET; HANDLE h = FindFirstFile((dir + "\\*").c_str(), &wfd); BOOL b = (h != INVALID_HANDLE_VALUE); while (b) { if ((wfd.dwFileAttributes & (FILE_ATTRIBUTE_ARCHIVE | FILE_ATTRIBUTE_DIRECTORY)) == FILE_ATTRIBUTE_ARCHIVE) { if (entries.size() >= 512) { cerr << "512 file limit reached; skipping file: " << wfd.cFileName << endl; limit_reached = true; } else if (wfd.nFileSizeHigh) { cerr << "skipping file larger than 4GB: " << wfd.cFileName << endl; limit_reached = true; } else if (offset + wfd.nFileSizeLow > 0x100000000) { cerr << "4GB file limit reached; skipping file: " << wfd.cFileName << endl; limit_reached = true; } else { string name = wfd.cAlternateFileName; if (name.empty()) name = wfd.cFileName; d2_entry entry = {name, (uint32_t)offset, wfd.nFileSizeLow}; entries.push_back(entry); offset += wfd.nFileSizeLow; } } b = FindNextFile(h,&wfd); } FindClose(h); if (limit_reached) return 1; d2_entry empty = {"", 0, 0}; while (entries.size() < 512) entries.push_back(empty); FILE *fout = fopen(file.c_str(), "wb"); char header[HEADER_LEN] = {'v', 's', ' ', 'd', '2', 0, 0, 0}; fwrite(header, 1, sizeof(header), fout); for (list<d2_entry>::const_iterator it = entries.begin(); it != entries.end(); ++it) { char name[12]; strncpy(name, it->name.c_str(), sizeof(name)); fwrite(name, 1, sizeof(name), fout); fwrite(&it->offset, 1, sizeof(it->offset), fout); fwrite(&it->size, 1, sizeof(it->size), fout); } for (list<d2_entry>::const_iterator it = entries.begin(); it != entries.end(); ++it) { if (it->name.empty()) continue; string name = dir + "\\" + it->name; FILE *fin = fopen(name.c_str(), "rb"); if (!fin) { cerr << "error opening file: " << name << endl; } char buff[32768]; size_t nleft = it->size; while (nleft > 0) { size_t req = min(nleft, sizeof(buff)); size_t nread = fread(buff, 1, req, fin); if (nread != req) { if (feof(fin)) cerr << "unexpected end of file in file: " << name << endl; else if (ferror(fin)) cerr << "error reading file: " << name << endl; else cerr << "unknown error reading file: " << name << endl; fclose(fin); fclose(fout); return 2; } size_t nwritten = fwrite(buff, 1, nread, fout); if (nwritten != nread) { cerr << "error writing file: " << file << endl; fclose(fin); fclose(fout); return 3; } nleft -= nwritten; } fread(buff, 1, 1, fin); if (!feof(fin)) { cerr << "file size has changed; file: " << name << endl; fclose(fin); fclose(fout); return 4; } fclose(fin); cout << "added file: " << name << endl; } fclose(fout); return 0; } int main(int argc, char **argv) { if (argc != 3) { usage(); return 1; } return make_d2(argv[1], argv[2]); } <commit_msg>Refactoring.<commit_after> #include <string> #include <list> #include <iostream> #include <algorithm> #include <cstdio> #include <cstring> #include <windows.h> #include <stdint.h> using std::string; using std::list; using std::cout; using std::cerr; using std::endl; using std::min; #ifdef _MSC_VER #pragma warning(disable: 4996) #endif #define HEADER_LEN 8 #define NUM_ENTRIES 512 #define ENTRY_SIZE (12 + 4 + 4) #define START_OFFSET (HEADER_LEN + NUM_ENTRIES * ENTRY_SIZE) typedef struct { string name; uint32_t offset; uint32_t size; } d2_entry; void usage() { cerr << "Usage: d2 dir file" << endl; } int make_d2(string dir, string file) { list<d2_entry> entries; bool limit_reached = false; WIN32_FIND_DATA wfd; uint64_t offset = START_OFFSET; HANDLE h = FindFirstFile((dir + "\\*").c_str(), &wfd); BOOL b = (h != INVALID_HANDLE_VALUE); while (b) { if ((wfd.dwFileAttributes & (FILE_ATTRIBUTE_ARCHIVE | FILE_ATTRIBUTE_DIRECTORY)) == FILE_ATTRIBUTE_ARCHIVE) { if (entries.size() >= 512) { cerr << "512 file limit reached; skipping file: " << wfd.cFileName << endl; limit_reached = true; } else if (wfd.nFileSizeHigh) { cerr << "skipping file larger than 4GB: " << wfd.cFileName << endl; limit_reached = true; } else if (offset + wfd.nFileSizeLow > 0x100000000) { cerr << "4GB file limit reached; skipping file: " << wfd.cFileName << endl; limit_reached = true; } else { string name = wfd.cAlternateFileName; if (name.empty()) name = wfd.cFileName; d2_entry entry = {name, (uint32_t)offset, wfd.nFileSizeLow}; entries.push_back(entry); offset += wfd.nFileSizeLow; } } b = FindNextFile(h,&wfd); } FindClose(h); if (limit_reached) return 1; d2_entry empty = {"", 0, 0}; while (entries.size() < 512) entries.push_back(empty); FILE *fout = fopen(file.c_str(), "wb"); char header[HEADER_LEN] = {'v', 's', ' ', 'd', '2', 0, 0, 0}; fwrite(header, 1, sizeof(header), fout); for (list<d2_entry>::const_iterator it = entries.begin(); it != entries.end(); ++it) { char name[12]; strncpy(name, it->name.c_str(), sizeof(name)); fwrite(name, 1, sizeof(name), fout); fwrite(&it->offset, 1, sizeof(it->offset), fout); fwrite(&it->size, 1, sizeof(it->size), fout); } for (list<d2_entry>::const_iterator it = entries.begin(); it != entries.end(); ++it) { if (it->name.empty()) continue; string name = dir + "\\" + it->name; FILE *fin = fopen(name.c_str(), "rb"); if (!fin) { cerr << "error opening file: " << name << endl; } char buff[32768]; size_t nleft = it->size; while (nleft > 0) { size_t req = min(nleft, sizeof(buff)); size_t nread = fread(buff, 1, req, fin); if (nread != req) { if (feof(fin)) cerr << "unexpected end of file in file: " << name << endl; else if (ferror(fin)) cerr << "error reading file: " << name << endl; else cerr << "unknown error reading file: " << name << endl; fclose(fin); fclose(fout); return 2; } size_t nwritten = fwrite(buff, 1, nread, fout); if (nwritten != nread) { cerr << "error writing file: " << file << endl; fclose(fin); fclose(fout); return 3; } nleft -= nwritten; } fread(buff, 1, 1, fin); if (!feof(fin)) { cerr << "file size has changed; file: " << name << endl; fclose(fin); fclose(fout); return 4; } fclose(fin); cout << "added file: " << name << endl; } fclose(fout); return 0; } int main(int argc, char **argv) { if (argc != 3) { usage(); return 1; } return make_d2(argv[1], argv[2]); } <|endoftext|>
<commit_before>/************************************************* * MP Misc Functions Source File * * (C) 1999-2006 The Botan Project * *************************************************/ #include <botan/mp_core.h> #include <botan/mp_asm.h> namespace Botan { extern "C" { /************************************************* * Core Division Operation * *************************************************/ u32bit bigint_divcore(word q, word y1, word y2, word x1, word x2, word x3) { word y0 = 0; y2 = word_madd2(q, y2, y0, &y0); y1 = word_madd2(q, y1, y0, &y0); if(y0 > x1) return 1; if(y0 < x1) return 0; if(y1 > x2) return 1; if(y1 < x2) return 0; if(y2 > x3) return 1; if(y2 < x3) return 0; return 0; } /************************************************* * Compare two MP integers * *************************************************/ s32bit bigint_cmp(const word x[], u32bit x_size, const word y[], u32bit y_size) { if(x_size < y_size) { return (-bigint_cmp(y, y_size, x, x_size)); } while(x_size > y_size) { if(x[x_size-1]) return 1; x_size--; } for(u32bit j = x_size; j > 0; --j) { if(x[j-1] > y[j-1]) return 1; if(x[j-1] < y[j-1]) return -1; } return 0; } /************************************************* * Do a 2-word/1-word Division * *************************************************/ word bigint_divop(word n1, word n0, word d) { word high = n1 % d, quotient = 0; for(u32bit j = 0; j != MP_WORD_BITS; ++j) { word high_top_bit = (high & MP_WORD_TOP_BIT); high <<= 1; high |= (n0 >> MP_WORD_BITS-1-j) & 1; quotient <<= 1; if(high_top_bit || high >= d) { high -= d; quotient |= 1; } } return quotient; } /************************************************* * Do a 2-word/1-word Modulo * *************************************************/ word bigint_modop(word n1, word n0, word d) { word z = bigint_divop(n1, n0, d); word dummy = 0; z = word_madd2(z, d, dummy, &dummy); return (n0-z); } /************************************************* * Do a word*word->2-word Multiply * *************************************************/ void bigint_wordmul(word a, word b, word* out_low, word* out_high) { const u32bit MP_HWORD_BITS = MP_WORD_BITS / 2; const word MP_HWORD_MASK = ((word)1 << MP_HWORD_BITS) - 1; const word a_hi = (a >> MP_HWORD_BITS); const word a_lo = (a & MP_HWORD_MASK); const word b_hi = (b >> MP_HWORD_BITS); const word b_lo = (b & MP_HWORD_MASK); word x0 = a_hi * b_hi; word x1 = a_lo * b_hi; word x2 = a_hi * b_lo; word x3 = a_lo * b_lo; x2 += x3 >> (MP_HWORD_BITS); x2 += x1; if(x2 < x1) x0 += ((word)1 << MP_HWORD_BITS); *out_high = x0 + (x2 >> MP_HWORD_BITS); *out_low = ((x2 & MP_HWORD_MASK) << MP_HWORD_BITS) + (x3 & MP_HWORD_MASK); } } } <commit_msg>Add parenthesis to make the order of evaluation in an expression more obvious<commit_after>/************************************************* * MP Misc Functions Source File * * (C) 1999-2006 The Botan Project * *************************************************/ #include <botan/mp_core.h> #include <botan/mp_asm.h> namespace Botan { extern "C" { /************************************************* * Core Division Operation * *************************************************/ u32bit bigint_divcore(word q, word y1, word y2, word x1, word x2, word x3) { word y0 = 0; y2 = word_madd2(q, y2, y0, &y0); y1 = word_madd2(q, y1, y0, &y0); if(y0 > x1) return 1; if(y0 < x1) return 0; if(y1 > x2) return 1; if(y1 < x2) return 0; if(y2 > x3) return 1; if(y2 < x3) return 0; return 0; } /************************************************* * Compare two MP integers * *************************************************/ s32bit bigint_cmp(const word x[], u32bit x_size, const word y[], u32bit y_size) { if(x_size < y_size) { return (-bigint_cmp(y, y_size, x, x_size)); } while(x_size > y_size) { if(x[x_size-1]) return 1; x_size--; } for(u32bit j = x_size; j > 0; --j) { if(x[j-1] > y[j-1]) return 1; if(x[j-1] < y[j-1]) return -1; } return 0; } /************************************************* * Do a 2-word/1-word Division * *************************************************/ word bigint_divop(word n1, word n0, word d) { word high = n1 % d, quotient = 0; for(u32bit j = 0; j != MP_WORD_BITS; ++j) { word high_top_bit = (high & MP_WORD_TOP_BIT); high <<= 1; high |= (n0 >> (MP_WORD_BITS-1-j)) & 1; quotient <<= 1; if(high_top_bit || high >= d) { high -= d; quotient |= 1; } } return quotient; } /************************************************* * Do a 2-word/1-word Modulo * *************************************************/ word bigint_modop(word n1, word n0, word d) { word z = bigint_divop(n1, n0, d); word dummy = 0; z = word_madd2(z, d, dummy, &dummy); return (n0-z); } /************************************************* * Do a word*word->2-word Multiply * *************************************************/ void bigint_wordmul(word a, word b, word* out_low, word* out_high) { const u32bit MP_HWORD_BITS = MP_WORD_BITS / 2; const word MP_HWORD_MASK = ((word)1 << MP_HWORD_BITS) - 1; const word a_hi = (a >> MP_HWORD_BITS); const word a_lo = (a & MP_HWORD_MASK); const word b_hi = (b >> MP_HWORD_BITS); const word b_lo = (b & MP_HWORD_MASK); word x0 = a_hi * b_hi; word x1 = a_lo * b_hi; word x2 = a_hi * b_lo; word x3 = a_lo * b_lo; x2 += x3 >> (MP_HWORD_BITS); x2 += x1; if(x2 < x1) x0 += ((word)1 << MP_HWORD_BITS); *out_high = x0 + (x2 >> MP_HWORD_BITS); *out_low = ((x2 & MP_HWORD_MASK) << MP_HWORD_BITS) + (x3 & MP_HWORD_MASK); } } } <|endoftext|>
<commit_before>#include <sys/types.h> #include <sys/mman.h> #include <stdlib.h> #include <unistd.h> //#include "atexit.h" //#include "thread_private.h" #include <iostream> #include <vector> #include <unordered_map> #include <map> #include <algorithm> #include <sstream> #include "xstring.h" #define NO_ALLOC_MACRO_OVERRIDE #include "mem_tracker.h" using namespace std; /** actually define the global (extern-ed) variables here * and do some initialization directly at the beginning of main() */ unsigned long long CALL_COUNT_NEW; unsigned long long CALL_COUNT_DELETE; unsigned long long MEMORY_COUNT_NEW; unsigned long long MEMORY_COUNT_DELETE; /** this flag activates the tracking */ bool USE_MEM_TRACKER; /** temporary save variables provided during "delete" call " */ const char* ____DELETE_FILENAME____; size_t ____DELETE_LINE____; /** the two main "databases" for the pointers */ tPtrDataStorage ALLOCATED_PTRS; tPtrDataList ARCHIVED_PTRS; /** no args ctor */ PtrData::PtrData() : p(nullptr), size(0), allocated(false), deleted(false), new_call(), delete_call() { } /** copy ctor */ PtrData::PtrData(const PtrData& obj) : p(obj.p), size(obj.size), allocated(obj.allocated), deleted(obj.deleted), new_call(obj.new_call), delete_call(obj.delete_call) { } /** keeps all the data for one pointer */ PtrData::PtrData(void* ptr, const size_t& len) : p(ptr), size(len), allocated(true), deleted(false), new_call(), delete_call() { } /** handle new-call */ void* __handle_new_request(size_t size, const char* fn, size_t line) _GLIBCXX_THROW(std::bad_alloc) { if(USE_MEM_TRACKER) { CALL_COUNT_NEW++; MEMORY_COUNT_NEW += size; } void* out = malloc(size); if(USE_MEM_TRACKER) { USE_MEM_TRACKER = false; ALLOCATED_PTRS[out] = PtrData(out, size); ALLOCATED_PTRS[out].new_call = make_pair(string(fn), line); USE_MEM_TRACKER = true; } return out; } /** save meta-data (filename, lineno) into tmp-vars for __handle_delete_request */ void __handle_delete_meta_data(const char* fn, const size_t& line) { ____DELETE_FILENAME____ = fn; ____DELETE_LINE____ = line; } /** handle delete-call */ void __handle_delete_request(void* ptr) { if(USE_MEM_TRACKER) { tPtrDataStorageIter i = ALLOCATED_PTRS.find(ptr); if(i != ALLOCATED_PTRS.end()) { USE_MEM_TRACKER = false; // move PtrData instance from ALLOCATED to ARCHIVED ARCHIVED_PTRS.push_back(ALLOCATED_PTRS[ptr]); ALLOCATED_PTRS.erase(ptr); ARCHIVED_PTRS.back().deleted = true; ARCHIVED_PTRS.back().delete_call = \ make_pair(string(____DELETE_FILENAME____), ____DELETE_LINE____); CALL_COUNT_DELETE++; MEMORY_COUNT_DELETE += ARCHIVED_PTRS.back().size; USE_MEM_TRACKER = true; } } free(ptr); } /** Global "new" operator overload */ void* operator new(size_t size, const char* fn, size_t line) _GLIBCXX_THROW(std::bad_alloc) { return __handle_new_request(size, fn, line); } void* operator new[](size_t size, const char* fn, size_t line) _GLIBCXX_THROW(std::bad_alloc) { return __handle_new_request(size, fn, line); } /** Global "delete" operator overload */ void operator delete(void* ptr) _GLIBCXX_USE_NOEXCEPT { __handle_delete_request(ptr); } void operator delete[](void* ptr) _GLIBCXX_USE_NOEXCEPT { __handle_delete_request(ptr); } /** return delete or new statistics */ string __print_memory_details(bool delete_mode, bool verbose) { stringstream ss; tOpPtrDataMap pos2ptr; tPtrDataList data; // generate reverse table if(!delete_mode) { for(tPtrDataStorage::value_type& i : ALLOCATED_PTRS) { pos2ptr[i.second.new_call].push_back(i.second); data.push_back(i.second); } } else { for(PtrData& i : ARCHIVED_PTRS) { pos2ptr[i.delete_call].push_back(i); data.push_back(i); } } // directly return, if no details are available if(data.size() == 0) return ""; // find PtrData instance allocating most bytes tPtrDataIter max_iter = std::max_element(data.begin(), data.end(), \ [](const PtrData& a, const PtrData& b) \ { return (a.size <= b.size); } \ ); // calc/set formatting vars size_t max_size = max_iter->size; size_t max_width = 0; size_t max_cols = 6; while(max_size) { max_size /= 10.0; max_width++; } // go over generated map and gen. results for(tOpPtrDataIter i=pos2ptr.begin(); i!=pos2ptr.end(); ++i) { // calculate sum of bytes alloced/deleted unsigned long long sum = 0; std::for_each(i->second.begin(), i->second.end(), \ [&](const PtrData& x) { sum += x.size; } ); ss << "[i] " << setw(5) << i->first.first << setw(10) << " line: " << setw(6) << i->first.second << setw(10) << "#calls: " << setw(8) << i->second.size() << setw(10) << " bytes: " << setw(16) << sum << endl; // print: ptr-addr[size] x (max_cols) each line size_t col = 0; if(verbose) { ss << "[E] "; for(tPtrDataIter p=i->second.begin(); p!=i->second.end(); ++p, col++) { ss << p->p << "[" << setw(max_width) << p->size << "]"; ss << (((p+1) != i->second.end()) ? ", " : "\n"); if((col % max_cols) == (max_cols - 1)) ss << endl << " "; } } } return ss.str(); } /** show some results and hints to search the leaks */ string get_memory_tracker_results(bool verbose) { long m_diff = (MEMORY_COUNT_NEW - MEMORY_COUNT_DELETE); long ptr_diff = CALL_COUNT_NEW - CALL_COUNT_DELETE; stringstream ss; ss << endl; ss << "[STATS] Memory tracking overview:" << endl; ss << endl; string sep = " | "; size_t pad = 14; size_t loff = 8; size_t hline = 82; ss << setw(pad+loff) << "tracked" << sep << setw(pad) << "tracked" << sep << setw(pad) << "leaked" << sep << setw(pad) << "leaked" << sep << endl; ss << setw(pad+loff) << "calls" << sep << setw(pad) << "bytes" << sep << setw(pad) << "calls" << sep << setw(pad) << "bytes" << sep << endl; ss << setw(hline) << setfill('-') << "" << setfill(' ') << endl; ss << setw(loff) << "NEW" << setw(pad) << CALL_COUNT_NEW << sep << setw(pad) << MEMORY_COUNT_NEW << sep << setw(pad) << "n/a" << sep << setw(pad) << "n/a" << sep << endl; ss << setw(hline) << setfill('-') << "" << setfill(' ') << endl; ss << setw(loff) << "DELETE" << setw(pad) << CALL_COUNT_DELETE << sep << setw(pad) << MEMORY_COUNT_DELETE << sep << setw(pad) << ptr_diff << sep << setw(pad) << m_diff << sep << endl; if(m_diff > 0) { ss << endl; ss << "[LEAK DATA] showing not deleted (bad) calls:" << endl; ss << __print_memory_details(false, verbose); } else cout << "[+] no leaks found!" << endl; ss << endl; if(verbose) { if(CALL_COUNT_DELETE > 0) { ss << "[DELETE DATA] showing deleted (good) calls:" << endl; ss << __print_memory_details(true, verbose); ss << endl; } else cout << "[i] no delete calls tracked..." << endl; } return ss.str(); } // saving pointer to original ::exit() function call auto original_exit = &::exit; /** To avoid a segfault on exit, if MEM_TRACKER is used. * (Segfault due to the automated cleanup of MemTracker datastructures on leaving scope) */ void exit(int status) throw() { ALLOCATED_PTRS.clear(); ARCHIVED_PTRS.clear(); // calling "real" exit() original_exit(status); } /** initilize the memory tracker variables */ void init_memory_tracker() { CALL_COUNT_NEW = 0; CALL_COUNT_DELETE = 0; MEMORY_COUNT_NEW = 0; MEMORY_COUNT_DELETE = 0; ____DELETE_FILENAME____ = ""; ____DELETE_LINE____ = 0; // set to true to start tracking! USE_MEM_TRACKER = false; ALLOCATED_PTRS.clear(); ARCHIVED_PTRS.clear(); } <commit_msg>exit still not working good<commit_after>#include <sys/types.h> #include <sys/mman.h> #include <stdlib.h> #include <unistd.h> //#include "atexit.h" //#include "thread_private.h" #include <iostream> #include <vector> #include <unordered_map> #include <map> #include <algorithm> #include <sstream> #include "xstring.h" #define NO_ALLOC_MACRO_OVERRIDE // NEED TWO MEM_TRACKER header files // one for this .cc file // another one for the target source files #include "mem_tracker.h" using namespace std; /** actually define the global (extern-ed) variables here * and do some initialization directly at the beginning of main() */ unsigned long long CALL_COUNT_NEW; unsigned long long CALL_COUNT_DELETE; unsigned long long MEMORY_COUNT_NEW; unsigned long long MEMORY_COUNT_DELETE; /** this flag activates the tracking */ bool USE_MEM_TRACKER; /** temporary save variables provided during "delete" call " */ const char* ____DELETE_FILENAME____; size_t ____DELETE_LINE____; /** the two main "databases" for the pointers */ tPtrDataStorage ALLOCATED_PTRS; tPtrDataList ARCHIVED_PTRS; /** no args ctor */ PtrData::PtrData() : p(nullptr), size(0), allocated(false), deleted(false), new_call(), delete_call() { } /** copy ctor */ PtrData::PtrData(const PtrData& obj) : p(obj.p), size(obj.size), allocated(obj.allocated), deleted(obj.deleted), new_call(obj.new_call), delete_call(obj.delete_call) { } /** keeps all the data for one pointer */ PtrData::PtrData(void* ptr, const size_t& len) : p(ptr), size(len), allocated(true), deleted(false), new_call(), delete_call() { } /** handle new-call */ void* __handle_new_request(size_t size, const char* fn, size_t line) _GLIBCXX_THROW(std::bad_alloc) { if(USE_MEM_TRACKER) { CALL_COUNT_NEW++; MEMORY_COUNT_NEW += size; } void* out = malloc(size); if(USE_MEM_TRACKER) { USE_MEM_TRACKER = false; ALLOCATED_PTRS[out] = PtrData(out, size); ALLOCATED_PTRS[out].new_call = make_pair(string(fn), line); USE_MEM_TRACKER = true; } return out; } /** save meta-data (filename, lineno) into tmp-vars for __handle_delete_request */ void __handle_delete_meta_data(const char* fn, const size_t& line) { ____DELETE_FILENAME____ = fn; ____DELETE_LINE____ = line; } /** handle delete-call */ void __handle_delete_request(void* ptr) { if(USE_MEM_TRACKER) { tPtrDataStorageIter i = ALLOCATED_PTRS.find(ptr); if(i != ALLOCATED_PTRS.end()) { USE_MEM_TRACKER = false; // move PtrData instance from ALLOCATED to ARCHIVED ARCHIVED_PTRS.push_back(ALLOCATED_PTRS[ptr]); ALLOCATED_PTRS.erase(ptr); ARCHIVED_PTRS.back().deleted = true; ARCHIVED_PTRS.back().delete_call = \ make_pair(string(____DELETE_FILENAME____), ____DELETE_LINE____); CALL_COUNT_DELETE++; MEMORY_COUNT_DELETE += ARCHIVED_PTRS.back().size; USE_MEM_TRACKER = true; } } free(ptr); } /** Global "new" operator overload */ void* operator new(size_t size, const char* fn, size_t line) _GLIBCXX_THROW(std::bad_alloc) { return __handle_new_request(size, fn, line); } void* operator new[](size_t size, const char* fn, size_t line) _GLIBCXX_THROW(std::bad_alloc) { return __handle_new_request(size, fn, line); } /** Global "delete" operator overload */ void operator delete(void* ptr) _GLIBCXX_USE_NOEXCEPT { __handle_delete_request(ptr); } void operator delete[](void* ptr) _GLIBCXX_USE_NOEXCEPT { __handle_delete_request(ptr); } /** return delete or new statistics */ string __print_memory_details(bool delete_mode, bool verbose) { stringstream ss; tOpPtrDataMap pos2ptr; tPtrDataList data; // generate reverse table if(!delete_mode) { for(tPtrDataStorage::value_type& i : ALLOCATED_PTRS) { pos2ptr[i.second.new_call].push_back(i.second); data.push_back(i.second); } } else { for(PtrData& i : ARCHIVED_PTRS) { pos2ptr[i.delete_call].push_back(i); data.push_back(i); } } // directly return, if no details are available if(data.size() == 0) return ""; // find PtrData instance allocating most bytes tPtrDataIter max_iter = std::max_element(data.begin(), data.end(), \ [](const PtrData& a, const PtrData& b) \ { return (a.size <= b.size); } \ ); // calc/set formatting vars size_t max_size = max_iter->size; size_t max_width = 0; size_t max_cols = 6; while(max_size) { max_size /= 10.0; max_width++; } // go over generated map and gen. results for(tOpPtrDataIter i=pos2ptr.begin(); i!=pos2ptr.end(); ++i) { // calculate sum of bytes alloced/deleted unsigned long long sum = 0; std::for_each(i->second.begin(), i->second.end(), \ [&](const PtrData& x) { sum += x.size; } ); ss << "[i] " << setw(5) << i->first.first << setw(10) << " line: " << setw(6) << i->first.second << setw(10) << "#calls: " << setw(8) << i->second.size() << setw(10) << " bytes: " << setw(16) << sum << endl; // print: ptr-addr[size] x (max_cols) each line size_t col = 0; if(verbose) { ss << "[E] "; for(tPtrDataIter p=i->second.begin(); p!=i->second.end(); ++p, col++) { ss << p->p << "[" << setw(max_width) << p->size << "]"; ss << (((p+1) != i->second.end()) ? ", " : "\n"); if((col % max_cols) == (max_cols - 1)) ss << endl << " "; } } } return ss.str(); } /** show some results and hints to search the leaks */ string get_memory_tracker_results(bool verbose) { long m_diff = (MEMORY_COUNT_NEW - MEMORY_COUNT_DELETE); long ptr_diff = CALL_COUNT_NEW - CALL_COUNT_DELETE; stringstream ss; ss << endl; ss << "[STATS] Memory tracking overview:" << endl; ss << endl; string sep = " | "; size_t pad = 14; size_t loff = 8; size_t hline = 82; ss << setw(pad+loff) << "tracked" << sep << setw(pad) << "tracked" << sep << setw(pad) << "leaked" << sep << setw(pad) << "leaked" << sep << endl; ss << setw(pad+loff) << "calls" << sep << setw(pad) << "bytes" << sep << setw(pad) << "calls" << sep << setw(pad) << "bytes" << sep << endl; ss << setw(hline) << setfill('-') << "" << setfill(' ') << endl; ss << setw(loff) << "NEW" << setw(pad) << CALL_COUNT_NEW << sep << setw(pad) << MEMORY_COUNT_NEW << sep << setw(pad) << "n/a" << sep << setw(pad) << "n/a" << sep << endl; ss << setw(hline) << setfill('-') << "" << setfill(' ') << endl; ss << setw(loff) << "DELETE" << setw(pad) << CALL_COUNT_DELETE << sep << setw(pad) << MEMORY_COUNT_DELETE << sep << setw(pad) << ptr_diff << sep << setw(pad) << m_diff << sep << endl; if(m_diff > 0) { ss << endl; ss << "[LEAK DATA] showing not deleted (bad) calls:" << endl; ss << __print_memory_details(false, verbose); } else cout << "[+] no leaks found!" << endl; ss << endl; if(verbose) { if(CALL_COUNT_DELETE > 0) { ss << "[DELETE DATA] showing deleted (good) calls:" << endl; ss << __print_memory_details(true, verbose); ss << endl; } else cout << "[i] no delete calls tracked..." << endl; } return ss.str(); } // saving pointer to original ::exit() function call auto original_exit = &::exit; /** To avoid a segfault on exit, if MEM_TRACKER is used. * (Segfault due to the automated cleanup of MemTracker datastructures on leaving scope) */ void exit(int status) throw() { ALLOCATED_PTRS.clear(); ARCHIVED_PTRS.clear(); // calling "real" exit() original_exit(status); } /** initilize the memory tracker variables */ void init_memory_tracker() { CALL_COUNT_NEW = 0; CALL_COUNT_DELETE = 0; MEMORY_COUNT_NEW = 0; MEMORY_COUNT_DELETE = 0; ____DELETE_FILENAME____ = ""; ____DELETE_LINE____ = 0; // set to true to start tracking! USE_MEM_TRACKER = false; ALLOCATED_PTRS.clear(); ARCHIVED_PTRS.clear(); } <|endoftext|>
<commit_before>#include <iostream> #include <vector> #include "trie/double_array.h" #include "trie/char_stream_vector.h" const unsigned utf8_len_table[] = { 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,6,6,1,1 }; bool is_hiragana(const char* s) { unsigned char c1 = s[0]; unsigned char c2 = s[1]; unsigned char c3 = s[2]; if (c1 == 0xE3) { if (c2 == 0x81) { if (c3 >= 0x81) return true; } else if (c2 == 0x82) { if (c3 <= 0x9F) return true; } } return false; } bool is_katakana(const char* s) { unsigned char c1 = s[0]; unsigned char c2 = s[1]; unsigned char c3 = s[2]; if (c1 == 0xE3) { if (c2 == 0x82) { if (c3 >= 0xA1) return true; } else if (c2 >= 0x83 && c2 <= 0x86) { return true; } else if (c2 == 0x87) { if (c3 <= 0xBF) return true; } } return false; } char char_type(const char*& s) { if(s[0] & 0x80) { if(utf8_len_table[static_cast<unsigned char>(s[0])]!=3) { s += utf8_len_table[s[0]]; return 4; // default; } s += 3; if(is_hiragana(s-3)) return 1; // hiragana if(is_katakana(s-3)) return 2; // katakana return 4; } else { char c=*(s++); if('0' <= c && c <= '9') return 0; // numeric switch(c) { case ',': case '.': case '!': case '?': return 3; // symbol default: return 4; // default } } } // for utf8 const char* next(const char* s) { for(unsigned char c=*(++s); c != '\0' && c & 0x80 && !(c & 0x40); c=*(++s)); return s; } // for utf8 const char* prev(const char* s) { for(unsigned char c=*(--s); c & 0x80 && !(c & 0x40); c=*(--s)); return s; } struct Callback { Callback(std::vector<int>& cut_score) : cut_score(cut_score) {} void operator()(const char* key, unsigned start, unsigned end, int score, unsigned type) const { //std::cout << type << "#" << std::string(key+start, key+end) << " => " << score << std::endl; unsigned pos=0; switch(type) { case 0: pos = next(key+end)-key; break; case 1: pos = end; break; case 2: pos = start; break; case 3: pos = prev(key+start)-key; break; default: pos = prev(key+end)-key; } /* if(pos > 0 && pos < cut_score.size()) std::cout <<type<<"#"<<start<<'~'<<end<< " => " << pos <<'/'<< cut_score.size() << " = " << score << std::endl; */ if(pos < cut_score.size()) cut_score[pos] += score; } std::vector<int>& cut_score; }; int main(int argc, char** argv) { if(argc != 3) { std::cerr << "Usage: mimic-split <index> <text-file>" << std::endl; return 1; } DoubleArray da(argv[1]); CharStreamVector csv(argv[2]); for(unsigned i=0; i < csv.size(); i++) { const char* line = csv[i].rest(); unsigned line_len = strlen(line); std::vector<int> cut_score(line_len); Callback fn(cut_score); // if(line_len != 0) { const char* line2 = line; char prev_type = char_type(line2); while(*line2 != '\0') { unsigned pos = line2-line; char type = char_type(line2); cut_score[pos] = da.char_type_link_score(prev_type, type); prev_type = type; } } /* for(unsigned pos=1; pos < line_len; pos++) { std::cout << " " << pos << "#" << cut_score[pos] << std::endl; } */ // for(unsigned pos=0; pos < line_len; pos++) da.each_common_prefix(line, pos, fn); unsigned prev=0; for(unsigned pos=1; pos < line_len; pos++) { if(cut_score[pos] > 0) { std::cout << std::string(line+prev, line+pos) << " "; prev=pos; } //std::cout << " " << pos << "#" << cut_score[pos] << std::endl; } std::cout << std::string(line+prev) << std::endl; } return 0; } <commit_msg>不正なUTF-8を分割しようとした際のchar_type関数の不具合修正(まだ不完全)<commit_after>#include <iostream> #include <vector> #include "trie/double_array.h" #include "trie/char_stream_vector.h" const unsigned utf8_len_table[] = { 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,6,6,1,1 }; bool is_hiragana(const char* s) { unsigned char c1 = s[0]; unsigned char c2 = s[1]; unsigned char c3 = s[2]; if (c1 == 0xE3) { if (c2 == 0x81) { if (c3 >= 0x81) return true; } else if (c2 == 0x82) { if (c3 <= 0x9F) return true; } } return false; } bool is_katakana(const char* s) { unsigned char c1 = s[0]; unsigned char c2 = s[1]; unsigned char c3 = s[2]; if (c1 == 0xE3) { if (c2 == 0x82) { if (c3 >= 0xA1) return true; } else if (c2 >= 0x83 && c2 <= 0x86) { return true; } else if (c2 == 0x87) { if (c3 <= 0xBF) return true; } } return false; } char char_type(const char*& s) { if(s[0] & 0x80) { if(utf8_len_table[static_cast<unsigned char>(s[0])]!=3) { s += utf8_len_table[s[0]]; return 4; // default; } s += 3; if(is_hiragana(s-3)) return 1; // hiragana if(is_katakana(s-3)) return 2; // katakana return 4; } else { char c=*(s++); if('0' <= c && c <= '9') return 0; // numeric switch(c) { case ',': case '.': case '!': case '?': return 3; // symbol default: return 4; // default } } } // for utf8 const char* next(const char* s) { for(unsigned char c=*(++s); c != '\0' && c & 0x80 && !(c & 0x40); c=*(++s)); return s; } // for utf8 const char* prev(const char* s) { for(unsigned char c=*(--s); c & 0x80 && !(c & 0x40); c=*(--s)); return s; } struct Callback { Callback(std::vector<int>& cut_score) : cut_score(cut_score) {} void operator()(const char* key, unsigned start, unsigned end, int score, unsigned type) const { //std::cout << type << "#" << std::string(key+start, key+end) << " => " << score << std::endl; unsigned pos=0; switch(type) { case 0: pos = next(key+end)-key; break; case 1: pos = end; break; case 2: pos = start; break; case 3: pos = prev(key+start)-key; break; default: pos = prev(key+end)-key; } /* if(pos > 0 && pos < cut_score.size()) std::cout <<type<<"#"<<start<<'~'<<end<< " => " << pos <<'/'<< cut_score.size() << " = " << score << std::endl; */ if(pos < cut_score.size()) cut_score[pos] += score; } std::vector<int>& cut_score; }; int main(int argc, char** argv) { if(argc != 3) { std::cerr << "Usage: mimic-split <index> <text-file>" << std::endl; return 1; } DoubleArray da(argv[1]); CharStreamVector csv(argv[2]); for(unsigned i=0; i < csv.size(); i++) { const char* line = csv[i].rest(); unsigned line_len = strlen(line); std::vector<int> cut_score(line_len); Callback fn(cut_score); // if(line_len != 0) { const char* line2 = line; char prev_type = char_type(line2); while(line < line2 && line2 < line+line_len) { // std::cerr << (int)line2 << std::endl; unsigned pos = line2-line; char type = char_type(line2); cut_score[pos] = da.char_type_link_score(prev_type, type); prev_type = type; } } /* for(unsigned pos=1; pos < line_len; pos++) { std::cout << " " << pos << "#" << cut_score[pos] << std::endl; } */ // for(unsigned pos=0; pos < line_len; pos++) da.each_common_prefix(line, pos, fn); unsigned prev=0; for(unsigned pos=1; pos < line_len; pos++) { if(cut_score[pos] > 0) { std::cout << std::string(line+prev, line+pos) << " "; prev=pos; } //std::cout << " " << pos << "#" << cut_score[pos] << std::endl; } std::cout << std::string(line+prev) << std::endl; } return 0; } <|endoftext|>
<commit_before>#include <fstream> #include <exception> #include <tclap/CmdLine.h> #include "io.hpp" namespace nest { namespace mc { namespace io { /// read simulation options from json file with name fname /// if file name is empty or if file is not a valid json file a default /// set of parameters is returned : /// 1000 cells, 500 synapses per cell, 100 compartments per segment cl_options read_options(int argc, char** argv) { // set default options const cl_options default_options{"", 1000, 500, 100, 100., 0.025, false}; cl_options options; // parse command line arguments try { TCLAP::CmdLine cmd("mod2c performance benchmark harness", ' ', "0.1"); TCLAP::ValueArg<uint32_t> ncells_arg( "n", "ncells", "total number of cells in the model", false, 1000, "non negative integer"); TCLAP::ValueArg<uint32_t> nsynapses_arg( "s", "nsynapses", "number of synapses per cell", false, 500, "non negative integer"); TCLAP::ValueArg<uint32_t> ncompartments_arg( "c", "ncompartments", "number of compartments per segment", false, 100, "non negative integer"); TCLAP::ValueArg<std::string> ifile_arg( "i", "ifile", "json file with model parameters", false, "","file name string"); TCLAP::ValueArg<double> tfinal_arg( "t", "tfinal", "time to simulate in ms", false, 100., "positive real number"); TCLAP::ValueArg<double> dt_arg( "d", "dt", "time step size in ms", false, 0.025, "positive real number"); TCLAP::SwitchArg all_to_all_arg( "a","alltoall","all to all network", cmd, false); cmd.add(ncells_arg); cmd.add(nsynapses_arg); cmd.add(ncompartments_arg); cmd.add(ifile_arg); cmd.add(dt_arg); cmd.add(tfinal_arg); cmd.parse(argc, argv); options.cells = ncells_arg.getValue(); options.synapses_per_cell = nsynapses_arg.getValue(); options.compartments_per_segment = ncompartments_arg.getValue(); options.ifname = ifile_arg.getValue(); options.tfinal = tfinal_arg.getValue(); options.dt = dt_arg.getValue(); options.all_to_all = all_to_all_arg.getValue(); } // catch any exceptions in command line handling catch(TCLAP::ArgException &e) { std::cerr << "error: parsing command line arguments:\n " << e.error() << " for arg " << e.argId() << "\n"; exit(1); } if(options.ifname == "") { options.check(); return options; } else { std::ifstream fid(options.ifname, std::ifstream::in); if(fid.is_open()) { // read json data in input file nlohmann::json fopts; fid >> fopts; try { options.cells = fopts["cells"]; options.synapses_per_cell = fopts["synapses"]; options.compartments_per_segment = fopts["compartments"]; options.dt = fopts["dt"]; options.tfinal = fopts["tfinal"]; options.all_to_all = fopts["all_to_all"]; } catch(std::domain_error e) { std::cerr << "error: unable to open parameters in " << options.ifname << " : " << e.what() << "\n"; exit(1); } catch(std::exception e) { std::cerr << "error: unable to open parameters in " << options.ifname << "\n"; exit(1); } options.check(); return options; } } return default_options; } std::ostream& operator<<(std::ostream& o, const cl_options& options) { o << "simultion options:\n"; o << " cells : " << options.cells << "\n"; o << " compartments/segment : " << options.compartments_per_segment << "\n"; o << " synapses/cell : " << options.synapses_per_cell << "\n"; o << " simulation time : " << options.tfinal << "\n"; o << " dt : " << options.dt << "\n"; o << " all to all network : " << (options.all_to_all ? "yes" : "no") << "\n"; o << " input file name : " << options.ifname << "\n"; return o; } } // namespace io } // namespace mc } // namespace nest <commit_msg>rename cl_options.check -> check_and_normalize<commit_after>#include <fstream> #include <exception> #include <tclap/CmdLine.h> #include "io.hpp" namespace nest { namespace mc { namespace io { /// read simulation options from json file with name fname /// if file name is empty or if file is not a valid json file a default /// set of parameters is returned : /// 1000 cells, 500 synapses per cell, 100 compartments per segment cl_options read_options(int argc, char** argv) { // set default options const cl_options default_options{"", 1000, 500, 100, 100., 0.025, false}; cl_options options; // parse command line arguments try { TCLAP::CmdLine cmd("mod2c performance benchmark harness", ' ', "0.1"); TCLAP::ValueArg<uint32_t> ncells_arg( "n", "ncells", "total number of cells in the model", false, 1000, "non negative integer"); TCLAP::ValueArg<uint32_t> nsynapses_arg( "s", "nsynapses", "number of synapses per cell", false, 500, "non negative integer"); TCLAP::ValueArg<uint32_t> ncompartments_arg( "c", "ncompartments", "number of compartments per segment", false, 100, "non negative integer"); TCLAP::ValueArg<std::string> ifile_arg( "i", "ifile", "json file with model parameters", false, "","file name string"); TCLAP::ValueArg<double> tfinal_arg( "t", "tfinal", "time to simulate in ms", false, 100., "positive real number"); TCLAP::ValueArg<double> dt_arg( "d", "dt", "time step size in ms", false, 0.025, "positive real number"); TCLAP::SwitchArg all_to_all_arg( "a","alltoall","all to all network", cmd, false); cmd.add(ncells_arg); cmd.add(nsynapses_arg); cmd.add(ncompartments_arg); cmd.add(ifile_arg); cmd.add(dt_arg); cmd.add(tfinal_arg); cmd.parse(argc, argv); options.cells = ncells_arg.getValue(); options.synapses_per_cell = nsynapses_arg.getValue(); options.compartments_per_segment = ncompartments_arg.getValue(); options.ifname = ifile_arg.getValue(); options.tfinal = tfinal_arg.getValue(); options.dt = dt_arg.getValue(); options.all_to_all = all_to_all_arg.getValue(); } // catch any exceptions in command line handling catch(TCLAP::ArgException &e) { std::cerr << "error: parsing command line arguments:\n " << e.error() << " for arg " << e.argId() << "\n"; exit(1); } if(options.ifname == "") { options.check_and_normalize(); return options; } else { std::ifstream fid(options.ifname, std::ifstream::in); if(fid.is_open()) { // read json data in input file nlohmann::json fopts; fid >> fopts; try { options.cells = fopts["cells"]; options.synapses_per_cell = fopts["synapses"]; options.compartments_per_segment = fopts["compartments"]; options.dt = fopts["dt"]; options.tfinal = fopts["tfinal"]; options.all_to_all = fopts["all_to_all"]; } catch(std::domain_error e) { std::cerr << "error: unable to open parameters in " << options.ifname << " : " << e.what() << "\n"; exit(1); } catch(std::exception e) { std::cerr << "error: unable to open parameters in " << options.ifname << "\n"; exit(1); } options.check_and_normalize(); return options; } } return default_options; } std::ostream& operator<<(std::ostream& o, const cl_options& options) { o << "simultion options:\n"; o << " cells : " << options.cells << "\n"; o << " compartments/segment : " << options.compartments_per_segment << "\n"; o << " synapses/cell : " << options.synapses_per_cell << "\n"; o << " simulation time : " << options.tfinal << "\n"; o << " dt : " << options.dt << "\n"; o << " all to all network : " << (options.all_to_all ? "yes" : "no") << "\n"; o << " input file name : " << options.ifname << "\n"; return o; } } // namespace io } // namespace mc } // namespace nest <|endoftext|>
<commit_before>#ifndef _options_hpp_INCLUDED #define _options_hpp_INCLUDED /*------------------------------------------------------------------------*/ // The 'check' option has by default '0' in optimized compilation, but for // debugging and testing we want to set it to '1', by default. Setting // 'check' to '1' for instance triggers saving all the original clauses for // checking witnesses and also learned clauses if a solution is provided. #ifndef NDEBUG #define DEBUG 1 #else #define DEBUG 0 #endif /*------------------------------------------------------------------------*/ // Some of the 'OPTION' macros below should only be included if certain // compile time options are enabled. This has the effect, that for instance // if 'LOGGING' is defined, and thus logging code is included, then also the // 'log' option is defined. Otherwise the 'log' option is not included. #ifdef LOGGING #define LOGOPT OPTION #else #define LOGOPT(ARGS...) /**/ #endif /*------------------------------------------------------------------------*/ // In order to add new option, simply add a new line below. #define OPTIONS \ \ /* NAME TYPE, VAL, LO, HI, USAGE */ \ \ OPTION(arena, int, 3, 0, 3, "1=clause,2=var,3=queue") \ OPTION(binary, bool, 1, 0, 1, "use binary proof format") \ OPTION(check, bool,DEBUG, 0, 1, "save & check original CNF") \ OPTION(clim, int, -1, 0,1e9, "conflict limit (-1=none)") \ OPTION(dlim, int, -1, 0,1e9, "decision limit (-1=none)") \ OPTION(elim, bool, 1, 0, 1, "bounded variable elimination") \ OPTION(elimclslim, int, 1000, 0,1e9, "ignore clauses of this size") \ OPTION(eliminit, int, 1e3, 0,1e9, "initial conflict limit") \ OPTION(elimint, int, 1e4, 1,1e9, "initial conflict interval") \ OPTION(elimocclim, int, 100, 0,1e9, "one sided occurrence limit") \ OPTION(elimroundsinit, int, 5, 1,1e9, "initial number of rounds") \ OPTION(elimrounds, int, 2, 1,1e9, "usual number of rounds") \ OPTION(emabumplast, double, 1e-5, 0, 1, "alpha bump last percentage") \ OPTION(emagluefast, double, 3e-2, 0, 1, "alpha fast glue") \ OPTION(emaglueslow, double, 1e-5, 0, 1, "alpha slow glue") \ OPTION(emajump, double, 1e-5, 0, 1, "alpha jump level") \ OPTION(emasize, double, 1e-5, 0, 1, "alpha learned clause size") \ OPTION(decompose, bool, 1, 0, 1, "SCC decompose BIG and ELS") \ OPTION(decomposerounds, int, 1, 1,1e9, "number of decompose rounds") \ OPTION(hbr, bool, 1, 0, 1, "learn hyper binary clauses") \ OPTION(hbrsizelim, int, 1e9, 3, 1e9, "max size HBR base clause") \ OPTION(keepglue, int, 2, 1,1e9, "glue kept learned clauses") \ OPTION(keepsize, int, 3, 2,1e9, "size kept learned clauses") \ OPTION(leak, bool, 1, 0, 1, "leak solver memory") \ LOGOPT(log, bool, 0, 0, 1, "enable logging") \ LOGOPT(logsort, bool, 0, 0, 1, "sort logged clauses") \ OPTION(minimize, bool, 1, 0, 1, "minimize learned clauses") \ OPTION(minimizedepth, int, 1000, 0,1e9, "minimization depth") \ OPTION(posize, int, 4, 4,1e9, "size for saving position") \ OPTION(probe, bool, 1, 0, 1, "failed literal probing" ) \ OPTION(probeinit, int, 500, 0,1e9, "initial probing interval" ) \ OPTION(probeint, int, 1e4, 1,1e9, "probing interval increment" ) \ OPTION(probereleff, double, 0.02, 0, 1, "relative probing efficiency") \ OPTION(probereschedule, bool, 0, 0, 1, "reschedule probing") \ OPTION(probemaxeff, double, 1e7, 0, 1, "maximum probing efficiency") \ OPTION(probemineff, double, 1e5, 0, 1, "minimum probing efficiency") \ OPTION(prefetch, bool, 1, 0, 1, "prefetch watches") \ OPTION(profile, int, 2, 0, 4, "profiling level") \ OPTION(quiet, bool, 0, 0, 1, "disable all messages") \ OPTION(reduceglue, bool, 1, 0, 1, "reduce on glue first") \ OPTION(reduceinc, int, 300, 1,1e6, "reduce limit increment") \ OPTION(reduceinit, int, 2000, 0,1e6, "initial reduce limit") \ OPTION(restart, bool, 1, 0, 1, "enable restarting") \ OPTION(restartint, int, 4, 1,1e9, "restart base interval") \ OPTION(restartmargin, double, 1.1, 0, 10, "restart slow fast margin") \ OPTION(reusetrail, bool, 1, 0, 1, "enable trail reuse") \ OPTION(simplify, bool, 1, 0, 1, "enable simplifier") \ OPTION(strengthen, bool, 1, 0, 1, "strengthen during subsume") \ OPTION(subsume, bool, 1, 0, 1, "enable clause subsumption") \ OPTION(subsumebinlim, int, 1e4, 0,1e9, "watch list length limit") \ OPTION(subsumeclslim, int, 1e3, 0,1e9, "clause length limit") \ OPTION(subsumeinc, int, 1e4, 1,1e9, "interval in conflicts") \ OPTION(subsumeinit, int, 1e4, 0,1e9, "initial subsume limit") \ OPTION(subsumeocclim, int, 1e2, 0,1e9, "watch list length limit") \ OPTION(trailbump, bool, 1, 0, 1, "use trail + bumped") \ OPTION(trailbumplast, double, 40, 0,100, "trail bump last level limit") \ OPTION(trailbumprops, double, 200, 0,1e9, "trail bump propagation limit") \ OPTION(transred, bool, 1, 0, 1, "transitive reduction of BIG") \ OPTION(transredreleff,double, 0.05, 0, 1, "relative efficiency") \ OPTION(transredmaxeff,double, 1e7, 0, 1, "maximum efficiency") \ OPTION(transredmineff,double, 1e5, 0, 1, "minimum efficiency") \ OPTION(verbose, int, 0, 0, 2, "more verbose messages") \ OPTION(vivify, bool, 1, 0, 1, "vivification") \ OPTION(vivifyreleff, double, 0.03, 0, 1, "relative efficiency") \ OPTION(vivifyreschedule,bool, 0, 0, 1, "reschedule vivification") \ OPTION(vivifymaxeff, double, 1e7, 0, 1, "maximum efficiency") \ OPTION(vivifymineff, double, 1e5, 0, 1, "minimum efficiency") \ OPTION(witness, bool, 1, 0, 1, "print witness") \ /*------------------------------------------------------------------------*/ namespace CaDiCaL { class Internal; class Options { Internal * internal; bool set ( int &, const char *, const char *, const int, const int); bool set ( bool &, const char *, const char *, const bool, const bool); bool set (double &, const char *, const char *, const double, const double); const char * match (const char *, const char *); public: // Makes options directly accessible, e.g., for instance declares the // member 'bool Options.restart' here. This will give fast and type save // access to option values (internally). In principle one could make all // options simply 'double' though, but that requires double conversions // during accessing options at run-time and disregards the intended types, // e.g., one would need to allow fractional values for actual integer // or boolean options. Keeping the different types makes the output of // 'print' and 'usage' also more appealing (since correctly typed values // are printed). #define OPTION(N,T,V,L,H,D) \ T N; OPTIONS #undef OPTION Options (Internal *); // This sets the value of an option assuming a 'long' command line // argument form. The argument 'arg' thus should look like // // "--<NAME>=<VAL>", "--<NAME>" or "--no-<NAME>" // // where 'NAME' is one of the option names above. Returns 'true' if the // option was parsed and set correctly. For boolean values we strictly // only allow "true", "false", "0" and "1" as "<VAL>" string. For 'int' // type options we parse "<VAL>" with 'atoi' and force the resulting 'int' // value to the 'LO' and 'HI' range and similarly for 'double' type // options using 'atof'. If the string is not a valid 'int' for 'int' // options or a 'double' value for 'double' options, then the function // returns 'false'. // bool set (const char * arg); // Interface to options using in a certain sense non-type-safe 'double' // values even for 'int' and 'bool'. However, 'double' can hold a 'bool' // as well an 'int' value precisely, e.g., if the result of 'get' is cast // down again by the client. This would only fail for 64 byte 'long', // which we currently do not support as option type. // bool has (const char * name); double get (const char * name); bool set (const char * name, double); void print (); // print current values in command line form static void usage (); // print usage message for all options }; }; #endif <commit_msg>everybody got releff=0.03<commit_after>#ifndef _options_hpp_INCLUDED #define _options_hpp_INCLUDED /*------------------------------------------------------------------------*/ // The 'check' option has by default '0' in optimized compilation, but for // debugging and testing we want to set it to '1', by default. Setting // 'check' to '1' for instance triggers saving all the original clauses for // checking witnesses and also learned clauses if a solution is provided. #ifndef NDEBUG #define DEBUG 1 #else #define DEBUG 0 #endif /*------------------------------------------------------------------------*/ // Some of the 'OPTION' macros below should only be included if certain // compile time options are enabled. This has the effect, that for instance // if 'LOGGING' is defined, and thus logging code is included, then also the // 'log' option is defined. Otherwise the 'log' option is not included. #ifdef LOGGING #define LOGOPT OPTION #else #define LOGOPT(ARGS...) /**/ #endif /*------------------------------------------------------------------------*/ // In order to add new option, simply add a new line below. #define OPTIONS \ \ /* NAME TYPE, VAL, LO, HI, USAGE */ \ \ OPTION(arena, int, 3, 0, 3, "1=clause,2=var,3=queue") \ OPTION(binary, bool, 1, 0, 1, "use binary proof format") \ OPTION(check, bool,DEBUG, 0, 1, "save & check original CNF") \ OPTION(clim, int, -1, 0,1e9, "conflict limit (-1=none)") \ OPTION(dlim, int, -1, 0,1e9, "decision limit (-1=none)") \ OPTION(elim, bool, 1, 0, 1, "bounded variable elimination") \ OPTION(elimclslim, int, 1000, 0,1e9, "ignore clauses of this size") \ OPTION(eliminit, int, 1e3, 0,1e9, "initial conflict limit") \ OPTION(elimint, int, 1e4, 1,1e9, "initial conflict interval") \ OPTION(elimocclim, int, 100, 0,1e9, "one sided occurrence limit") \ OPTION(elimroundsinit, int, 5, 1,1e9, "initial number of rounds") \ OPTION(elimrounds, int, 2, 1,1e9, "usual number of rounds") \ OPTION(emabumplast, double, 1e-5, 0, 1, "alpha bump last percentage") \ OPTION(emagluefast, double, 3e-2, 0, 1, "alpha fast glue") \ OPTION(emaglueslow, double, 1e-5, 0, 1, "alpha slow glue") \ OPTION(emajump, double, 1e-5, 0, 1, "alpha jump level") \ OPTION(emasize, double, 1e-5, 0, 1, "alpha learned clause size") \ OPTION(decompose, bool, 1, 0, 1, "SCC decompose BIG and ELS") \ OPTION(decomposerounds, int, 1, 1,1e9, "number of decompose rounds") \ OPTION(hbr, bool, 1, 0, 1, "learn hyper binary clauses") \ OPTION(hbrsizelim, int, 1e9, 3, 1e9, "max size HBR base clause") \ OPTION(keepglue, int, 2, 1,1e9, "glue kept learned clauses") \ OPTION(keepsize, int, 3, 2,1e9, "size kept learned clauses") \ OPTION(leak, bool, 1, 0, 1, "leak solver memory") \ LOGOPT(log, bool, 0, 0, 1, "enable logging") \ LOGOPT(logsort, bool, 0, 0, 1, "sort logged clauses") \ OPTION(minimize, bool, 1, 0, 1, "minimize learned clauses") \ OPTION(minimizedepth, int, 1000, 0,1e9, "minimization depth") \ OPTION(posize, int, 4, 4,1e9, "size for saving position") \ OPTION(probe, bool, 1, 0, 1, "failed literal probing" ) \ OPTION(probeinit, int, 500, 0,1e9, "initial probing interval" ) \ OPTION(probeint, int, 1e4, 1,1e9, "probing interval increment" ) \ OPTION(probereleff, double, 0.03, 0, 1, "relative probing efficiency") \ OPTION(probereschedule, bool, 0, 0, 1, "reschedule probing") \ OPTION(probemaxeff, double, 1e7, 0, 1, "maximum probing efficiency") \ OPTION(probemineff, double, 1e5, 0, 1, "minimum probing efficiency") \ OPTION(prefetch, bool, 1, 0, 1, "prefetch watches") \ OPTION(profile, int, 2, 0, 4, "profiling level") \ OPTION(quiet, bool, 0, 0, 1, "disable all messages") \ OPTION(reduceglue, bool, 1, 0, 1, "reduce on glue first") \ OPTION(reduceinc, int, 300, 1,1e6, "reduce limit increment") \ OPTION(reduceinit, int, 2000, 0,1e6, "initial reduce limit") \ OPTION(restart, bool, 1, 0, 1, "enable restarting") \ OPTION(restartint, int, 4, 1,1e9, "restart base interval") \ OPTION(restartmargin, double, 1.1, 0, 10, "restart slow fast margin") \ OPTION(reusetrail, bool, 1, 0, 1, "enable trail reuse") \ OPTION(simplify, bool, 1, 0, 1, "enable simplifier") \ OPTION(strengthen, bool, 1, 0, 1, "strengthen during subsume") \ OPTION(subsume, bool, 1, 0, 1, "enable clause subsumption") \ OPTION(subsumebinlim, int, 1e4, 0,1e9, "watch list length limit") \ OPTION(subsumeclslim, int, 1e3, 0,1e9, "clause length limit") \ OPTION(subsumeinc, int, 1e4, 1,1e9, "interval in conflicts") \ OPTION(subsumeinit, int, 1e4, 0,1e9, "initial subsume limit") \ OPTION(subsumeocclim, int, 1e2, 0,1e9, "watch list length limit") \ OPTION(trailbump, bool, 1, 0, 1, "use trail + bumped") \ OPTION(trailbumplast, double, 40, 0,100, "trail bump last level limit") \ OPTION(trailbumprops, double, 200, 0,1e9, "trail bump propagation limit") \ OPTION(transred, bool, 1, 0, 1, "transitive reduction of BIG") \ OPTION(transredreleff,double, 0.03, 0, 1, "relative efficiency") \ OPTION(transredmaxeff,double, 1e7, 0, 1, "maximum efficiency") \ OPTION(transredmineff,double, 1e5, 0, 1, "minimum efficiency") \ OPTION(verbose, int, 0, 0, 2, "more verbose messages") \ OPTION(vivify, bool, 1, 0, 1, "vivification") \ OPTION(vivifyreleff, double, 0.03, 0, 1, "relative efficiency") \ OPTION(vivifyreschedule,bool, 0, 0, 1, "reschedule vivification") \ OPTION(vivifymaxeff, double, 1e7, 0, 1, "maximum efficiency") \ OPTION(vivifymineff, double, 1e5, 0, 1, "minimum efficiency") \ OPTION(witness, bool, 1, 0, 1, "print witness") \ /*------------------------------------------------------------------------*/ namespace CaDiCaL { class Internal; class Options { Internal * internal; bool set ( int &, const char *, const char *, const int, const int); bool set ( bool &, const char *, const char *, const bool, const bool); bool set (double &, const char *, const char *, const double, const double); const char * match (const char *, const char *); public: // Makes options directly accessible, e.g., for instance declares the // member 'bool Options.restart' here. This will give fast and type save // access to option values (internally). In principle one could make all // options simply 'double' though, but that requires double conversions // during accessing options at run-time and disregards the intended types, // e.g., one would need to allow fractional values for actual integer // or boolean options. Keeping the different types makes the output of // 'print' and 'usage' also more appealing (since correctly typed values // are printed). #define OPTION(N,T,V,L,H,D) \ T N; OPTIONS #undef OPTION Options (Internal *); // This sets the value of an option assuming a 'long' command line // argument form. The argument 'arg' thus should look like // // "--<NAME>=<VAL>", "--<NAME>" or "--no-<NAME>" // // where 'NAME' is one of the option names above. Returns 'true' if the // option was parsed and set correctly. For boolean values we strictly // only allow "true", "false", "0" and "1" as "<VAL>" string. For 'int' // type options we parse "<VAL>" with 'atoi' and force the resulting 'int' // value to the 'LO' and 'HI' range and similarly for 'double' type // options using 'atof'. If the string is not a valid 'int' for 'int' // options or a 'double' value for 'double' options, then the function // returns 'false'. // bool set (const char * arg); // Interface to options using in a certain sense non-type-safe 'double' // values even for 'int' and 'bool'. However, 'double' can hold a 'bool' // as well an 'int' value precisely, e.g., if the result of 'get' is cast // down again by the client. This would only fail for 64 byte 'long', // which we currently do not support as option type. // bool has (const char * name); double get (const char * name); bool set (const char * name, double); void print (); // print current values in command line form static void usage (); // print usage message for all options }; }; #endif <|endoftext|>
<commit_before>/* * */ #include "unix/constant.h" #include "unix/log.hpp" #include "menu.hpp" // current track number // mpc -f %position% current namespace led_d { constexpr auto TRACK_ROTOR = ROTOR_1; // select track constexpr auto VOLUME_ROTOR = ROTOR_2; // tune volume constexpr auto MENU_ROTOR = TRACK_ROTOR; // select menu constexpr auto VALUE_ROTOR = VOLUME_ROTOR; // select value menu_t::menu_t () : m_playlist_update (false) { } void menu_t::track_add (const std::string &track) { if (m_playlist_update == false) { m_playlist_update = true; m_playlist.clear (); } if (track.empty () == false) { m_playlist.push_back (track); } else { m_playlist_update = false; } } void menu_t::track_clear () { m_playlist.clear (); } void menu_t::rotor (uint8_t rotor_id, uint8_t action) { if (!m_id) { if (rotor_id == VOLUME_ROTOR) select (id_t::VOLUME); else select (id_t::TRACK); // switch (action) { case ROTOR_CLOCKWISE: value (true); break; case ROTOR_COUNTER_CLOCKWISE: value (false); break; case ROTOR_PUSH: // volume & track directly accessible, // user wants something different select (id_t::BRIGHTNESS); break; default: log_t::buffer_t buf; buf << "menu: Unknown rotor action has arrived in idle mode \"" << static_cast<int>(action) << "\""; log_t::error (buf); break; } return; } switch (action) { case ROTOR_CLOCKWISE: case ROTOR_COUNTER_CLOCKWISE: { bool inc = (action == ROTOR_CLOCKWISE) ? true : false; if (rotor_id == MENU_ROTOR) select (inc); else value (inc); } break; case ROTOR_PUSH: if (rotor_id == MENU_ROTOR) select (); else value (); break; default: log_t::buffer_t buf; buf << "menu: Unknown rotor action has arrived in non idle mode \"" << static_cast<int>(action) << "\""; log_t::error (buf); break; } } } // led_d <commit_msg>pi: Polish<commit_after>/* * */ #include "unix/constant.h" #include "unix/log.hpp" #include "menu.hpp" // current track number // mpc -f %position% current namespace led_d { constexpr auto TRACK_ROTOR = ROTOR_1; // select track constexpr auto VOLUME_ROTOR = ROTOR_2; // tune volume constexpr auto MENU_ROTOR = VOLUME_ROTOR; // select menu constexpr auto VALUE_ROTOR = TRACK_ROTOR; // select value menu_t::menu_t () : m_playlist_update (false) { } void menu_t::track_add (const std::string &track) { if (m_playlist_update == false) { m_playlist_update = true; m_playlist.clear (); } if (track.empty () == false) { m_playlist.push_back (track); } else { m_playlist_update = false; } } void menu_t::track_clear () { m_playlist.clear (); } void menu_t::rotor (uint8_t rotor_id, uint8_t action) { if (!m_id) { if (rotor_id == VOLUME_ROTOR) select (id_t::VOLUME); else select (id_t::TRACK); // switch (action) { case ROTOR_CLOCKWISE: value (true); break; case ROTOR_COUNTER_CLOCKWISE: value (false); break; case ROTOR_PUSH: // volume & track directly accessible, // user wants something different select (id_t::BRIGHTNESS); break; default: log_t::buffer_t buf; buf << "menu: Unknown rotor action has arrived in idle mode \"" << static_cast<int>(action) << "\""; log_t::error (buf); break; } return; } switch (action) { case ROTOR_CLOCKWISE: case ROTOR_COUNTER_CLOCKWISE: { bool inc = (action == ROTOR_CLOCKWISE) ? true : false; if (rotor_id == MENU_ROTOR) select (inc); else value (inc); } break; case ROTOR_PUSH: if (rotor_id == MENU_ROTOR) select (); else value (); break; default: log_t::buffer_t buf; buf << "menu: Unknown rotor action has arrived in non idle mode \"" << static_cast<int>(action) << "\""; log_t::error (buf); break; } } } // led_d <|endoftext|>
<commit_before>/*************************************************************************** * Copyright (C) 2006 by FThauer FHammer * * f.thauer@web.de * * * * 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., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #include <boost/asio.hpp> #include <iostream> #include <cstdlib> #include <ctime> #include <qapplication.h> #include <QtGui> #include <QtCore> #ifdef __APPLE__ #include <QMacStyle> #endif #include <curl/curl.h> #include "session.h" #include "startwindowimpl.h" #include "configfile.h" #include "startsplash.h" #include "game_defs.h" #include <net/socket_startup.h> #include <third_party/qtsingleapplication/qtsingleapplication.h> #ifdef _MSC_VER #ifdef _DEBUG #define _CRTDBG_MAP_ALLOC #include <crtdbg.h> #define ENABLE_LEAK_CHECK() \ { \ int tmpFlag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG); \ tmpFlag |= _CRTDBG_LEAK_CHECK_DF; \ _CrtSetDbgFlag(tmpFlag); \ } #endif #endif #ifndef ENABLE_LEAK_CHECK #define ENABLE_LEAK_CHECK() #endif //Uncomment this for RELEASE on Linux/Unix/BSD (static Qt only) //#include <QtPlugin> //Q_IMPORT_PLUGIN(qjpeg) //Q_IMPORT_PLUGIN(qgif) #ifdef _WIN32 // Always use static Qt on Windows. #include <QtPlugin> Q_IMPORT_PLUGIN(qjpeg) Q_IMPORT_PLUGIN(qgif) #endif using namespace std; class startWindowImpl; class Game; int main( int argc, char **argv ) { //ENABLE_LEAK_CHECK(); //_CrtSetBreakAlloc(49937); socket_startup(); curl_global_init(CURL_GLOBAL_NOTHING); /////// can be removed for non-qt-guis //////////// QtSingleApplication a( argc, argv ); if (a.sendMessage("Wake up!")) { return 0; } #ifdef __APPLE__ // The following needs to be done directly after the application is created. QDir dir(QApplication::applicationDirPath()); dir.cdUp(); dir.cd("plugins"); QApplication::setLibraryPaths(QStringList(dir.absolutePath())); #endif //create defaultconfig ConfigFile *myConfig = new ConfigFile(argv[0], false); // set PlastiqueStyle even for mac-version to prevent artefacts on styled widgets // a.setStyle(new QPlastiqueStyle); QString myAppDataPath = QString::fromUtf8(myConfig->readConfigString("AppDataDir").c_str()); //set QApplication default font QFontDatabase::addApplicationFont (myAppDataPath +"fonts/n019003l.pfb"); QFontDatabase::addApplicationFont (myAppDataPath +"fonts/VeraBd.ttf"); QFontDatabase::addApplicationFont (myAppDataPath +"fonts/c059013l.pfb"); #ifdef _WIN32 QString font1String("font-family: \"Arial\";"); a.setStyleSheet("QApplication, QWidget, QDialog { " + font1String + " font-size: 12px; }"); #else #ifdef __APPLE__ QString font1String("font-family: \"Lucida Grande\";"); a.setStyleSheet("QWidget, QDialog { " + font1String + " font-size: 8px; }"); #else QString font1String("font-family: \"Nimbus Sans L\";"); a.setStyleSheet("QApplication, QWidget, QDialog { " + font1String + " font-size: 18px; }"); #endif #endif a.setStyleSheet("QDialogButtonBox, QMessageBox { dialogbuttonbox-buttons-have-icons: 1; dialog-ok-icon: url(:/gfx/dialog_ok_apply.png); dialog-cancel-icon: url(:/gfx/dialog_close.png); dialog-close-icon: url(:/gfx/dialog_close.png); dialog-yes-icon: url(:/gfx/dialog_ok_apply.png); dialog-no-icon: url(:/gfx/dialog_close.png) }"); QPixmap *pixmap = new QPixmap(myAppDataPath + "gfx/gui/misc/welcomepokerth.png"); StartSplash splash(*pixmap); if(!myConfig->readConfigInt("DisableSplashScreenOnStartup")) { splash.show(); splash.showMessage(QString("Version %1").arg(POKERTH_BETA_RELEASE_STRING), 0x0042, QColor(153,213,0)); } //Set translations QTranslator qtTranslator; qtTranslator.load(QString(myAppDataPath +"translations/qt_") + QString::fromStdString(myConfig->readConfigString("Language"))); a.installTranslator(&qtTranslator); QTranslator translator; translator.load(QString(myAppDataPath +"translations/pokerth_") + QString::fromStdString(myConfig->readConfigString("Language"))); a.installTranslator(&translator); qRegisterMetaType<unsigned>("unsigned"); qRegisterMetaType<boost::shared_ptr<Game> >("boost::shared_ptr<Game>"); qRegisterMetaType<ServerStats>("ServerStats"); qRegisterMetaType<DenyGameInvitationReason>("DenyGameInvitationReason"); /////////////////////////////////////////////////// startWindowImpl mainWin(myConfig); a.setActivationWindow(&mainWin, true); int retVal = a.exec(); curl_global_cleanup(); socket_cleanup(); return retVal; } <commit_msg>mac font fix<commit_after>/*************************************************************************** * Copyright (C) 2006 by FThauer FHammer * * f.thauer@web.de * * * * 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., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #include <boost/asio.hpp> #include <iostream> #include <cstdlib> #include <ctime> #include <qapplication.h> #include <QtGui> #include <QtCore> #ifdef __APPLE__ #include <QMacStyle> #endif #include <curl/curl.h> #include "session.h" #include "startwindowimpl.h" #include "configfile.h" #include "startsplash.h" #include "game_defs.h" #include <net/socket_startup.h> #include <third_party/qtsingleapplication/qtsingleapplication.h> #ifdef _MSC_VER #ifdef _DEBUG #define _CRTDBG_MAP_ALLOC #include <crtdbg.h> #define ENABLE_LEAK_CHECK() \ { \ int tmpFlag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG); \ tmpFlag |= _CRTDBG_LEAK_CHECK_DF; \ _CrtSetDbgFlag(tmpFlag); \ } #endif #endif #ifndef ENABLE_LEAK_CHECK #define ENABLE_LEAK_CHECK() #endif //Uncomment this for RELEASE on Linux/Unix/BSD (static Qt only) //#include <QtPlugin> //Q_IMPORT_PLUGIN(qjpeg) //Q_IMPORT_PLUGIN(qgif) #ifdef _WIN32 // Always use static Qt on Windows. #include <QtPlugin> Q_IMPORT_PLUGIN(qjpeg) Q_IMPORT_PLUGIN(qgif) #endif using namespace std; class startWindowImpl; class Game; int main( int argc, char **argv ) { //ENABLE_LEAK_CHECK(); //_CrtSetBreakAlloc(49937); socket_startup(); curl_global_init(CURL_GLOBAL_NOTHING); /////// can be removed for non-qt-guis //////////// QtSingleApplication a( argc, argv ); if (a.sendMessage("Wake up!")) { return 0; } #ifdef __APPLE__ // The following needs to be done directly after the application is created. QDir dir(QApplication::applicationDirPath()); dir.cdUp(); dir.cd("plugins"); QApplication::setLibraryPaths(QStringList(dir.absolutePath())); #endif //create defaultconfig ConfigFile *myConfig = new ConfigFile(argv[0], false); // set PlastiqueStyle even for mac-version to prevent artefacts on styled widgets a.setStyle(new QPlastiqueStyle); QString myAppDataPath = QString::fromUtf8(myConfig->readConfigString("AppDataDir").c_str()); //set QApplication default font QFontDatabase::addApplicationFont (myAppDataPath +"fonts/n019003l.pfb"); QFontDatabase::addApplicationFont (myAppDataPath +"fonts/VeraBd.ttf"); QFontDatabase::addApplicationFont (myAppDataPath +"fonts/c059013l.pfb"); #ifdef _WIN32 QString font1String("QApplication, QWidget, QDialog { font-family: \"Arial\"; font-size: 12px; }"); #else #ifdef __APPLE__ // QString font1String("font-family: \"Lucida Grande\";"); QString font1String("QApplication, QWidget, QDialog { font-family: \"Nimbus Sans L\"; font-size: 12px; }"); #else QString font1String("QApplication, QWidget, QDialog { font-family: \"Nimbus Sans L\"; font-size: 12px; }"); #endif #endif a.setStyleSheet(font1String + " QDialogButtonBox, QMessageBox { dialogbuttonbox-buttons-have-icons: 1; dialog-ok-icon: url(:/gfx/dialog_ok_apply.png); dialog-cancel-icon: url(:/gfx/dialog_close.png); dialog-close-icon: url(:/gfx/dialog_close.png); dialog-yes-icon: url(:/gfx/dialog_ok_apply.png); dialog-no-icon: url(:/gfx/dialog_close.png) }"); QPixmap *pixmap = new QPixmap(myAppDataPath + "gfx/gui/misc/welcomepokerth.png"); StartSplash splash(*pixmap); if(!myConfig->readConfigInt("DisableSplashScreenOnStartup")) { splash.show(); splash.showMessage(QString("Version %1").arg(POKERTH_BETA_RELEASE_STRING), 0x0042, QColor(153,213,0)); } //Set translations QTranslator qtTranslator; qtTranslator.load(QString(myAppDataPath +"translations/qt_") + QString::fromStdString(myConfig->readConfigString("Language"))); a.installTranslator(&qtTranslator); QTranslator translator; translator.load(QString(myAppDataPath +"translations/pokerth_") + QString::fromStdString(myConfig->readConfigString("Language"))); a.installTranslator(&translator); qRegisterMetaType<unsigned>("unsigned"); qRegisterMetaType<boost::shared_ptr<Game> >("boost::shared_ptr<Game>"); qRegisterMetaType<ServerStats>("ServerStats"); qRegisterMetaType<DenyGameInvitationReason>("DenyGameInvitationReason"); /////////////////////////////////////////////////// startWindowImpl mainWin(myConfig); a.setActivationWindow(&mainWin, true); int retVal = a.exec(); curl_global_cleanup(); socket_cleanup(); return retVal; } <|endoftext|>
<commit_before>#include "producer.h" #include <nan.h> #include <v8.h> #include <errno.h> #include <iostream> using namespace v8; using namespace std; Producer::Producer(Local<Object> &options) : Common(RD_KAFKA_PRODUCER, options) { } Producer::~Producer() { } Persistent<Function> Producer::constructor; void Producer::Init() { NanScope(); // Prepare constructor template Local<FunctionTemplate> tpl = NanNew<FunctionTemplate>(New); tpl->SetClassName(NanNew("Producer")); tpl->InstanceTemplate()->SetInternalFieldCount(1); NODE_SET_PROTOTYPE_METHOD(tpl, "send", WRAPPED_METHOD_NAME(Send)); NODE_SET_PROTOTYPE_METHOD(tpl, "get_metadata", WRAPPED_METHOD_NAME(GetMetadata)); NanAssignPersistent(constructor, tpl->GetFunction()); } Local<Object> Producer::NewInstance(Local<Value> arg) { NanEscapableScope(); const unsigned argc = 1; Local<Value> argv[argc] = { arg }; Local<Function> cons = NanNew<Function>(constructor); Local<Object> instance = cons->NewInstance(argc, argv); return NanEscapeScope(instance); } NAN_METHOD(Producer::New) { NanScope(); if (!args.IsConstructCall()) { return NanThrowError("non-constructor invocation not supported"); } Local<Object> options(NanNew<Object>()); if (args.Length() == 1 && args[0] != NanUndefined()) { options = args[0].As<Object>(); } Producer* obj = new Producer(options); obj->Wrap(args.This()); string error; if (obj->producer_init(&error)) { NanThrowError(error.c_str()); NanReturnUndefined(); } NanReturnValue(args.This()); } int Producer::producer_init(string *error_str) { return common_init(error_str); } WRAPPED_METHOD(Producer, Send) { NanScope(); if (!kafka_client_) { NanThrowError("you must setup the client before using send"); NanReturnUndefined(); } if (args.Length() != 3 || !( args[0]->IsString() && args[1]->IsNumber() && args[2]->IsArray()) ) { NanThrowError("you must supply a topic name, partition, and array of strings"); NanReturnUndefined(); } String::AsciiValue topic_name(args[0]); rd_kafka_topic_t *topic = get_topic(*topic_name); if (!topic) { string error; topic = setup_topic(*topic_name, &error); if (!topic) { NanThrowError(error.c_str()); NanReturnUndefined(); } } int32_t partition = args[1].As<Number>()->Int32Value(); Local<Array> msg_array(args[2].As<Array>()); uint32_t message_cnt = msg_array->Length(); unique_ptr<rd_kafka_message_t[]> holder(new rd_kafka_message_t[message_cnt]()); rd_kafka_message_t *messages = holder.get(); for (uint32_t i = 0; i < message_cnt; ++i) { rd_kafka_message_t *msg = &messages[i]; const Local<String>& str(msg_array->Get(i).As<String>()); int length = str->Utf8Length(); msg->len = length; // malloc here to match the F_FREE flag below msg->payload = malloc(length); // WriteUtf8 in v8/src/api.cc str->WriteUtf8((char*)msg->payload, length, nullptr, 0); } uint32_t sent = rd_kafka_produce_batch( topic, partition, RD_KAFKA_MSG_F_FREE, messages, message_cnt); if (sent != message_cnt) { // Since rdkafka didn't take ownership of these, // we need to free them ourselves. for (uint32_t i = 0; i < (message_cnt - sent); ++i) { rd_kafka_message_t *msg = &messages[i + sent]; free(msg->payload); } } NanReturnValue(NanNew<Number>(sent)); } WRAPPED_METHOD(Producer, GetMetadata) { NanScope(); get_metadata(args); NanReturnUndefined(); } <commit_msg>improve error checking for produce side failures<commit_after>#include "producer.h" #include <nan.h> #include <v8.h> #include <errno.h> #include <iostream> using namespace v8; using namespace std; Producer::Producer(Local<Object> &options) : Common(RD_KAFKA_PRODUCER, options) { } Producer::~Producer() { } Persistent<Function> Producer::constructor; void Producer::Init() { NanScope(); // Prepare constructor template Local<FunctionTemplate> tpl = NanNew<FunctionTemplate>(New); tpl->SetClassName(NanNew("Producer")); tpl->InstanceTemplate()->SetInternalFieldCount(1); NODE_SET_PROTOTYPE_METHOD(tpl, "send", WRAPPED_METHOD_NAME(Send)); NODE_SET_PROTOTYPE_METHOD(tpl, "get_metadata", WRAPPED_METHOD_NAME(GetMetadata)); NanAssignPersistent(constructor, tpl->GetFunction()); } Local<Object> Producer::NewInstance(Local<Value> arg) { NanEscapableScope(); const unsigned argc = 1; Local<Value> argv[argc] = { arg }; Local<Function> cons = NanNew<Function>(constructor); Local<Object> instance = cons->NewInstance(argc, argv); return NanEscapeScope(instance); } NAN_METHOD(Producer::New) { NanScope(); if (!args.IsConstructCall()) { return NanThrowError("non-constructor invocation not supported"); } Local<Object> options(NanNew<Object>()); if (args.Length() == 1 && args[0] != NanUndefined()) { options = args[0].As<Object>(); } Producer* obj = new Producer(options); obj->Wrap(args.This()); string error; if (obj->producer_init(&error)) { NanThrowError(error.c_str()); NanReturnUndefined(); } NanReturnValue(args.This()); } int Producer::producer_init(string *error_str) { return common_init(error_str); } WRAPPED_METHOD(Producer, Send) { NanScope(); if (!kafka_client_) { NanThrowError("you must setup the client before using send"); NanReturnUndefined(); } if (args.Length() != 3 || !( args[0]->IsString() && args[1]->IsNumber() && args[2]->IsArray()) ) { NanThrowError("you must supply a topic name, partition, and array of strings"); NanReturnUndefined(); } String::AsciiValue topic_name(args[0]); rd_kafka_topic_t *topic = get_topic(*topic_name); if (!topic) { string error; topic = setup_topic(*topic_name, &error); if (!topic) { NanThrowError(error.c_str()); NanReturnUndefined(); } } int32_t partition = args[1].As<Number>()->Int32Value(); Local<Array> msg_array(args[2].As<Array>()); uint32_t message_cnt = msg_array->Length(); unique_ptr<rd_kafka_message_t[]> holder(new rd_kafka_message_t[message_cnt]()); rd_kafka_message_t *messages = holder.get(); for (uint32_t i = 0; i < message_cnt; ++i) { rd_kafka_message_t *msg = &messages[i]; const Local<String>& str(msg_array->Get(i).As<String>()); int length = str->Utf8Length(); msg->len = length; // malloc here to match the F_FREE flag below msg->payload = malloc(length); // WriteUtf8 in v8/src/api.cc str->WriteUtf8((char*)msg->payload, length, nullptr, 0); // ensure errors aren't missed by checking that // prodce_batch clears the error for good messages msg->err = RD_KAFKA_RESP_ERR_UNKNOWN; } uint32_t sent = rd_kafka_produce_batch( topic, partition, RD_KAFKA_MSG_F_FREE, messages, message_cnt); if (sent != message_cnt) { // Since rdkafka didn't take ownership of these, // we need to free them ourselves. for (uint32_t i = 0; i < message_cnt; ++i) { rd_kafka_message_t *msg = &messages[i]; if (msg->err != RD_KAFKA_RESP_ERR_NO_ERROR) { free(msg->payload); } } } NanReturnValue(NanNew<Number>(sent)); } WRAPPED_METHOD(Producer, GetMetadata) { NanScope(); get_metadata(args); NanReturnUndefined(); } <|endoftext|>
<commit_before>// $Id$ // vim::tabstop=2 /*********************************************************************** Moses - factored phrase-based language decoder Copyright (C) 2006 University of Edinburgh This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA ***********************************************************************/ #include <sstream> #include "memory.h" #include "Word.h" #include "TypeDef.h" #include "FactorTypeSet.h" #include "FactorCollection.h" #include "StaticData.h" // needed to determine the FactorDelimiter #include "util/exception.hh" #include "util/tokenize_piece.hh" using namespace std; namespace Moses { // static int Word::Compare(const Word &targetWord, const Word &sourceWord) { if (targetWord.IsNonTerminal() != sourceWord.IsNonTerminal()) { return targetWord.IsNonTerminal() ? -1 : 1; } for (size_t factorType = 0 ; factorType < MAX_NUM_FACTORS ; factorType++) { const Factor *targetFactor = targetWord[factorType] ,*sourceFactor = sourceWord[factorType]; if (targetFactor == NULL || sourceFactor == NULL) continue; if (targetFactor == sourceFactor) continue; return (targetFactor<sourceFactor) ? -1 : +1; } return 0; } void Word::Merge(const Word &sourceWord) { for (unsigned int currFactor = 0 ; currFactor < MAX_NUM_FACTORS ; currFactor++) { const Factor *sourcefactor = sourceWord.m_factorArray[currFactor] ,*targetFactor = this ->m_factorArray[currFactor]; if (targetFactor == NULL && sourcefactor != NULL) { m_factorArray[currFactor] = sourcefactor; } } } std::string Word::GetString(const vector<FactorType> factorType,bool endWithBlank) const { stringstream strme; const std::string& factorDelimiter = StaticData::Instance().GetFactorDelimiter(); bool firstPass = true; for (unsigned int i = 0 ; i < factorType.size() ; i++) { UTIL_THROW_IF2(factorType[i] >= MAX_NUM_FACTORS, "Trying to reference factor " << factorType[i] << ". Max factor is " << MAX_NUM_FACTORS); const Factor *factor = m_factorArray[factorType[i]]; if (factor != NULL) { if (firstPass) { firstPass = false; } else { strme << factorDelimiter; } strme << factor->GetString(); } } if(endWithBlank) strme << " "; return strme.str(); } StringPiece Word::GetString(FactorType factorType) const { return m_factorArray[factorType]->GetString(); } class StrayFactorException : public util::Exception {}; void Word:: CreateFromString(FactorDirection direction , const std::vector<FactorType> &factorOrder , const StringPiece &str , bool isNonTerminal , bool strict) { FactorCollection &factorCollection = FactorCollection::Instance(); vector<StringPiece> bits(MAX_NUM_FACTORS); util::TokenIter<util::MultiCharacter> fit(str, StaticData::Instance().GetFactorDelimiter()); size_t i = 0; for (; i < MAX_NUM_FACTORS && fit; ++i,++fit) bits[i] = *fit; if (i == MAX_NUM_FACTORS) UTIL_THROW_IF(fit, StrayFactorException, "The hard limit for factors is " << MAX_NUM_FACTORS << ". The word " << str << " contains factor delimiter " << StaticData::Instance().GetFactorDelimiter() << " too many times."); if (strict) UTIL_THROW_IF(fit, StrayFactorException, "You have configured " << factorOrder.size() << " factors but the word " << str << " contains factor delimiter " << StaticData::Instance().GetFactorDelimiter() << " too many times."); UTIL_THROW_IF(i < factorOrder.size(),util::Exception, "Too few factors in string '" << str << "'."); for (size_t k = 0; k < factorOrder.size(); ++k) { UTIL_THROW_IF(factorOrder[k] >= MAX_NUM_FACTORS, util::Exception, "Factor order out of bounds."); m_factorArray[factorOrder[k]] = factorCollection.AddFactor(bits[k], isNonTerminal); } // assume term/non-term same for all factors m_isNonTerminal = isNonTerminal; } void Word::CreateUnknownWord(const Word &sourceWord) { FactorCollection &factorCollection = FactorCollection::Instance(); m_isNonTerminal = sourceWord.IsNonTerminal(); for (unsigned int currFactor = 0 ; currFactor < MAX_NUM_FACTORS ; currFactor++) { FactorType factorType = static_cast<FactorType>(currFactor); const Factor *sourceFactor = sourceWord[currFactor]; if (sourceFactor == NULL) SetFactor(factorType, factorCollection.AddFactor(Output, factorType, UNKNOWN_FACTOR, m_isNonTerminal)); else SetFactor(factorType, factorCollection.AddFactor(Output, factorType, sourceFactor->GetString(), m_isNonTerminal)); } m_isOOV = true; } void Word::OnlyTheseFactors(const FactorMask &factors) { for (unsigned int currFactor = 0 ; currFactor < MAX_NUM_FACTORS ; currFactor++) { if (!factors[currFactor]) { SetFactor(currFactor, NULL); } } } bool Word::IsEpsilon() const { const Factor *factor = m_factorArray[0]; int compare = factor->GetString().compare(EPSILON); return compare == 0; } TO_STRING_BODY(Word); // friend ostream& operator<<(ostream& out, const Word& word) { stringstream strme; const std::string& factorDelimiter = StaticData::Instance().GetFactorDelimiter(); bool firstPass = true; for (unsigned int currFactor = 0 ; currFactor < MAX_NUM_FACTORS ; currFactor++) { FactorType factorType = static_cast<FactorType>(currFactor); const Factor *factor = word.GetFactor(factorType); if (factor != NULL) { if (firstPass) { firstPass = false; } else { strme << factorDelimiter; } strme << *factor; } } out << strme.str() << " "; return out; } } <commit_msg>Word.CreateFromString() now bypasses factor splitting if the factor delimiter is th empty string (specify as: none).<commit_after>// $Id$ // vim::tabstop=2 /*********************************************************************** Moses - factored phrase-based language decoder Copyright (C) 2006 University of Edinburgh This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA ***********************************************************************/ #include <sstream> #include "memory.h" #include "Word.h" #include "TypeDef.h" #include "FactorTypeSet.h" #include "FactorCollection.h" #include "StaticData.h" // needed to determine the FactorDelimiter #include "util/exception.hh" #include "util/tokenize_piece.hh" using namespace std; namespace Moses { // static int Word::Compare(const Word &targetWord, const Word &sourceWord) { if (targetWord.IsNonTerminal() != sourceWord.IsNonTerminal()) { return targetWord.IsNonTerminal() ? -1 : 1; } for (size_t factorType = 0 ; factorType < MAX_NUM_FACTORS ; factorType++) { const Factor *targetFactor = targetWord[factorType] ,*sourceFactor = sourceWord[factorType]; if (targetFactor == NULL || sourceFactor == NULL) continue; if (targetFactor == sourceFactor) continue; return (targetFactor<sourceFactor) ? -1 : +1; } return 0; } void Word::Merge(const Word &sourceWord) { for (unsigned int currFactor = 0 ; currFactor < MAX_NUM_FACTORS ; currFactor++) { const Factor *sourcefactor = sourceWord.m_factorArray[currFactor] ,*targetFactor = this ->m_factorArray[currFactor]; if (targetFactor == NULL && sourcefactor != NULL) { m_factorArray[currFactor] = sourcefactor; } } } std::string Word::GetString(const vector<FactorType> factorType,bool endWithBlank) const { stringstream strme; const std::string& factorDelimiter = StaticData::Instance().GetFactorDelimiter(); bool firstPass = true; for (unsigned int i = 0 ; i < factorType.size() ; i++) { UTIL_THROW_IF2(factorType[i] >= MAX_NUM_FACTORS, "Trying to reference factor " << factorType[i] << ". Max factor is " << MAX_NUM_FACTORS); const Factor *factor = m_factorArray[factorType[i]]; if (factor != NULL) { if (firstPass) { firstPass = false; } else { strme << factorDelimiter; } strme << factor->GetString(); } } if(endWithBlank) strme << " "; return strme.str(); } StringPiece Word::GetString(FactorType factorType) const { return m_factorArray[factorType]->GetString(); } class StrayFactorException : public util::Exception {}; void Word:: CreateFromString(FactorDirection direction , const std::vector<FactorType> &factorOrder , const StringPiece &str , bool isNonTerminal , bool strict) { FactorCollection &factorCollection = FactorCollection::Instance(); vector<StringPiece> bits(MAX_NUM_FACTORS); string factorDelimiter = StaticData::Instance().GetFactorDelimiter(); if (factorDelimiter.size()) { util::TokenIter<util::MultiCharacter> fit(str, factorDelimiter); size_t i = 0; for (; i < MAX_NUM_FACTORS && fit; ++i,++fit) bits[i] = *fit; if (i == MAX_NUM_FACTORS) UTIL_THROW_IF(fit, StrayFactorException, "The hard limit for factors is " << MAX_NUM_FACTORS << ". The word " << str << " contains factor delimiter " << StaticData::Instance().GetFactorDelimiter() << " too many times."); if (strict) UTIL_THROW_IF(fit, StrayFactorException, "You have configured " << factorOrder.size() << " factors but the word " << str << " contains factor delimiter " << StaticData::Instance().GetFactorDelimiter() << " too many times."); UTIL_THROW_IF(i < factorOrder.size(),util::Exception, "Too few factors in string '" << str << "'."); } else { bits[0] = str; } for (size_t k = 0; k < factorOrder.size(); ++k) { UTIL_THROW_IF(factorOrder[k] >= MAX_NUM_FACTORS, util::Exception, "Factor order out of bounds."); m_factorArray[factorOrder[k]] = factorCollection.AddFactor(bits[k], isNonTerminal); } // assume term/non-term same for all factors m_isNonTerminal = isNonTerminal; } void Word::CreateUnknownWord(const Word &sourceWord) { FactorCollection &factorCollection = FactorCollection::Instance(); m_isNonTerminal = sourceWord.IsNonTerminal(); for (unsigned int currFactor = 0 ; currFactor < MAX_NUM_FACTORS ; currFactor++) { FactorType factorType = static_cast<FactorType>(currFactor); const Factor *sourceFactor = sourceWord[currFactor]; if (sourceFactor == NULL) SetFactor(factorType, factorCollection.AddFactor(Output, factorType, UNKNOWN_FACTOR, m_isNonTerminal)); else SetFactor(factorType, factorCollection.AddFactor(Output, factorType, sourceFactor->GetString(), m_isNonTerminal)); } m_isOOV = true; } void Word::OnlyTheseFactors(const FactorMask &factors) { for (unsigned int currFactor = 0 ; currFactor < MAX_NUM_FACTORS ; currFactor++) { if (!factors[currFactor]) { SetFactor(currFactor, NULL); } } } bool Word::IsEpsilon() const { const Factor *factor = m_factorArray[0]; int compare = factor->GetString().compare(EPSILON); return compare == 0; } TO_STRING_BODY(Word); // friend ostream& operator<<(ostream& out, const Word& word) { stringstream strme; const std::string& factorDelimiter = StaticData::Instance().GetFactorDelimiter(); bool firstPass = true; for (unsigned int currFactor = 0 ; currFactor < MAX_NUM_FACTORS ; currFactor++) { FactorType factorType = static_cast<FactorType>(currFactor); const Factor *factor = word.GetFactor(factorType); if (factor != NULL) { if (firstPass) { firstPass = false; } else { strme << factorDelimiter; } strme << *factor; } } out << strme.str() << " "; return out; } } <|endoftext|>
<commit_before>/** * oakmodelview - version 0.1.0 * -------------------------------------------------------- * Copyright (C) 2017, by Mikkel Nøhr Løvgreen (mikkel@oakmodelview.com) * Report bugs and download new versions at http://oakmodelview.com/ * * This library is distributed under the MIT License. * See accompanying file LICENSE in the root folder. */ #ifdef XML_BACKEND #include "XMLListRef.h" namespace Oak { namespace XML { // ============================================================================= // (public) ListRef::ListRef(const std::string &elementTagName) : m_listBaseRef(Ref::MakeUPtr()), m_tagName(elementTagName), m_subRef(ChildRefGroup::MakeUPtr()) { } // ============================================================================= // (public) ListRef::ListRef(RefUPtr listBaseRef, const std::string &elementTagName, ChildRefGroupUPtr elementSubRef) : m_listBaseRef(std::move(listBaseRef)), m_tagName(elementTagName), m_subRef(std::move(elementSubRef)) { assert(!m_tagName.empty()); } // ============================================================================= // (public) ListRef::ListRef(const ListRef &copy) { *this = copy; } // ============================================================================= // (public) ListRef::ListRef(ListRef &&move) { *this = std::move(move); } // ============================================================================= // (public) ListRef::~ListRef() { } // ============================================================================= // (public) ListRef& ListRef::operator=(const ListRef &copy) { m_listBaseRef = copy.m_listBaseRef->copy(); m_tagName = copy.m_tagName; m_subRef = copy.m_subRef->copyChildGroup(); return *this; } // ============================================================================= // (public) ListRef& ListRef::operator=(ListRef &&move) { m_listBaseRef = std::move(move.m_listBaseRef); m_tagName = std::move(move.m_tagName); m_subRef = std::move(move.m_subRef); return *this; } // ============================================================================= // (public) ListRefUPtr ListRef::copy() const { return MakeUPtr(*this); } // ============================================================================= // (public) int ListRef::count(Element refBase) const { if (refBase.isNull()) { return -1; } Element listBase = m_listBaseRef->getTarget(refBase); if (listBase.isNull()) { return -1; } int nb = 0; Element element = listBase.firstChild(m_tagName); while (!element.isNull()) { nb++; element = element.nextSibling(m_tagName); } return nb; } // ============================================================================= // (public) int ListRef::indexOf(Element refBase, Element refElement) const { if (refBase.isNull()) { return -1; } Element listBase = m_listBaseRef->getTarget(refBase); if (listBase.isNull()) { return -1; } int index = 0; Element element = listBase.firstChild(m_tagName); while (!element.isNull()) { if (m_subRef->getTarget(element) == refElement) { return index; } index++; element = element.nextSibling(m_tagName); } // The child node was not found return -1; } // ============================================================================= // (public) Element ListRef::at(Element refBase, int index) const { if (refBase.isNull()) { return Element(); } Element listBase = m_listBaseRef->getTarget(refBase); if (listBase.isNull()) { return Element(); } int nb = 0; Element element = listBase.firstChild(m_tagName); while (!element.isNull() && nb < index) { nb++; element = element.nextSibling(m_tagName); } return m_subRef->getTarget(element, true); } // ============================================================================= // (public) std::vector<Element> ListRef::list(Element refBase) const { if (refBase.isNull()) { return std::vector<Element>(); } Element listBase = m_listBaseRef->getTarget(refBase); if (listBase.isNull()) { return std::vector<Element>(); } std::vector<Element> eList; Element element = listBase.firstChild(m_tagName); while (!element.isNull()) { eList.push_back(m_subRef->getTarget(element, true)); element = element.nextSibling(m_tagName); } return eList; } // ============================================================================= // (public) Element ListRef::first(Element refBase) const { if (refBase.isNull()) { return Element(); } Element listBase = m_listBaseRef->getTarget(refBase); if (listBase.isNull()) { return Element(); } return m_subRef->getTarget(listBase.firstChild(m_tagName), true); } // ============================================================================= // (public) Element ListRef::last(Element refBase) const { if (refBase.isNull()) { return Element(); } Element listBase = m_listBaseRef->getTarget(refBase); if (listBase.isNull()) { return Element(); } return m_subRef->getTarget(listBase.lastChild(m_tagName), true); } // ============================================================================= // (public) Element ListRef::next(Element element) const { element = m_subRef->getSource(element); if (element.isNull()) { return Element(); } return m_subRef->getTarget(element.nextSibling(m_tagName)); } // ============================================================================= // (public) Element ListRef::previous(Element element) const { element = m_subRef->getSource(element); if (element.isNull()) { return Element(); } return m_subRef->getTarget(element.previousSibling(m_tagName)); } // ============================================================================= // (public) Element ListRef::insert(Element refBase, int index) const { if (refBase.isNull()) { return Element(); } Element listBase = m_listBaseRef->getTarget(refBase); if (listBase.isNull()) { return Element(); } int nb = 1; Element refElement = listBase.firstChild(m_tagName); while (!refElement.isNull() && nb < index) { nb++; refElement = refElement.nextSibling(m_tagName); } if (refElement.isNull()) { if (index > 0) { // The index of the new element is out of range and therefore not created return Element(); } // No elements already exists so the new element is appended refElement = listBase.appendChild(m_tagName); } else { if (index == 0) { // The new element has to be inserted before existing elements // so insert before has to be used refElement = listBase.insertBefore(m_tagName, refElement); } else { // The new element is inserted after the refElement = listBase.insertAfter(m_tagName, refElement); } } return m_subRef->getTarget(refElement, true); } // ============================================================================= // (public) Element ListRef::insertBefore(Element refBase, Element refElement) const { if (refBase.isNull()) { return Element(); } Element listBase = m_listBaseRef->getTarget(refBase); if (listBase.isNull()) { return Element(); } Element element; if (listBase == refElement.parentElement()) { element = listBase.insertBefore(m_tagName, refElement); } else { refElement = m_subRef->getSource(refElement); if (refElement.isNull()) { return Element(); } if (listBase == refElement.parentElement()) { element = listBase.insertBefore(m_tagName, refElement); } else { return Element(); } } return m_subRef->getTarget(element, true); } // ============================================================================= // (public) Element ListRef::insertAfter(Element refBase, Element refElement) const { if (refBase.isNull()) { return Element(); } Element listBase = m_listBaseRef->getTarget(refBase); if (listBase.isNull()) { return Element(); } Element element; if (listBase == refElement.parentElement()) { element = listBase.insertAfter(m_tagName, refElement); } else { refElement = m_subRef->getSource(refElement); if (refElement.isNull()) { return Element(); } if (listBase == refElement.parentElement()) { element = listBase.insertAfter(m_tagName, refElement); } else { return Element(); } } return m_subRef->getTarget(element, true); } // ============================================================================= // (public) Element ListRef::clone(Element refBase, int index, Element cloneElement) const { Element newElement = insert(refBase, index); if (!newElement.isNull()) { newElement.cloneElement(cloneElement); } return newElement; } // ============================================================================= // (public) Element ListRef::cloneBefore(Element refBase, Element refElement, Element cloneElement) const { Element newElement = insertBefore(refBase, refElement); if (!newElement.isNull()) { newElement.cloneElement(cloneElement); } return newElement; } // ============================================================================= // (public) Element ListRef::cloneAfter(Element refBase, Element refElement, Element cloneElement) const { Element newElement = insertAfter(refBase, refElement); if (!newElement.isNull()) { newElement.cloneElement(cloneElement); } return newElement; } // ============================================================================= // (public) Element ListRef::move(Element refBase, int index, Element moveElement) const { // Adjust the index to take into account that the moveElement is moved away int moveIndex = indexOf(refBase, moveElement); if (moveIndex >= 0 && moveIndex < index) { index++; } Element tempElement = insert(refBase, index); if (!tempElement.isNull()) { Element parent = tempElement.parentElement(); Element newElement = parent.moveAfter(moveElement, tempElement); parent.removeChild(tempElement); return newElement; } return Element(); } // ============================================================================= // (public) Element ListRef::moveBefore(Element refBase, Element refElement, Element moveElement) const { Element tempElement = insertBefore(refBase, refElement); if (!tempElement.isNull()) { Element parent = tempElement.parentElement(); Element newElement = parent.moveAfter(moveElement, tempElement); parent.removeChild(tempElement); return newElement; } return Element(); } // ============================================================================= // (public) Element ListRef::moveAfter(Element refBase, Element refElement, Element moveElement) const { Element tempElement = insertAfter(refBase, refElement); if (!tempElement.isNull()) { Element parent = tempElement.parentElement(); Element newElement = parent.moveAfter(moveElement, tempElement); parent.removeChild(tempElement); return newElement; } return Element(); } // ============================================================================= // (public) bool ListRef::remove(Element refBase, Element refElement) const { if (refBase.isNull()) { return false; } Element listBase = m_listBaseRef->getTarget(refBase); if (listBase.isNull()) { return false; } if (listBase == refElement.parentElement()) { return listBase.removeChild(refElement); } else { refElement = m_subRef->getSource(refElement); if (refElement.isNull()) { return false; } if (listBase == refElement.parentElement()) { return listBase.removeChild(refElement); } } return false; } // ============================================================================= // (public) bool ListRef::remove(Element &refBase, int index) const { if (refBase.isNull()) { return false; } Element listBase = m_listBaseRef->getTarget(refBase); if (listBase.isNull()) { return false; } int nb = 0; Element refElement = listBase.firstChild(m_tagName); while (!refElement.isNull() && nb < index) { nb++; refElement = refElement.nextSibling(m_tagName); } if (!refElement.isNull()) { return listBase.removeChild(refElement); } return false; } // ============================================================================= // (public) Element ListRef::invertedAt(Element refElement) const { refElement = m_subRef->getSource(refElement); if (refElement.isNull()) { return Element(); } if (refElement.compareTagName(m_tagName) != 0) { return Element(); } return m_listBaseRef->getSource(refElement.parentElement()); } // ============================================================================= // (public) void ListRef::setListBaseRef(RefUPtr value) { m_listBaseRef = std::move(value); } // ============================================================================= // (public) void ListRef::setTagName(const std::string &value) { assert(!value.empty()); m_tagName = value; } // ============================================================================= // (public) void ListRef::setSubRef(ChildRefGroupUPtr value) { m_subRef = std::move(value); } } // namespace XML } // namespace Oak #endif // XML_BACKEND <commit_msg>XML list base can now be created when the first element in the list is created<commit_after>/** * oakmodelview - version 0.1.0 * -------------------------------------------------------- * Copyright (C) 2017, by Mikkel Nøhr Løvgreen (mikkel@oakmodelview.com) * Report bugs and download new versions at http://oakmodelview.com/ * * This library is distributed under the MIT License. * See accompanying file LICENSE in the root folder. */ #ifdef XML_BACKEND #include "XMLListRef.h" namespace Oak { namespace XML { // ============================================================================= // (public) ListRef::ListRef(const std::string &elementTagName) : m_listBaseRef(Ref::MakeUPtr()), m_tagName(elementTagName), m_subRef(ChildRefGroup::MakeUPtr()) { } // ============================================================================= // (public) ListRef::ListRef(RefUPtr listBaseRef, const std::string &elementTagName, ChildRefGroupUPtr elementSubRef) : m_listBaseRef(std::move(listBaseRef)), m_tagName(elementTagName), m_subRef(std::move(elementSubRef)) { assert(!m_tagName.empty()); } // ============================================================================= // (public) ListRef::ListRef(const ListRef &copy) { *this = copy; } // ============================================================================= // (public) ListRef::ListRef(ListRef &&move) { *this = std::move(move); } // ============================================================================= // (public) ListRef::~ListRef() { } // ============================================================================= // (public) ListRef& ListRef::operator=(const ListRef &copy) { m_listBaseRef = copy.m_listBaseRef->copy(); m_tagName = copy.m_tagName; m_subRef = copy.m_subRef->copyChildGroup(); return *this; } // ============================================================================= // (public) ListRef& ListRef::operator=(ListRef &&move) { m_listBaseRef = std::move(move.m_listBaseRef); m_tagName = std::move(move.m_tagName); m_subRef = std::move(move.m_subRef); return *this; } // ============================================================================= // (public) ListRefUPtr ListRef::copy() const { return MakeUPtr(*this); } // ============================================================================= // (public) int ListRef::count(Element refBase) const { if (refBase.isNull()) { return -1; } Element listBase = m_listBaseRef->getTarget(refBase); if (listBase.isNull()) { return 0; } int nb = 0; Element element = listBase.firstChild(m_tagName); while (!element.isNull()) { nb++; element = element.nextSibling(m_tagName); } return nb; } // ============================================================================= // (public) int ListRef::indexOf(Element refBase, Element refElement) const { if (refBase.isNull()) { return -1; } Element listBase = m_listBaseRef->getTarget(refBase); if (listBase.isNull()) { return -1; } int index = 0; Element element = listBase.firstChild(m_tagName); while (!element.isNull()) { if (m_subRef->getTarget(element) == refElement) { return index; } index++; element = element.nextSibling(m_tagName); } // The child node was not found return -1; } // ============================================================================= // (public) Element ListRef::at(Element refBase, int index) const { if (refBase.isNull()) { return Element(); } Element listBase = m_listBaseRef->getTarget(refBase); if (listBase.isNull()) { return Element(); } int nb = 0; Element element = listBase.firstChild(m_tagName); while (!element.isNull() && nb < index) { nb++; element = element.nextSibling(m_tagName); } return m_subRef->getTarget(element, true); } // ============================================================================= // (public) std::vector<Element> ListRef::list(Element refBase) const { if (refBase.isNull()) { return std::vector<Element>(); } Element listBase = m_listBaseRef->getTarget(refBase); if (listBase.isNull()) { return std::vector<Element>(); } std::vector<Element> eList; Element element = listBase.firstChild(m_tagName); while (!element.isNull()) { eList.push_back(m_subRef->getTarget(element, true)); element = element.nextSibling(m_tagName); } return eList; } // ============================================================================= // (public) Element ListRef::first(Element refBase) const { if (refBase.isNull()) { return Element(); } Element listBase = m_listBaseRef->getTarget(refBase); if (listBase.isNull()) { return Element(); } return m_subRef->getTarget(listBase.firstChild(m_tagName), true); } // ============================================================================= // (public) Element ListRef::last(Element refBase) const { if (refBase.isNull()) { return Element(); } Element listBase = m_listBaseRef->getTarget(refBase); if (listBase.isNull()) { return Element(); } return m_subRef->getTarget(listBase.lastChild(m_tagName), true); } // ============================================================================= // (public) Element ListRef::next(Element element) const { element = m_subRef->getSource(element); if (element.isNull()) { return Element(); } return m_subRef->getTarget(element.nextSibling(m_tagName)); } // ============================================================================= // (public) Element ListRef::previous(Element element) const { element = m_subRef->getSource(element); if (element.isNull()) { return Element(); } return m_subRef->getTarget(element.previousSibling(m_tagName)); } // ============================================================================= // (public) Element ListRef::insert(Element refBase, int index) const { if (refBase.isNull()) { return Element(); } Element listBase = m_listBaseRef->getTarget(refBase, true); if (listBase.isNull()) { return Element(); } int nb = 1; Element refElement = listBase.firstChild(m_tagName); while (!refElement.isNull() && nb < index) { nb++; refElement = refElement.nextSibling(m_tagName); } if (refElement.isNull()) { if (index > 0) { // The index of the new element is out of range and therefore not created return Element(); } // No elements already exists so the new element is appended refElement = listBase.appendChild(m_tagName); } else { if (index == 0) { // The new element has to be inserted before existing elements // so insert before has to be used refElement = listBase.insertBefore(m_tagName, refElement); } else { // The new element is inserted after the refElement = listBase.insertAfter(m_tagName, refElement); } } return m_subRef->getTarget(refElement, true); } // ============================================================================= // (public) Element ListRef::insertBefore(Element refBase, Element refElement) const { if (refBase.isNull()) { return Element(); } Element listBase = m_listBaseRef->getTarget(refBase); if (listBase.isNull()) { return Element(); } Element element; if (listBase == refElement.parentElement()) { element = listBase.insertBefore(m_tagName, refElement); } else { refElement = m_subRef->getSource(refElement); if (refElement.isNull()) { return Element(); } if (listBase == refElement.parentElement()) { element = listBase.insertBefore(m_tagName, refElement); } else { return Element(); } } return m_subRef->getTarget(element, true); } // ============================================================================= // (public) Element ListRef::insertAfter(Element refBase, Element refElement) const { if (refBase.isNull()) { return Element(); } Element listBase = m_listBaseRef->getTarget(refBase); if (listBase.isNull()) { return Element(); } Element element; if (listBase == refElement.parentElement()) { element = listBase.insertAfter(m_tagName, refElement); } else { refElement = m_subRef->getSource(refElement); if (refElement.isNull()) { return Element(); } if (listBase == refElement.parentElement()) { element = listBase.insertAfter(m_tagName, refElement); } else { return Element(); } } return m_subRef->getTarget(element, true); } // ============================================================================= // (public) Element ListRef::clone(Element refBase, int index, Element cloneElement) const { Element newElement = insert(refBase, index); if (!newElement.isNull()) { newElement.cloneElement(cloneElement); } return newElement; } // ============================================================================= // (public) Element ListRef::cloneBefore(Element refBase, Element refElement, Element cloneElement) const { Element newElement = insertBefore(refBase, refElement); if (!newElement.isNull()) { newElement.cloneElement(cloneElement); } return newElement; } // ============================================================================= // (public) Element ListRef::cloneAfter(Element refBase, Element refElement, Element cloneElement) const { Element newElement = insertAfter(refBase, refElement); if (!newElement.isNull()) { newElement.cloneElement(cloneElement); } return newElement; } // ============================================================================= // (public) Element ListRef::move(Element refBase, int index, Element moveElement) const { // Adjust the index to take into account that the moveElement is moved away int moveIndex = indexOf(refBase, moveElement); if (moveIndex >= 0 && moveIndex < index) { index++; } Element tempElement = insert(refBase, index); if (!tempElement.isNull()) { Element parent = tempElement.parentElement(); Element newElement = parent.moveAfter(moveElement, tempElement); parent.removeChild(tempElement); return newElement; } return Element(); } // ============================================================================= // (public) Element ListRef::moveBefore(Element refBase, Element refElement, Element moveElement) const { Element tempElement = insertBefore(refBase, refElement); if (!tempElement.isNull()) { Element parent = tempElement.parentElement(); Element newElement = parent.moveAfter(moveElement, tempElement); parent.removeChild(tempElement); return newElement; } return Element(); } // ============================================================================= // (public) Element ListRef::moveAfter(Element refBase, Element refElement, Element moveElement) const { Element tempElement = insertAfter(refBase, refElement); if (!tempElement.isNull()) { Element parent = tempElement.parentElement(); Element newElement = parent.moveAfter(moveElement, tempElement); parent.removeChild(tempElement); return newElement; } return Element(); } // ============================================================================= // (public) bool ListRef::remove(Element refBase, Element refElement) const { if (refBase.isNull()) { return false; } Element listBase = m_listBaseRef->getTarget(refBase); if (listBase.isNull()) { return false; } if (listBase == refElement.parentElement()) { return listBase.removeChild(refElement); } else { refElement = m_subRef->getSource(refElement); if (refElement.isNull()) { return false; } if (listBase == refElement.parentElement()) { return listBase.removeChild(refElement); } } return false; } // ============================================================================= // (public) bool ListRef::remove(Element &refBase, int index) const { if (refBase.isNull()) { return false; } Element listBase = m_listBaseRef->getTarget(refBase); if (listBase.isNull()) { return false; } int nb = 0; Element refElement = listBase.firstChild(m_tagName); while (!refElement.isNull() && nb < index) { nb++; refElement = refElement.nextSibling(m_tagName); } if (!refElement.isNull()) { return listBase.removeChild(refElement); } return false; } // ============================================================================= // (public) Element ListRef::invertedAt(Element refElement) const { refElement = m_subRef->getSource(refElement); if (refElement.isNull()) { return Element(); } if (refElement.compareTagName(m_tagName) != 0) { return Element(); } return m_listBaseRef->getSource(refElement.parentElement()); } // ============================================================================= // (public) void ListRef::setListBaseRef(RefUPtr value) { m_listBaseRef = std::move(value); } // ============================================================================= // (public) void ListRef::setTagName(const std::string &value) { assert(!value.empty()); m_tagName = value; } // ============================================================================= // (public) void ListRef::setSubRef(ChildRefGroupUPtr value) { m_subRef = std::move(value); } } // namespace XML } // namespace Oak #endif // XML_BACKEND <|endoftext|>
<commit_before>#include <atomic> #include <chrono> #include <random> #include <string> #include <thread> #include <TFile.h> #include <TTree.h> #include <TSystem.h> #include <TTreeReader.h> #include <TTreeReaderValue.h> #include <ROOT/TTreeProcessorMT.hxx> #include "gtest/gtest.h" void WriteFiles(const std::string &treename, const std::vector<std::string> &filenames) { int v = 0; for (const auto &f : filenames) { TFile file(f.c_str(), "recreate"); TTree t(treename.c_str(), treename.c_str()); t.Branch("v", &v); for (auto i = 0; i < 10; ++i) { ++v; t.Fill(); } t.Write(); } } void DeleteFiles(const std::vector<std::string> &filenames) { for (const auto &f : filenames) gSystem->Unlink(f.c_str()); } TEST(TreeProcessorMT, EmptyTChain) { TChain c("mytree"); auto exceptionFired(false); try { ROOT::TTreeProcessorMT proc(c); } catch(...) { exceptionFired = true; } EXPECT_TRUE(exceptionFired); } TEST(TreeProcessorMT, ManyFiles) { const auto nFiles = 100u; const std::string treename = "t"; std::vector<std::string> filenames; for (auto i = 0u; i < nFiles; ++i) filenames.emplace_back("treeprocmt_" + std::to_string(i) + ".root"); WriteFiles(treename, filenames); std::atomic_int sum(0); std::atomic_int count(0); auto sumValues = [&sum, &count](TTreeReader &r) { TTreeReaderValue<int> v(r, "v"); std::random_device seed; std::default_random_engine eng(seed()); std::uniform_int_distribution<> rand(1, 100); while (r.Next()) { std::this_thread::sleep_for(std::chrono::nanoseconds(rand(eng))); sum += *v; ++count; } }; // TTreeProcMT requires a vector<string_view> std::vector<std::string_view> fnames; for (const auto &f : filenames) fnames.emplace_back(f); ROOT::TTreeProcessorMT proc(fnames, treename); proc.Process(sumValues); EXPECT_EQ(count.load(), int(nFiles*10)); // 10 entries per file EXPECT_EQ(sum.load(), 500500); // sum 1..nFiles*10 DeleteFiles(filenames); } TEST(TreeProcessorMT, TreeInSubDirectory) { auto filename = "fileTreeInSubDirectory.root"; auto procLambda = [](TTreeReader &r) { while (r.Next()); }; { TFile f(filename, "RECREATE"); auto dir0 = f.mkdir("dir0"); dir0->cd(); auto dir1 = dir0->mkdir("dir1"); dir1->cd(); TTree t("tree", "tree"); t.Write(); } ROOT::EnableThreadSafety(); auto fullPath = "dir0/dir1/tree"; // With a TTree TFile f(filename); auto t = (TTree *)f.Get(fullPath); ROOT::TTreeProcessorMT tp(*t); tp.Process(procLambda); // With a TChain std::string chainElementName = filename; chainElementName += "/"; chainElementName += fullPath; TChain chain; chain.Add(chainElementName.c_str()); ROOT::TTreeProcessorMT tpc(chain); tpc.Process(procLambda); gSystem->Unlink(filename); } <commit_msg>[TTreeProcessorMT][ROOT-9791] Add test<commit_after>#include <atomic> #include <chrono> #include <random> #include <string> #include <thread> #include <TFile.h> #include <TTree.h> #include <TSystem.h> #include <TTreeReader.h> #include <TTreeReaderValue.h> #include <ROOT/TTreeProcessorMT.hxx> #include "gtest/gtest.h" void WriteFiles(const std::string &treename, const std::vector<std::string> &filenames) { int v = 0; for (const auto &f : filenames) { TFile file(f.c_str(), "recreate"); TTree t(treename.c_str(), treename.c_str()); t.Branch("v", &v); for (auto i = 0; i < 10; ++i) { ++v; t.Fill(); } t.Write(); } } void WriteFileManyClusters(unsigned int nevents, const char *treename, const char *filename) { int v = 0; TFile file(filename, "recreate"); TTree t(treename, treename); t.Branch("v", &v); //t.SetAutoFlush(1); for (auto i = 0U; i < nevents; ++i) { t.Fill(); t.FlushBaskets(); } t.Write(); file.Close(); } void DeleteFiles(const std::vector<std::string> &filenames) { for (const auto &f : filenames) gSystem->Unlink(f.c_str()); } TEST(TreeProcessorMT, EmptyTChain) { TChain c("mytree"); auto exceptionFired(false); try { ROOT::TTreeProcessorMT proc(c); } catch (...) { exceptionFired = true; } EXPECT_TRUE(exceptionFired); } TEST(TreeProcessorMT, ManyFiles) { const auto nFiles = 100u; const std::string treename = "t"; std::vector<std::string> filenames; for (auto i = 0u; i < nFiles; ++i) filenames.emplace_back("treeprocmt_" + std::to_string(i) + ".root"); WriteFiles(treename, filenames); std::atomic_int sum(0); std::atomic_int count(0); auto sumValues = [&sum, &count](TTreeReader &r) { TTreeReaderValue<int> v(r, "v"); std::random_device seed; std::default_random_engine eng(seed()); std::uniform_int_distribution<> rand(1, 100); while (r.Next()) { std::this_thread::sleep_for(std::chrono::nanoseconds(rand(eng))); sum += *v; ++count; } }; // TTreeProcMT requires a vector<string_view> std::vector<std::string_view> fnames; for (const auto &f : filenames) fnames.emplace_back(f); ROOT::TTreeProcessorMT proc(fnames, treename); proc.Process(sumValues); EXPECT_EQ(count.load(), int(nFiles * 10)); // 10 entries per file EXPECT_EQ(sum.load(), 500500); // sum 1..nFiles*10 DeleteFiles(filenames); } TEST(TreeProcessorMT, TreeInSubDirectory) { auto filename = "fileTreeInSubDirectory.root"; auto procLambda = [](TTreeReader &r) { while (r.Next()) ; }; { TFile f(filename, "RECREATE"); auto dir0 = f.mkdir("dir0"); dir0->cd(); auto dir1 = dir0->mkdir("dir1"); dir1->cd(); TTree t("tree", "tree"); t.Write(); } ROOT::EnableThreadSafety(); auto fullPath = "dir0/dir1/tree"; // With a TTree TFile f(filename); auto t = (TTree *)f.Get(fullPath); ROOT::TTreeProcessorMT tp(*t); tp.Process(procLambda); // With a TChain std::string chainElementName = filename; chainElementName += "/"; chainElementName += fullPath; TChain chain; chain.Add(chainElementName.c_str()); ROOT::TTreeProcessorMT tpc(chain); tpc.Process(procLambda); gSystem->Unlink(filename); } TEST(TreeProcessorMT, MaxTasks) { const auto nEvents = 991; const auto filename = "TreeProcessorMT_MaxTasks.root"; const auto treename = "t"; WriteFileManyClusters(nEvents, treename, filename); auto nTasks = 0U; std::map<unsigned int, unsigned int> nEntriesCountsMap; std::mutex theMutex; auto f = [&](TTreeReader &t) { auto nentries = 0U; while(t.Next()) nentries++; std::lock_guard<std::mutex> lg(theMutex); nTasks++; if(!nEntriesCountsMap.insert({nentries, 1U}).second) { nEntriesCountsMap[nentries]++; } }; ROOT::DisableImplicitMT(); ROOT::EnableImplicitMT(4); ROOT::TTreeProcessorMT p(filename, treename); p.Process(f); EXPECT_EQ(nTasks, 96U) << "Wrong number of tasks generated!\n"; EXPECT_EQ(nEntriesCountsMap[10], 65U) << "Wrong number of tasks with 10 clusters each!\n"; EXPECT_EQ(nEntriesCountsMap[11], 31U) << "Wrong number of tasks with 11 clusters each!\n"; gSystem->Unlink(filename); ROOT::DisableImplicitMT(); }<|endoftext|>
<commit_before>// Time: O(logn) // Space: O(1) class Solution { public: /** * @param dividend the dividend * @param divisor the divisor * @return the result */ int divide(int dividend, int divisor) { // Handle corner case. if (divisor == INT_MIN) { return dividend == divisor ? 1 : 0; } else if (!divisor || divisor == -1 && dividend == INT_MIN) { return INT_MAX; } else if (divisor == 1) { return dividend; } bool negative = (dividend > 0) ^ (divisor > 0); if (dividend > 0) { dividend = -dividend; } if (divisor > 0) { divisor = -divisor; } vector<int> multipliers, products; multipliers.push_back(1); products.push_back(divisor); int idx = 1, res = 0; while (products[idx - 1] < 0 && idx < 32) { products.push_back(divisor << idx); multipliers.push_back(1 << idx); ++idx; } idx -= 2; while (dividend <= divisor) { if (dividend <= products[idx]) { res += multipliers[idx]; dividend -= products[idx]; } --idx; } return negative ? -res : res; } }; <commit_msg>Update divide-two-integers.cpp<commit_after>// Time: O(logn) // Space: O(1) class Solution { public: /** * @param dividend the dividend * @param divisor the divisor * @return the result */ int divide(int dividend, int divisor) { // Handle corner case. if (divisor == INT_MIN) { return dividend == divisor ? 1 : 0; } else if (!divisor || divisor == -1 && dividend == INT_MIN) { return INT_MAX; } else if (divisor == 1) { return dividend; } bool negative = (dividend > 0) ^ (divisor > 0); if (dividend > 0) { dividend = -dividend; } if (divisor > 0) { divisor = -divisor; } int product = divisor; int idx = 1; while (product < 0 && idx < 32) { ++idx; product <<= 1; } idx -= 2; // Skip value of INT_MIN product = divisor << idx; int multiplier = 1 << idx; int res = 0; while (dividend <= divisor) { if (dividend <= product) { res += multiplier; dividend -= product; } --idx; product = divisor << idx; multiplier >>= 1; } return negative ? -res : res; } }; class Solution2 { public: /** * @param dividend the dividend * @param divisor the divisor * @return the result */ int divide(int dividend, int divisor) { // Handle corner case. if (divisor == INT_MIN) { return dividend == divisor ? 1 : 0; } else if (!divisor || divisor == -1 && dividend == INT_MIN) { return INT_MAX; } else if (divisor == 1) { return dividend; } bool negative = (dividend > 0) ^ (divisor > 0); if (dividend > 0) { dividend = -dividend; } if (divisor > 0) { divisor = -divisor; } vector<int> multipliers, products; multipliers.push_back(1); products.push_back(divisor); int idx = 1, res = 0; while (products[idx - 1] < 0 && idx < 32) { products.push_back(divisor << idx); multipliers.push_back(1 << idx); ++idx; } idx -= 2; while (dividend <= divisor) { if (dividend <= products[idx]) { res += multipliers[idx]; dividend -= products[idx]; } --idx; } return negative ? -res : res; } }; <|endoftext|>
<commit_before>// Time: O(k * n^2) // Space: O(n^2) class Solution { public: /** * @param A an integer array * @param k an integer * @return an integer */ int postOffice(vector<int>& A, int k) { const int n = A.size(); if (A.empty() || k >= n) { return 0; } sort(A.begin(), A.end()); // Time: O(nlogn) // Precompute cost. // Time: O(n^2) // Space: O(n^2) vector<vector<int>> cost(A.size() + 1, vector<int>(A.size() + 1, 0)); computeMinCost(A, &cost); // DP of sum. // Time: O(k * n^2) // Space: O(n) // sum[i][j] denotes the smallest sum of // picking i post offices for the first j houses. vector<vector<int>> sum(2, vector<int>(A.size() + 1, INT_MAX)); sum[0][0] = 0; for (int i = 1; i <= k; ++i) { for (int j = 0; j <= n; ++j) { // We can skip this line due to sum[i][j] <= sum[i - 2][j] // sum[i % 2][j] = INT_MAX; for (int r = 1; r <= j; ++r) { if (sum[(i - 1) % 2][j - r] != INT_MAX) { sum[i % 2][j] = min(sum[i % 2][j], sum[(i - 1) % 2][j - r] + cost[j - r + 1][j]); } } } } return sum[k % 2][n]; } void computeMinCost(const vector<int>& A, vector<vector<int>> *cost) { // Min cost of building a post office between house (i, j). // This post office must be in median position. const int n = A.size(); vector<int> before_diff(n), after_diff(n); for (int i = 1; i < n; ++i) { before_diff[i] = before_diff[i - 1] + i * (A[i] - A[i - 1]); } for (int i = n - 2; i >= 0; --i) { after_diff[i] = after_diff[i + 1] + (n - 1 - i) * (A[i + 1] - A[i]); } for (int i = 0; i < n; ++i) { for (int j = i; j < n; ++j) { int mid = i + (j - i) / 2; int before_mid = before_diff[mid] - (before_diff[i] + i * (A[mid] - A[i])); int after_mid = after_diff[mid] - (after_diff[j] + (n - 1 - j) * (A[j] - A[mid])); (*cost)[i + 1][j + 1] += before_mid + after_mid; } } } }; // Time: O(n^3) // Space: O(n^2) class Solution2 { public: /** * @param A an integer array * @param k an integer * @return an integer */ int postOffice(vector<int>& A, int k) { const int n = A.size(); if (A.empty() || k >= n) { return 0; } sort(A.begin(), A.end()); // Time: O(nlogn) // Precompute cost. // Time: O(n^3) // Space: O(n^2) vector<vector<int>> cost(A.size() + 1, vector<int>(A.size() + 1, 0)); computeMinCost(A, &cost); // DP of sum. // Time: O(k * n^2) // Space: O(k * n) // sum[i][j] denotes the smallest sum of // picking i post offices for the first j houses. vector<vector<int>> sum(k + 1, vector<int>(A.size() + 1, INT_MAX)); sum[0][0] = 0; for (int i = 1; i <= k; ++i) { for (int j = 0; j < n; ++j) { if (sum[i - 1][j] != INT_MAX) { for (int r = 1; j + r <= n; ++r) { sum[i][j + r] = min(sum[i][j + r], sum[i - 1][j] + cost[j + 1][j + r]); } } } } return sum[k][n]; } void computeMinCost(const vector<int>& A, vector<vector<int>> *cost) { // Min cost of building a post office between house (i, j). // This post office must be in median position. const int n = A.size(); for (int i = 0; i < n; ++i) { for (int j = i; j < n; ++j) { int mid = (i + j) / 2; for (int r = i; r <= mid; ++r) { (*cost)[i + 1][j + 1] += A[mid] - A[r]; } for (int r = mid + 1; r <= j; ++r) { (*cost)[i + 1][j + 1] += A[r] - A[mid]; } } } } }; <commit_msg>Update post-office-problem.cpp<commit_after>// Time: O(k * n^2) // Space: O(n^2) class Solution { public: /** * @param A an integer array * @param k an integer * @return an integer */ int postOffice(vector<int>& A, int k) { const int n = A.size(); if (A.empty() || k >= n) { return 0; } sort(A.begin(), A.end()); // Time: O(nlogn) // Precompute cost. // Time: O(n^2) // Space: O(n^2) vector<vector<int>> cost(A.size() + 1, vector<int>(A.size() + 1, 0)); computeMinCost(A, &cost); // DP of sum. // Time: O(k * n^2) // Space: O(n) // sum[i][j] denotes the smallest sum of // picking i post offices for the first j houses. vector<vector<int>> sum(2, vector<int>(A.size() + 1, INT_MAX)); sum[0][0] = 0; for (int i = 1; i <= k; ++i) { for (int j = 0; j <= n; ++j) { // We can skip this line due to sum[i][j] <= sum[i - 2][j] // sum[i % 2][j] = INT_MAX; for (int r = 1; r <= j; ++r) { if (sum[(i - 1) % 2][j - r] != INT_MAX) { sum[i % 2][j] = min(sum[i % 2][j], sum[(i - 1) % 2][j - r] + cost[j - r + 1][j]); } } } } return sum[k % 2][n]; } void computeMinCost(const vector<int>& A, vector<vector<int>> *cost) { // Min cost of building a post office between house (i, j). // This post office must be in median position. const int n = A.size(); vector<int> before_diff(n), after_diff(n); for (int i = 1; i < n; ++i) { // before_diff[i] = Sum(A[i] - A[k]) for k < i before_diff[i] = before_diff[i - 1] + i * (A[i] - A[i - 1]); } for (int i = n - 2; i >= 0; --i) { // after_diff[i] = Sum(A[k] - A[i]) for k > i after_diff[i] = after_diff[i + 1] + (n - 1 - i) * (A[i + 1] - A[i]); } for (int i = 0; i < n; ++i) { for (int j = i; j < n; ++j) { int mid = i + (j - i) / 2; int before_mid = before_diff[mid] - (before_diff[i] + i * (A[mid] - A[i])); int after_mid = after_diff[mid] - (after_diff[j] + (n - 1 - j) * (A[j] - A[mid])); (*cost)[i + 1][j + 1] += before_mid + after_mid; } } } }; // Time: O(n^3) // Space: O(n^2) class Solution2 { public: /** * @param A an integer array * @param k an integer * @return an integer */ int postOffice(vector<int>& A, int k) { const int n = A.size(); if (A.empty() || k >= n) { return 0; } sort(A.begin(), A.end()); // Time: O(nlogn) // Precompute cost. // Time: O(n^3) // Space: O(n^2) vector<vector<int>> cost(A.size() + 1, vector<int>(A.size() + 1, 0)); computeMinCost(A, &cost); // DP of sum. // Time: O(k * n^2) // Space: O(k * n) // sum[i][j] denotes the smallest sum of // picking i post offices for the first j houses. vector<vector<int>> sum(k + 1, vector<int>(A.size() + 1, INT_MAX)); sum[0][0] = 0; for (int i = 1; i <= k; ++i) { for (int j = 0; j < n; ++j) { if (sum[i - 1][j] != INT_MAX) { for (int r = 1; j + r <= n; ++r) { sum[i][j + r] = min(sum[i][j + r], sum[i - 1][j] + cost[j + 1][j + r]); } } } } return sum[k][n]; } void computeMinCost(const vector<int>& A, vector<vector<int>> *cost) { // Min cost of building a post office between house (i, j). // This post office must be in median position. const int n = A.size(); for (int i = 0; i < n; ++i) { for (int j = i; j < n; ++j) { int mid = (i + j) / 2; for (int r = i; r <= mid; ++r) { (*cost)[i + 1][j + 1] += A[mid] - A[r]; } for (int r = mid + 1; r <= j; ++r) { (*cost)[i + 1][j + 1] += A[r] - A[mid]; } } } } }; <|endoftext|>
<commit_before>#include "master.hpp" namespace factor { gc_event::gc_event(gc_op op, factor_vm* parent) : op(op), cards_scanned(0), decks_scanned(0), code_blocks_scanned(0), start_time(nano_count()), card_scan_time(0), code_scan_time(0), data_sweep_time(0), code_sweep_time(0), compaction_time(0) { data_heap_before = parent->data_room(); code_heap_before = parent->code->allocator->as_allocator_room(); start_time = nano_count(); } void gc_event::started_card_scan() { temp_time = nano_count(); } void gc_event::ended_card_scan(cell cards_scanned_, cell decks_scanned_) { cards_scanned += cards_scanned_; decks_scanned += decks_scanned_; card_scan_time = (cell)(nano_count() - temp_time); } void gc_event::started_code_scan() { temp_time = nano_count(); } void gc_event::ended_code_scan(cell code_blocks_scanned_) { code_blocks_scanned += code_blocks_scanned_; code_scan_time = (cell)(nano_count() - temp_time); } void gc_event::started_data_sweep() { temp_time = nano_count(); } void gc_event::ended_data_sweep() { data_sweep_time = (cell)(nano_count() - temp_time); } void gc_event::started_code_sweep() { temp_time = nano_count(); } void gc_event::ended_code_sweep() { code_sweep_time = (cell)(nano_count() - temp_time); } void gc_event::started_compaction() { temp_time = nano_count(); } void gc_event::ended_compaction() { compaction_time = (cell)(nano_count() - temp_time); } void gc_event::ended_gc(factor_vm* parent) { data_heap_after = parent->data_room(); code_heap_after = parent->code->allocator->as_allocator_room(); total_time = (cell)(nano_count() - start_time); } gc_state::gc_state(gc_op op, factor_vm* parent) : op(op) { if (parent->gc_events) { event = new gc_event(op, parent); start_time = nano_count(); } else event = NULL; } gc_state::~gc_state() { if (event) { delete event; event = NULL; } } void factor_vm::end_gc() { if (gc_events) { current_gc->event->ended_gc(this); gc_events->push_back(*current_gc->event); } } void factor_vm::start_gc_again() { end_gc(); switch (current_gc->op) { case collect_nursery_op: /* Nursery collection can fail if aging does not have enough free space to fit all live objects from nursery. */ current_gc->op = collect_aging_op; break; case collect_aging_op: /* Aging collection can fail if the aging semispace cannot fit all the live objects from the other aging semispace and the nursery. */ current_gc->op = collect_to_tenured_op; break; default: /* Nothing else should fail mid-collection due to insufficient space in the target generation. */ critical_error("Bad GC op", current_gc->op); break; } if (gc_events) current_gc->event = new gc_event(current_gc->op, this); } void factor_vm::set_current_gc_op(gc_op op) { current_gc->op = op; if (gc_events) current_gc->event->op = op; } void factor_vm::gc(gc_op op, cell requested_size, bool trace_contexts_p) { FACTOR_ASSERT(!gc_off); FACTOR_ASSERT(!current_gc); /* Important invariant: tenured space must have enough contiguous free space to fit the entire contents of the aging space and nursery. This is because when doing a full collection, objects from younger generations are promoted before any unreachable tenured objects are freed. */ FACTOR_ASSERT(!data->high_fragmentation_p()); current_gc = new gc_state(op, this); atomic::store(&current_gc_p, true); /* Keep trying to GC higher and higher generations until we don't run out of space in the target generation. */ for (;;) { try { if (gc_events) current_gc->event->op = current_gc->op; switch (current_gc->op) { case collect_nursery_op: collect_nursery(); break; case collect_aging_op: /* We end up here if the above fails. */ collect_aging(); if (data->high_fragmentation_p()) { /* Change GC op so that if we fail again, we crash. */ set_current_gc_op(collect_full_op); collect_full(trace_contexts_p); } break; case collect_to_tenured_op: /* We end up here if the above fails. */ collect_to_tenured(); if (data->high_fragmentation_p()) { /* Change GC op so that if we fail again, we crash. */ set_current_gc_op(collect_full_op); collect_full(trace_contexts_p); } break; case collect_full_op: collect_full(trace_contexts_p); break; case collect_compact_op: collect_compact(trace_contexts_p); break; case collect_growing_heap_op: collect_growing_heap(requested_size, trace_contexts_p); break; default: critical_error("Bad GC op", current_gc->op); break; } break; } catch (const must_start_gc_again&) { /* We come back here if the target generation is full. */ start_gc_again(); continue; } } end_gc(); atomic::store(&current_gc_p, false); delete current_gc; current_gc = NULL; /* Check the invariant again, just in case. */ FACTOR_ASSERT(!data->high_fragmentation_p()); } void factor_vm::primitive_minor_gc() { gc(collect_nursery_op, 0, /* requested size */ true /* trace contexts? */); } void factor_vm::primitive_full_gc() { gc(collect_full_op, 0, /* requested size */ true /* trace contexts? */); } void factor_vm::primitive_compact_gc() { gc(collect_compact_op, 0, /* requested size */ true /* trace contexts? */); } /* * It is up to the caller to fill in the object's fields in a meaningful * fashion! */ /* Allocates memory */ object* factor_vm::allot_large_object(cell type, cell size) { /* If tenured space does not have enough room, collect and compact */ cell requested_size = size + data->high_water_mark(); if (!data->tenured->can_allot_p(requested_size)) { primitive_compact_gc(); /* If it still won't fit, grow the heap */ if (!data->tenured->can_allot_p(requested_size)) { gc(collect_growing_heap_op, size, /* requested size */ true /* trace contexts? */); } } object* obj = data->tenured->allot(size); /* Allows initialization code to store old->new pointers without hitting the write barrier in the common case of a nursery allocation */ write_barrier(obj, size); obj->initialize(type); return obj; } void factor_vm::primitive_enable_gc_events() { gc_events = new std::vector<gc_event>(); } /* Allocates memory (byte_array_from_value, result.add) */ /* XXX: Remember that growable_array has a data_root already */ void factor_vm::primitive_disable_gc_events() { if (gc_events) { growable_array result(this); std::vector<gc_event>* gc_events = this->gc_events; this->gc_events = NULL; std::vector<gc_event>::const_iterator iter = gc_events->begin(); std::vector<gc_event>::const_iterator end = gc_events->end(); for (; iter != end; iter++) { gc_event event = *iter; byte_array* obj = byte_array_from_value(&event); result.add(tag<byte_array>(obj)); } result.trim(); ctx->push(result.elements.value()); delete this->gc_events; } else ctx->push(false_object); } } <commit_msg>vm: We don't want ambiguity for which print triggered on a gc error. Differentiate the error messages.<commit_after>#include "master.hpp" namespace factor { gc_event::gc_event(gc_op op, factor_vm* parent) : op(op), cards_scanned(0), decks_scanned(0), code_blocks_scanned(0), start_time(nano_count()), card_scan_time(0), code_scan_time(0), data_sweep_time(0), code_sweep_time(0), compaction_time(0) { data_heap_before = parent->data_room(); code_heap_before = parent->code->allocator->as_allocator_room(); start_time = nano_count(); } void gc_event::started_card_scan() { temp_time = nano_count(); } void gc_event::ended_card_scan(cell cards_scanned_, cell decks_scanned_) { cards_scanned += cards_scanned_; decks_scanned += decks_scanned_; card_scan_time = (cell)(nano_count() - temp_time); } void gc_event::started_code_scan() { temp_time = nano_count(); } void gc_event::ended_code_scan(cell code_blocks_scanned_) { code_blocks_scanned += code_blocks_scanned_; code_scan_time = (cell)(nano_count() - temp_time); } void gc_event::started_data_sweep() { temp_time = nano_count(); } void gc_event::ended_data_sweep() { data_sweep_time = (cell)(nano_count() - temp_time); } void gc_event::started_code_sweep() { temp_time = nano_count(); } void gc_event::ended_code_sweep() { code_sweep_time = (cell)(nano_count() - temp_time); } void gc_event::started_compaction() { temp_time = nano_count(); } void gc_event::ended_compaction() { compaction_time = (cell)(nano_count() - temp_time); } void gc_event::ended_gc(factor_vm* parent) { data_heap_after = parent->data_room(); code_heap_after = parent->code->allocator->as_allocator_room(); total_time = (cell)(nano_count() - start_time); } gc_state::gc_state(gc_op op, factor_vm* parent) : op(op) { if (parent->gc_events) { event = new gc_event(op, parent); start_time = nano_count(); } else event = NULL; } gc_state::~gc_state() { if (event) { delete event; event = NULL; } } void factor_vm::end_gc() { if (gc_events) { current_gc->event->ended_gc(this); gc_events->push_back(*current_gc->event); } } void factor_vm::start_gc_again() { end_gc(); switch (current_gc->op) { case collect_nursery_op: /* Nursery collection can fail if aging does not have enough free space to fit all live objects from nursery. */ current_gc->op = collect_aging_op; break; case collect_aging_op: /* Aging collection can fail if the aging semispace cannot fit all the live objects from the other aging semispace and the nursery. */ current_gc->op = collect_to_tenured_op; break; default: /* Nothing else should fail mid-collection due to insufficient space in the target generation. */ critical_error("in start_gc_again, bad GC op", current_gc->op); break; } if (gc_events) current_gc->event = new gc_event(current_gc->op, this); } void factor_vm::set_current_gc_op(gc_op op) { current_gc->op = op; if (gc_events) current_gc->event->op = op; } void factor_vm::gc(gc_op op, cell requested_size, bool trace_contexts_p) { FACTOR_ASSERT(!gc_off); FACTOR_ASSERT(!current_gc); /* Important invariant: tenured space must have enough contiguous free space to fit the entire contents of the aging space and nursery. This is because when doing a full collection, objects from younger generations are promoted before any unreachable tenured objects are freed. */ FACTOR_ASSERT(!data->high_fragmentation_p()); current_gc = new gc_state(op, this); atomic::store(&current_gc_p, true); /* Keep trying to GC higher and higher generations until we don't run out of space in the target generation. */ for (;;) { try { if (gc_events) current_gc->event->op = current_gc->op; switch (current_gc->op) { case collect_nursery_op: collect_nursery(); break; case collect_aging_op: /* We end up here if the above fails. */ collect_aging(); if (data->high_fragmentation_p()) { /* Change GC op so that if we fail again, we crash. */ set_current_gc_op(collect_full_op); collect_full(trace_contexts_p); } break; case collect_to_tenured_op: /* We end up here if the above fails. */ collect_to_tenured(); if (data->high_fragmentation_p()) { /* Change GC op so that if we fail again, we crash. */ set_current_gc_op(collect_full_op); collect_full(trace_contexts_p); } break; case collect_full_op: collect_full(trace_contexts_p); break; case collect_compact_op: collect_compact(trace_contexts_p); break; case collect_growing_heap_op: collect_growing_heap(requested_size, trace_contexts_p); break; default: critical_error("in gc, bad GC op", current_gc->op); break; } break; } catch (const must_start_gc_again&) { /* We come back here if the target generation is full. */ start_gc_again(); continue; } } end_gc(); atomic::store(&current_gc_p, false); delete current_gc; current_gc = NULL; /* Check the invariant again, just in case. */ FACTOR_ASSERT(!data->high_fragmentation_p()); } void factor_vm::primitive_minor_gc() { gc(collect_nursery_op, 0, /* requested size */ true /* trace contexts? */); } void factor_vm::primitive_full_gc() { gc(collect_full_op, 0, /* requested size */ true /* trace contexts? */); } void factor_vm::primitive_compact_gc() { gc(collect_compact_op, 0, /* requested size */ true /* trace contexts? */); } /* * It is up to the caller to fill in the object's fields in a meaningful * fashion! */ /* Allocates memory */ object* factor_vm::allot_large_object(cell type, cell size) { /* If tenured space does not have enough room, collect and compact */ cell requested_size = size + data->high_water_mark(); if (!data->tenured->can_allot_p(requested_size)) { primitive_compact_gc(); /* If it still won't fit, grow the heap */ if (!data->tenured->can_allot_p(requested_size)) { gc(collect_growing_heap_op, size, /* requested size */ true /* trace contexts? */); } } object* obj = data->tenured->allot(size); /* Allows initialization code to store old->new pointers without hitting the write barrier in the common case of a nursery allocation */ write_barrier(obj, size); obj->initialize(type); return obj; } void factor_vm::primitive_enable_gc_events() { gc_events = new std::vector<gc_event>(); } /* Allocates memory (byte_array_from_value, result.add) */ /* XXX: Remember that growable_array has a data_root already */ void factor_vm::primitive_disable_gc_events() { if (gc_events) { growable_array result(this); std::vector<gc_event>* gc_events = this->gc_events; this->gc_events = NULL; std::vector<gc_event>::const_iterator iter = gc_events->begin(); std::vector<gc_event>::const_iterator end = gc_events->end(); for (; iter != end; iter++) { gc_event event = *iter; byte_array* obj = byte_array_from_value(&event); result.add(tag<byte_array>(obj)); } result.trim(); ctx->push(result.elements.value()); delete this->gc_events; } else ctx->push(false_object); } } <|endoftext|>
<commit_before>//===--- DefToYAMLConverterTest.cpp --------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #include "swift/Localization/LocalizationFormat.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/StringExtras.h" #include "llvm/ADT/StringRef.h" #include "llvm/Support/Path.h" #include "llvm/Support/YAMLParser.h" #include "llvm/Support/YAMLTraits.h" #include "llvm/Support/raw_ostream.h" #include "gtest/gtest.h" #include <random> #include <string> using namespace swift; using namespace swift::diag; enum LocalDiagID : uint32_t { #define DIAG(KIND, ID, Options, Text, Signature) ID, #include "swift/AST/DiagnosticsAll.def" NumDiags }; static constexpr const char *const diagnosticMessages[] = { #define DIAG(KIND, ID, Options, Text, Signature) Text, #include "swift/AST/DiagnosticsAll.def" }; static std::string getDefaultLocalizationPath() { std::string libPath = llvm::sys::path::parent_path(SWIFTLIB_DIR); llvm::SmallString<128> DefaultDiagnosticMessagesDir(libPath); llvm::sys::path::remove_filename(DefaultDiagnosticMessagesDir); // Remove /lib llvm::sys::path::remove_filename(DefaultDiagnosticMessagesDir); // Remove /. llvm::sys::path::append(DefaultDiagnosticMessagesDir, "share", "swift", "diagnostics"); return std::string(DefaultDiagnosticMessagesDir.str()); } /// Random number in [0,n) unsigned randNum(unsigned n) { return unsigned(rand()) % n; } TEST(DefToYAMLConverterTest, missingLocalizationFiles) { ASSERT_TRUE(llvm::sys::fs::exists(getDefaultLocalizationPath())); llvm::SmallString<128> EnglishLocalization(getDefaultLocalizationPath()); llvm::sys::path::append(EnglishLocalization, "en"); llvm::sys::path::replace_extension(EnglishLocalization, ".yaml"); ASSERT_TRUE(llvm::sys::fs::exists(EnglishLocalization)); llvm::sys::path::replace_extension(EnglishLocalization, ".db"); ASSERT_TRUE(llvm::sys::fs::exists(EnglishLocalization)); } TEST(DefToYAMLConverterTest, matchDiagnosticMessagesSequentially) { llvm::SmallString<128> EnglishLocalization(getDefaultLocalizationPath()); llvm::sys::path::append(EnglishLocalization, "en"); llvm::sys::path::replace_extension(EnglishLocalization, ".yaml"); YAMLLocalizationProducer yaml(EnglishLocalization.str()); yaml.forEachAvailable([](swift::DiagID id, llvm::StringRef translation) { llvm::StringRef msg = diagnosticMessages[static_cast<uint32_t>(id)]; ASSERT_EQ(msg, translation); }); } TEST(DefToYAMLConverterTest, matchDiagnosticMessagesRandomly) { llvm::SmallString<128> EnglishLocalization(getDefaultLocalizationPath()); llvm::sys::path::append(EnglishLocalization, "en"); llvm::sys::path::replace_extension(EnglishLocalization, ".yaml"); YAMLLocalizationProducer yaml(EnglishLocalization.str()); std::random_device rd; std::mt19937 gen(rd()); std::uniform_int_distribution<> distr(50, LocalDiagID::NumDiags); unsigned numberOfQueries = distr(gen); while (numberOfQueries--) { unsigned randomNum = randNum(LocalDiagID::NumDiags); DiagID randomId = static_cast<DiagID>(randomNum); llvm::StringRef msg = diagnosticMessages[randomNum]; llvm::StringRef translation = yaml.getMessageOr(randomId, ""); ASSERT_EQ(msg, translation); } } <commit_msg>[unittests] Make tests call the converter on temp files<commit_after>//===--- DefToYAMLConverterTest.cpp --------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #include "swift/Localization/LocalizationFormat.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/StringExtras.h" #include "llvm/ADT/StringRef.h" #include "llvm/Support/Path.h" #include "llvm/Support/Signals.h" #include "llvm/Support/ToolOutputFile.h" #include "llvm/Support/YAMLParser.h" #include "llvm/Support/YAMLTraits.h" #include "llvm/Support/raw_ostream.h" #include "gtest/gtest.h" #include <cstdlib> #include <random> #include <string> #include <system_error> using namespace swift; using namespace swift::diag; enum LocalDiagID : uint32_t { #define DIAG(KIND, ID, Options, Text, Signature) ID, #include "swift/AST/DiagnosticsAll.def" NumDiags }; static constexpr const char *const diagnosticMessages[] = { #define DIAG(KIND, ID, Options, Text, Signature) Text, #include "swift/AST/DiagnosticsAll.def" }; static std::string getMainExecutablePath() { std::string libPath = llvm::sys::path::parent_path(SWIFTLIB_DIR); llvm::SmallString<128> MainExecutablePath(libPath); llvm::sys::path::remove_filename(MainExecutablePath); // Remove /lib llvm::sys::path::remove_filename(MainExecutablePath); // Remove /. return std::string(MainExecutablePath.str()); } static std::string getDefaultLocalizationPath() { llvm::SmallString<128> DefaultDiagnosticMessagesDir(getMainExecutablePath()); llvm::sys::path::append(DefaultDiagnosticMessagesDir, "share", "swift", "diagnostics"); return std::string(DefaultDiagnosticMessagesDir.str()); } static std::string getDefToYAMLConverterPath() { llvm::SmallString<128> defYAMLConverter(getMainExecutablePath()); llvm::sys::path::append(defYAMLConverter, "bin", "swift-def-to-yaml-converter"); return std::string(defYAMLConverter.str()); } /// Random number in [0,n) unsigned randNum(unsigned n) { return unsigned(rand()) % n; } TEST(DefToYAMLConverterTest, missingLocalizationFiles) { ASSERT_TRUE(llvm::sys::fs::exists(getDefaultLocalizationPath())); llvm::SmallString<128> EnglishLocalization(getDefaultLocalizationPath()); llvm::sys::path::append(EnglishLocalization, "en"); llvm::sys::path::replace_extension(EnglishLocalization, ".yaml"); ASSERT_TRUE(llvm::sys::fs::exists(EnglishLocalization)); llvm::sys::path::replace_extension(EnglishLocalization, ".db"); ASSERT_TRUE(llvm::sys::fs::exists(EnglishLocalization)); } TEST(DefToYAMLConverterTest, matchDiagnosticMessagesSequentially) { llvm::SmallString<128> defYAMLConverter(getDefToYAMLConverterPath()); defYAMLConverter.append(" --output-filename="); llvm::SmallString<128> tempFilename; std::error_code EC = llvm::sys::fs::createTemporaryFile("en", "yaml", tempFilename); ASSERT_FALSE(EC); llvm::sys::RemoveFileOnSignal(tempFilename); defYAMLConverter.append(tempFilename); std::system(defYAMLConverter.c_str()); YAMLLocalizationProducer yaml(tempFilename.str()); yaml.forEachAvailable([](swift::DiagID id, llvm::StringRef translation) { llvm::StringRef msg = diagnosticMessages[static_cast<uint32_t>(id)]; ASSERT_EQ(msg, translation); }); } TEST(DefToYAMLConverterTest, matchDiagnosticMessagesRandomly) { llvm::SmallString<128> defYAMLConverter(getDefToYAMLConverterPath()); defYAMLConverter.append(" --output-filename="); llvm::SmallString<128> tempFilename; std::error_code EC = llvm::sys::fs::createTemporaryFile("en", "yaml", tempFilename); ASSERT_FALSE(EC); llvm::sys::RemoveFileOnSignal(tempFilename); defYAMLConverter.append(tempFilename); std::system(defYAMLConverter.c_str()); YAMLLocalizationProducer yaml(tempFilename.str()); std::random_device rd; std::mt19937 gen(rd()); std::uniform_int_distribution<> distr(50, LocalDiagID::NumDiags); unsigned numberOfQueries = distr(gen); while (numberOfQueries--) { unsigned randomNum = randNum(LocalDiagID::NumDiags); DiagID randomId = static_cast<DiagID>(randomNum); llvm::StringRef msg = diagnosticMessages[randomNum]; llvm::StringRef translation = yaml.getMessageOr(randomId, ""); ASSERT_EQ(msg, translation); } } <|endoftext|>
<commit_before>// test function for increment, bulk operations //Database functions #include <ktremotedb.h> using namespace std; using namespace kyototycoon; // main routine int main(int argc, char** argv) { // create the database object RemoteDB *rdb = new RemoteDB(); // open the database if (!rdb->open("kolossus-10.kilokluster.ucsc.edu", 1978, -1)) { cerr << "open error: " << rdb->error().name() << endl; } rdb->clear(); string value; // arbitrary expiration time int64_t xt = 50; // test integer increment function int64_t key = 1; size_t sizeOfKey = sizeof(int64_t); int initialValue = 123; int incrValue = 23; int64_t sizeOfRecord = sizeof(int); size_t sp; rdb->add((char *)&key, sizeOfKey, (const char *)&initialValue, sizeOfRecord); cerr << "add record error: " << rdb->error().name() << endl; rdb->increment((char *)&key, sizeOfKey, incrValue, xt); //450 (the existing record was not compatible). cerr << "increment error: " << rdb->error().name() << endl; char *afterIncr = rdb->get((char *)&key, sizeOfKey, &sp, NULL); printf("value after increment (should be 146): %d\n", *afterIncr); rdb->clear(); // the CPP version doesn't work either rdb->add("1", "123"); cerr << "add record error: " << rdb->error().name() << endl; rdb->increment("1", 23); //450 (the existing record was not compatible). cerr << "increment error: " << rdb->error().name() << endl; rdb->get("1", &value); cout << "key 1 incremented to (should be 146): " << value << endl; rdb->clear(); // test bulk set operation map<string,string> recs; recs.insert( pair<string,string>("5", "5") ); recs.insert( pair<string,string>("6", "10") ); recs.insert( pair<string,string>("7", "15") ); recs.insert( pair<string,string>("8", "20") ); int64_t retVal = rdb->set_bulk(recs, xt, true); cerr << "retval bulk set: " << retVal << endl; cerr << " bulk retval: " << rdb->error().name() << endl; // retrieve a record rdb->get("5", &value); cout << "key 5 set to (should be 5): " << value << endl; rdb->get("6", &value); cout << "key 6 set to (should be 10): " << value << endl; rdb->get("7", &value); cout << "key 7 set to (should be 15): " << value << endl; rdb->get("8", &value); cout << "key 8 set to (should be 20): " << value << endl; value = ""; vector<string> keys; keys.push_back("5"); keys.push_back("6"); keys.push_back("7"); keys.push_back("8"); retVal = rdb->remove_bulk(keys,true); cerr << " bulk records removed: " << retVal << endl; cerr << " bulk retval: " << rdb->error().name() << endl; rdb->get("7", &value); cout << "key 8 set to (should be zero): " << value << endl; rdb->clear(); if (!rdb->close()) { cerr << "close error: " << rdb->error().name() << endl; } return 0; } <commit_msg>-- per the email response from Fal Labs: " I suppose that the byte order of your machine is little endian. In that case, you have to switch the byte order of "initialValue". In order to normalize the byte order to big endian, the function "kyotocabinet::hton64" is useful. "<commit_after>// test function for increment, bulk operations //Database functions #include <ktremotedb.h> #include <kclangc.h> using namespace std; using namespace kyototycoon; // main routine int main(int argc, char** argv) { // create the database object RemoteDB *rdb = new RemoteDB(); // open the database if (!rdb->open("kolossus-10.kilokluster.ucsc.edu", 1978, -1)) { cerr << "open error: " << rdb->error().name() << endl; } rdb->clear(); string value; // arbitrary expiration time int64_t xt = 50; // test integer increment function uint64_t key = 7; size_t sizeOfKey = sizeof(uint64_t); uint64_t initialValue = 123; uint64_t incrValue = 23; uint64_t sizeOfRecord = sizeof(uint64_t); size_t sp; char *record; uint64_t currValue = 0; cout << "adding record " << initialValue << " of size " << sizeOfRecord << endl; // Normalize a 64-bit number in the native order into the network byte order. // little endian (our x86 linux machine) to big Endian.... uint64_t KCSafeIV = kyotocabinet::hton64(initialValue); rdb->add((char *)&key, sizeOfKey, (const char *)&KCSafeIV, sizeOfRecord); cerr << "add record error: " << rdb->error().name() << endl; record = rdb->get((char *)&key, sizeOfKey, &sp, NULL); currValue = kyotocabinet::ntoh64(*record); cout << "added record " << currValue << " of size " << sp << endl; KCSafeIV = kyotocabinet::hton64(incrValue); rdb->increment((char *)&key, sizeOfKey, KCSafeIV, xt); //450 (the existing record was not compatible). cerr << "increment error: " << rdb->error().name() << endl; record = rdb->get((char *)&key, sizeOfKey, &sp, NULL); // Denormalize a 64-bit number in the network byte order into the native order. // (big-endian to little endian) currValue = kyotocabinet::ntoh64(*record); printf("value after increment (should be 146): %d and size %d\n", currValue, sp); rdb->clear(); // the CPP version doesn't work either rdb->add("1", "123"); cerr << "add record error: " << rdb->error().name() << endl; rdb->increment("1", 23); //450 (the existing record was not compatible). cerr << "increment error: " << rdb->error().name() << endl; rdb->get("1", &value); cout << "key 1 incremented to (should be 146): " << value << endl; rdb->clear(); // test bulk set operation map<string,string> recs; recs.insert( pair<string,string>("5", "5") ); recs.insert( pair<string,string>("6", "10") ); recs.insert( pair<string,string>("7", "15") ); recs.insert( pair<string,string>("8", "20") ); int64_t retVal = rdb->set_bulk(recs, xt, true); cerr << "retval bulk set: " << retVal << endl; cerr << " bulk retval: " << rdb->error().name() << endl; // retrieve a record rdb->get("5", &value); cout << "key 5 set to (should be 5): " << value << endl; rdb->get("6", &value); cout << "key 6 set to (should be 10): " << value << endl; rdb->get("7", &value); cout << "key 7 set to (should be 15): " << value << endl; rdb->get("8", &value); cout << "key 8 set to (should be 20): " << value << endl; value = ""; vector<string> keys; keys.push_back("5"); keys.push_back("6"); keys.push_back("7"); keys.push_back("8"); retVal = rdb->remove_bulk(keys,true); cerr << " bulk records removed: " << retVal << endl; cerr << " bulk retval: " << rdb->error().name() << endl; rdb->get("7", &value); cout << "key 8 set to (should be zero): " << value << endl; rdb->clear(); if (!rdb->close()) { cerr << "close error: " << rdb->error().name() << endl; } return 0; } <|endoftext|>
<commit_before>/** @file * * @ingroup modularLibrary * * @brief TTBlue Class for caching common symbols for speed * * @details * * @authors Théo de la Hogue * * @copyright Copyright © 2010, Théo de la Hogue @n * This code is licensed under the terms of the "New BSD License" @n * http://creativecommons.org/licenses/BSD/ */ #include "TTModular.h" #include "TTValueCache.h" #include "TTSymbolTable.h" #include "TTModularSymbolCache.h" // object classe name TTMODULAR_EXPORT TTSymbol kTTSym_Application (("Application")); TTMODULAR_EXPORT TTSymbol kTTSym_ApplicationManager (("ApplicationManager")); TTMODULAR_EXPORT TTSymbol kTTSym_Container (("Container")); TTMODULAR_EXPORT TTSymbol kTTSym_Cue (("Cue")); TTMODULAR_EXPORT TTSymbol kTTSym_CueManager (("CueManager")); TTMODULAR_EXPORT TTSymbol kTTSym_Data (("Data")); TTMODULAR_EXPORT TTSymbol kTTSym_Explorer (("Explorer")); TTMODULAR_EXPORT TTSymbol kTTSym_Input (("Input")); TTMODULAR_EXPORT TTSymbol kTTSym_Mapper (("Mapper")); TTMODULAR_EXPORT TTSymbol kTTSym_MapperManager (("MapperManager")); TTMODULAR_EXPORT TTSymbol kTTSym_Mirror (("Mirror")); TTMODULAR_EXPORT TTSymbol kTTSym_OpmlHandler (("OpmlHandler")); TTMODULAR_EXPORT TTSymbol kTTSym_Output (("Output")); TTMODULAR_EXPORT TTSymbol kTTSym_Preset (("Preset")); TTMODULAR_EXPORT TTSymbol kTTSym_PresetManager (("PresetManager")); TTMODULAR_EXPORT TTSymbol kTTSym_Ramp (("Ramp")); TTMODULAR_EXPORT TTSymbol kTTSym_Receiver (("Receiver")); TTMODULAR_EXPORT TTSymbol kTTSym_Sender (("Sender")); TTMODULAR_EXPORT TTSymbol kTTSym_Script (("Script")); TTMODULAR_EXPORT TTSymbol kTTSym_Subscriber (("Subscriber")); TTMODULAR_EXPORT TTSymbol kTTSym_TextHandler (("TextHandler")); TTMODULAR_EXPORT TTSymbol kTTSym_Viewer (("Viewer")); TTMODULAR_EXPORT TTSymbol kTTSym_XmlHandler (("XmlHandler")); // attribute, message or any word often used TTMODULAR_EXPORT TTSymbol kTTSym_active (("active")); TTMODULAR_EXPORT TTSymbol kTTSym_activity (("activity")); TTMODULAR_EXPORT TTSymbol kTTSym_activityIn (("activityIn")); TTMODULAR_EXPORT TTSymbol kTTSym_activityOut (("activityOut")); TTMODULAR_EXPORT TTSymbol kTTSym_address (("address")); TTMODULAR_EXPORT TTSymbol kTTSym_addresses (("addresses")); TTMODULAR_EXPORT TTSymbol kTTSym_alias (("alias")); TTMODULAR_EXPORT TTSymbol kTTSym_alphabetic (("alphabetic")); TTMODULAR_EXPORT TTSymbol kTTSym_attributes (("attributes")); TTMODULAR_EXPORT TTSymbol kTTSym_array (("array")); TTMODULAR_EXPORT TTSymbol kTTSym_boolean (("boolean")); TTMODULAR_EXPORT TTSymbol kTTSym_brothers (("brothers")); TTMODULAR_EXPORT TTSymbol kTTSym_children (("children")); TTMODULAR_EXPORT TTSymbol kTTSym_command (("command")); TTMODULAR_EXPORT TTSymbol kTTSym_Command (("Command")); TTMODULAR_EXPORT TTSymbol kTTSym_comment (("comment")); TTMODULAR_EXPORT TTSymbol kTTSym_ConvertToAppName (("ConvertToAppName")); TTMODULAR_EXPORT TTSymbol kTTSym_ConvertToTTName (("ConvertToTTName")); TTMODULAR_EXPORT TTSymbol kTTSym_created (("created")); TTMODULAR_EXPORT TTSymbol kTTSym_dash (("-")); TTMODULAR_EXPORT TTSymbol kTTSym_dataspace (("dataspace")); TTMODULAR_EXPORT TTSymbol kTTSym_dataspaceUnit (("dataspaceUnit")); TTMODULAR_EXPORT TTSymbol kTTSym_debug (("debug")); TTMODULAR_EXPORT TTSymbol kTTSym_decimal (("decimal")); TTMODULAR_EXPORT TTSymbol kTTSym_descendants (("descendants")); TTMODULAR_EXPORT TTSymbol kTTSym_description (("description")); TTMODULAR_EXPORT TTSymbol kTTSym_destroyed (("destroyed")); TTMODULAR_EXPORT TTSymbol kTTSym_directory (("directory")); TTMODULAR_EXPORT TTSymbol kTTSym_Dump (("Dump")); TTMODULAR_EXPORT TTSymbol kTTSym_end (("end")); TTMODULAR_EXPORT TTSymbol kTTSym_external (("external")); TTMODULAR_EXPORT TTSymbol kTTSym_Fill (("Fill")); TTMODULAR_EXPORT TTSymbol kTTSym_filter (("filter")); TTMODULAR_EXPORT TTSymbol kTTSym_flag (("flag")); TTMODULAR_EXPORT TTSymbol kTTSym_Flatten (("Flatten")); TTMODULAR_EXPORT TTSymbol kTTSym_flattened (("flattened")); TTMODULAR_EXPORT TTSymbol kTTSym_freeze (("freeze")); TTMODULAR_EXPORT TTSymbol kTTSym_generic (("generic")); TTMODULAR_EXPORT TTSymbol kTTSym_Get (("Get")); TTMODULAR_EXPORT TTSymbol kTTSym_global (("global")); TTMODULAR_EXPORT TTSymbol kTTSym_highlight (("highlight")); TTMODULAR_EXPORT TTSymbol kTTSym_Init (("Init")); TTMODULAR_EXPORT TTSymbol kTTSym_initialized (("initialized")); TTMODULAR_EXPORT TTSymbol kTTSym_inputUnit (("inputUnit")); TTMODULAR_EXPORT TTSymbol kTTSym_instances (("instances")); TTMODULAR_EXPORT TTSymbol kTTSym_integer (("integer")); TTMODULAR_EXPORT TTSymbol kTTSym_life (("life")); TTMODULAR_EXPORT TTSymbol kTTSym_lookfor (("lookfor")); TTMODULAR_EXPORT TTSymbol kTTSym_Map (("Map")); TTMODULAR_EXPORT TTSymbol kTTSym_message (("message")); TTMODULAR_EXPORT TTSymbol kTTSym_mix (("mix")); TTMODULAR_EXPORT TTSymbol kTTSym_model (("model")); TTMODULAR_EXPORT TTSymbol kTTSym_mute (("mute")); TTMODULAR_EXPORT TTSymbol kTTSym_namespace (("namespace")); TTMODULAR_EXPORT TTSymbol kTTSym_nodeAddress (("nodeAddress")); TTMODULAR_EXPORT TTSymbol kTTSym_object (("object")); TTMODULAR_EXPORT TTSymbol kTTSym_objectCache (("objectCache")); TTMODULAR_EXPORT TTSymbol kTTSym_order (("order")); TTMODULAR_EXPORT TTSymbol kTTSym_parameter (("parameter")); TTMODULAR_EXPORT TTSymbol kTTSym_preview (("preview")); TTMODULAR_EXPORT TTSymbol kTTSym_priority (("priority")); TTMODULAR_EXPORT TTSymbol kTTSym_rangeBounds (("rangeBounds")); TTMODULAR_EXPORT TTSymbol kTTSym_rangeClipmode (("rangeClipmode")); TTMODULAR_EXPORT TTSymbol kTTSym_rampDrive (("rampDrive")); TTMODULAR_EXPORT TTSymbol kTTSym_rampFunction (("rampFunction")); TTMODULAR_EXPORT TTSymbol kTTSym_RampGo (("RampGo")); TTMODULAR_EXPORT TTSymbol kTTSym_RampSet (("RampSet")); TTMODULAR_EXPORT TTSymbol kTTSym_RampSlide (("RampSlide")); TTMODULAR_EXPORT TTSymbol kTTSym_rampStatus (("rampStatus")); TTMODULAR_EXPORT TTSymbol kTTSym_RampTarget (("RampTarget")); TTMODULAR_EXPORT TTSymbol kTTSym_Read (("Read")); TTMODULAR_EXPORT TTSymbol kTTSym_ReadAgain (("ReadAgain")); TTMODULAR_EXPORT TTSymbol kTTSym_readonly (("readonly")); TTMODULAR_EXPORT TTSymbol kTTSym_Recall (("Recall")); TTMODULAR_EXPORT TTSymbol kTTSym_receiver (("receiver")); TTMODULAR_EXPORT TTSymbol kTTSym_repetitionsAllow (("repetitionsAllow")); TTMODULAR_EXPORT TTSymbol kTTSym_Reset (("Reset")); TTMODULAR_EXPORT TTSymbol kTTSym_return (("return")); TTMODULAR_EXPORT TTSymbol kTTSym_returnedValue (("returnedValue")); TTMODULAR_EXPORT TTSymbol kTTSym_Run (("Run")); TTMODULAR_EXPORT TTSymbol kTTSym_Send (("Send")); TTMODULAR_EXPORT TTSymbol kTTSym_script (("script")); TTMODULAR_EXPORT TTSymbol kTTSym_service (("service")); TTMODULAR_EXPORT TTSymbol kTTSym_sharp (("#")); TTMODULAR_EXPORT TTSymbol kTTSym_signal (("signal")); TTMODULAR_EXPORT TTSymbol kTTSym_start (("start")); TTMODULAR_EXPORT TTSymbol kTTSym_stop (("stop")); TTMODULAR_EXPORT TTSymbol kTTSym_Subscribe (("Subscribe")); TTMODULAR_EXPORT TTSymbol kTTSym_tag (("tag")); TTMODULAR_EXPORT TTSymbol kTTSym_target (("target")); TTMODULAR_EXPORT TTSymbol kTTSym_unit (("unit")); TTMODULAR_EXPORT TTSymbol kTTSym_value (("value")); TTMODULAR_EXPORT TTSymbol kTTSym_valueDefault (("valueDefault")); TTMODULAR_EXPORT TTSymbol kTTSym_valueStepsize (("valueStepsize")); TTMODULAR_EXPORT TTSymbol kTTSym_viewFreeze (("viewFreeze")); TTMODULAR_EXPORT TTSymbol kTTSym_view (("view")); TTMODULAR_EXPORT TTSymbol kTTSym_Write (("Write")); TTMODULAR_EXPORT TTSymbol kTTSym_WriteAgain (("WriteAgain")); <commit_msg>Adding kTTSym_InputAudio and kTTSym_OutputAudio to the cache<commit_after>/** @file * * @ingroup modularLibrary * * @brief TTBlue Class for caching common symbols for speed * * @details * * @authors Théo de la Hogue * * @copyright Copyright © 2010, Théo de la Hogue @n * This code is licensed under the terms of the "New BSD License" @n * http://creativecommons.org/licenses/BSD/ */ #include "TTModular.h" #include "TTValueCache.h" #include "TTSymbolTable.h" #include "TTModularSymbolCache.h" // object classe name TTMODULAR_EXPORT TTSymbol kTTSym_Application (("Application")); TTMODULAR_EXPORT TTSymbol kTTSym_ApplicationManager (("ApplicationManager")); TTMODULAR_EXPORT TTSymbol kTTSym_Container (("Container")); TTMODULAR_EXPORT TTSymbol kTTSym_Cue (("Cue")); TTMODULAR_EXPORT TTSymbol kTTSym_CueManager (("CueManager")); TTMODULAR_EXPORT TTSymbol kTTSym_Data (("Data")); TTMODULAR_EXPORT TTSymbol kTTSym_Explorer (("Explorer")); TTMODULAR_EXPORT TTSymbol kTTSym_Input (("Input")); TTMODULAR_EXPORT TTSymbol kTTSym_InputAudio (("Input.audio")); TTMODULAR_EXPORT TTSymbol kTTSym_Mapper (("Mapper")); TTMODULAR_EXPORT TTSymbol kTTSym_MapperManager (("MapperManager")); TTMODULAR_EXPORT TTSymbol kTTSym_Mirror (("Mirror")); TTMODULAR_EXPORT TTSymbol kTTSym_OpmlHandler (("OpmlHandler")); TTMODULAR_EXPORT TTSymbol kTTSym_Output (("Output")); TTMODULAR_EXPORT TTSymbol kTTSym_OutputAudio (("Output.audio")); TTMODULAR_EXPORT TTSymbol kTTSym_Preset (("Preset")); TTMODULAR_EXPORT TTSymbol kTTSym_PresetManager (("PresetManager")); TTMODULAR_EXPORT TTSymbol kTTSym_Ramp (("Ramp")); TTMODULAR_EXPORT TTSymbol kTTSym_Receiver (("Receiver")); TTMODULAR_EXPORT TTSymbol kTTSym_Sender (("Sender")); TTMODULAR_EXPORT TTSymbol kTTSym_Script (("Script")); TTMODULAR_EXPORT TTSymbol kTTSym_Subscriber (("Subscriber")); TTMODULAR_EXPORT TTSymbol kTTSym_TextHandler (("TextHandler")); TTMODULAR_EXPORT TTSymbol kTTSym_Viewer (("Viewer")); TTMODULAR_EXPORT TTSymbol kTTSym_XmlHandler (("XmlHandler")); // attribute, message or any word often used TTMODULAR_EXPORT TTSymbol kTTSym_active (("active")); TTMODULAR_EXPORT TTSymbol kTTSym_activity (("activity")); TTMODULAR_EXPORT TTSymbol kTTSym_activityIn (("activityIn")); TTMODULAR_EXPORT TTSymbol kTTSym_activityOut (("activityOut")); TTMODULAR_EXPORT TTSymbol kTTSym_address (("address")); TTMODULAR_EXPORT TTSymbol kTTSym_addresses (("addresses")); TTMODULAR_EXPORT TTSymbol kTTSym_alias (("alias")); TTMODULAR_EXPORT TTSymbol kTTSym_alphabetic (("alphabetic")); TTMODULAR_EXPORT TTSymbol kTTSym_attributes (("attributes")); TTMODULAR_EXPORT TTSymbol kTTSym_array (("array")); TTMODULAR_EXPORT TTSymbol kTTSym_boolean (("boolean")); TTMODULAR_EXPORT TTSymbol kTTSym_brothers (("brothers")); TTMODULAR_EXPORT TTSymbol kTTSym_children (("children")); TTMODULAR_EXPORT TTSymbol kTTSym_command (("command")); TTMODULAR_EXPORT TTSymbol kTTSym_Command (("Command")); TTMODULAR_EXPORT TTSymbol kTTSym_comment (("comment")); TTMODULAR_EXPORT TTSymbol kTTSym_ConvertToAppName (("ConvertToAppName")); TTMODULAR_EXPORT TTSymbol kTTSym_ConvertToTTName (("ConvertToTTName")); TTMODULAR_EXPORT TTSymbol kTTSym_created (("created")); TTMODULAR_EXPORT TTSymbol kTTSym_dash (("-")); TTMODULAR_EXPORT TTSymbol kTTSym_dataspace (("dataspace")); TTMODULAR_EXPORT TTSymbol kTTSym_dataspaceUnit (("dataspaceUnit")); TTMODULAR_EXPORT TTSymbol kTTSym_debug (("debug")); TTMODULAR_EXPORT TTSymbol kTTSym_decimal (("decimal")); TTMODULAR_EXPORT TTSymbol kTTSym_descendants (("descendants")); TTMODULAR_EXPORT TTSymbol kTTSym_description (("description")); TTMODULAR_EXPORT TTSymbol kTTSym_destroyed (("destroyed")); TTMODULAR_EXPORT TTSymbol kTTSym_directory (("directory")); TTMODULAR_EXPORT TTSymbol kTTSym_Dump (("Dump")); TTMODULAR_EXPORT TTSymbol kTTSym_end (("end")); TTMODULAR_EXPORT TTSymbol kTTSym_external (("external")); TTMODULAR_EXPORT TTSymbol kTTSym_Fill (("Fill")); TTMODULAR_EXPORT TTSymbol kTTSym_filter (("filter")); TTMODULAR_EXPORT TTSymbol kTTSym_flag (("flag")); TTMODULAR_EXPORT TTSymbol kTTSym_Flatten (("Flatten")); TTMODULAR_EXPORT TTSymbol kTTSym_flattened (("flattened")); TTMODULAR_EXPORT TTSymbol kTTSym_freeze (("freeze")); TTMODULAR_EXPORT TTSymbol kTTSym_generic (("generic")); TTMODULAR_EXPORT TTSymbol kTTSym_Get (("Get")); TTMODULAR_EXPORT TTSymbol kTTSym_global (("global")); TTMODULAR_EXPORT TTSymbol kTTSym_highlight (("highlight")); TTMODULAR_EXPORT TTSymbol kTTSym_Init (("Init")); TTMODULAR_EXPORT TTSymbol kTTSym_initialized (("initialized")); TTMODULAR_EXPORT TTSymbol kTTSym_inputUnit (("inputUnit")); TTMODULAR_EXPORT TTSymbol kTTSym_instances (("instances")); TTMODULAR_EXPORT TTSymbol kTTSym_integer (("integer")); TTMODULAR_EXPORT TTSymbol kTTSym_life (("life")); TTMODULAR_EXPORT TTSymbol kTTSym_lookfor (("lookfor")); TTMODULAR_EXPORT TTSymbol kTTSym_Map (("Map")); TTMODULAR_EXPORT TTSymbol kTTSym_message (("message")); TTMODULAR_EXPORT TTSymbol kTTSym_mix (("mix")); TTMODULAR_EXPORT TTSymbol kTTSym_model (("model")); TTMODULAR_EXPORT TTSymbol kTTSym_mute (("mute")); TTMODULAR_EXPORT TTSymbol kTTSym_namespace (("namespace")); TTMODULAR_EXPORT TTSymbol kTTSym_nodeAddress (("nodeAddress")); TTMODULAR_EXPORT TTSymbol kTTSym_object (("object")); TTMODULAR_EXPORT TTSymbol kTTSym_objectCache (("objectCache")); TTMODULAR_EXPORT TTSymbol kTTSym_order (("order")); TTMODULAR_EXPORT TTSymbol kTTSym_parameter (("parameter")); TTMODULAR_EXPORT TTSymbol kTTSym_preview (("preview")); TTMODULAR_EXPORT TTSymbol kTTSym_priority (("priority")); TTMODULAR_EXPORT TTSymbol kTTSym_rangeBounds (("rangeBounds")); TTMODULAR_EXPORT TTSymbol kTTSym_rangeClipmode (("rangeClipmode")); TTMODULAR_EXPORT TTSymbol kTTSym_rampDrive (("rampDrive")); TTMODULAR_EXPORT TTSymbol kTTSym_rampFunction (("rampFunction")); TTMODULAR_EXPORT TTSymbol kTTSym_RampGo (("RampGo")); TTMODULAR_EXPORT TTSymbol kTTSym_RampSet (("RampSet")); TTMODULAR_EXPORT TTSymbol kTTSym_RampSlide (("RampSlide")); TTMODULAR_EXPORT TTSymbol kTTSym_rampStatus (("rampStatus")); TTMODULAR_EXPORT TTSymbol kTTSym_RampTarget (("RampTarget")); TTMODULAR_EXPORT TTSymbol kTTSym_Read (("Read")); TTMODULAR_EXPORT TTSymbol kTTSym_ReadAgain (("ReadAgain")); TTMODULAR_EXPORT TTSymbol kTTSym_readonly (("readonly")); TTMODULAR_EXPORT TTSymbol kTTSym_Recall (("Recall")); TTMODULAR_EXPORT TTSymbol kTTSym_receiver (("receiver")); TTMODULAR_EXPORT TTSymbol kTTSym_repetitionsAllow (("repetitionsAllow")); TTMODULAR_EXPORT TTSymbol kTTSym_Reset (("Reset")); TTMODULAR_EXPORT TTSymbol kTTSym_return (("return")); TTMODULAR_EXPORT TTSymbol kTTSym_returnedValue (("returnedValue")); TTMODULAR_EXPORT TTSymbol kTTSym_Run (("Run")); TTMODULAR_EXPORT TTSymbol kTTSym_Send (("Send")); TTMODULAR_EXPORT TTSymbol kTTSym_script (("script")); TTMODULAR_EXPORT TTSymbol kTTSym_service (("service")); TTMODULAR_EXPORT TTSymbol kTTSym_sharp (("#")); TTMODULAR_EXPORT TTSymbol kTTSym_signal (("signal")); TTMODULAR_EXPORT TTSymbol kTTSym_start (("start")); TTMODULAR_EXPORT TTSymbol kTTSym_stop (("stop")); TTMODULAR_EXPORT TTSymbol kTTSym_Subscribe (("Subscribe")); TTMODULAR_EXPORT TTSymbol kTTSym_tag (("tag")); TTMODULAR_EXPORT TTSymbol kTTSym_target (("target")); TTMODULAR_EXPORT TTSymbol kTTSym_unit (("unit")); TTMODULAR_EXPORT TTSymbol kTTSym_value (("value")); TTMODULAR_EXPORT TTSymbol kTTSym_valueDefault (("valueDefault")); TTMODULAR_EXPORT TTSymbol kTTSym_valueStepsize (("valueStepsize")); TTMODULAR_EXPORT TTSymbol kTTSym_viewFreeze (("viewFreeze")); TTMODULAR_EXPORT TTSymbol kTTSym_view (("view")); TTMODULAR_EXPORT TTSymbol kTTSym_Write (("Write")); TTMODULAR_EXPORT TTSymbol kTTSym_WriteAgain (("WriteAgain")); <|endoftext|>
<commit_before>#include "module_pressuresensor.h" #include "pressure_form.h" #include "module_uid.h" #define REGISTER_CALIB 00 // 8 bytes #define REGISTER_PRESSURE_RAW 8 #define REGISTER_TEMP_RAW 10 #define REGISTER_PRESSURE 12 #define REGISTER_TEMP 14 #define REGISTER_STATUS 17 // indicates problem between i2c-spi bridge and pressure sensor #define STATUS_MAGIC_VALUE 0x55 #define CALIB_MAGIC_VALUE 224 // pressure range. everything outside this range will be regarded as // a meassurement error #define PRESSURE_MIN 900 #define PRESSURE_MAX 3000 Module_PressureSensor::Module_PressureSensor(QString id, Module_UID *uid) : RobotModule(id) { this->uid=uid; setDefaultValue("i2cAddress", 0x50); setDefaultValue("frequency", 1); connect(&timer,SIGNAL(timeout()), this, SLOT(refreshData())); reset(); } Module_PressureSensor::~Module_PressureSensor() { } void Module_PressureSensor::terminate() { RobotModule::terminate(); timer.stop(); } void Module_PressureSensor::reset() { int freq = 1000/getSettings().value("frequency").toInt(); if (freq>0) timer.start(freq); else timer.stop(); } void Module_PressureSensor::refreshData() { if (!getSettings().value("enabled").toBool()) return; readPressure(); readTemperature(); if (getHealthStatus().isHealthOk()) { emit dataChanged(this); emit newDepthData(getDepth()); } } void Module_PressureSensor::readPressure() { unsigned char readBuffer[2]; if (!readRegister(REGISTER_PRESSURE, 2, readBuffer)) { setHealthToSick("UID reported error."); return; } // this is the pressure in mBar uint16_t pressure = (int)readBuffer[0] << 8 | (int)readBuffer[1]; data["pressure"] = pressure; // 100 mBar == ca. 1m wassersäule - druck an der luft data["depth"] = ((float)pressure-getSettings().value("airPressure").toFloat())/100; if (pressure < PRESSURE_MIN || pressure > PRESSURE_MAX) { setHealthToSick("Pressure of "+QString::number(pressure) + " doesn't make sense."); } } void Module_PressureSensor::readTemperature() { unsigned char readBuffer[2]; if (!readRegister(REGISTER_TEMP, 2, readBuffer)) { setHealthToSick("UID reported error."); return; } // this is the temperature in 10/degree celsius uint16_t temp = (int)readBuffer[0] << 8 | (int)readBuffer[1]; data["temperature"] = ((float)temp)/10; } float Module_PressureSensor::getDepth() { float p = data["pressure"].toFloat(); if (p > 900 && p <= 2000) { return data["depth"].toFloat(); } else { setHealthToSick("Pressure of "+QString::number(p) + " doesn't make sense."); return 0; } } float Module_PressureSensor::getTemperature() { return data["temperature"].toFloat(); } QList<RobotModule*> Module_PressureSensor::getDependencies() { QList<RobotModule*> ret; ret.append(uid); return ret; } QWidget* Module_PressureSensor::createView(QWidget* parent) { return new Pressure_Form(this, parent); } void Module_PressureSensor::doHealthCheck() { if (!getSettings().value("enabled").toBool()) return; unsigned char readBuffer[1]; if (!readRegister(REGISTER_STATUS, 1, readBuffer)) { setHealthToSick("UID reported error."); return; } if (readBuffer[0] != STATUS_MAGIC_VALUE) { setHealthToSick("Status register doesn't match magic value: is="+QString::number(readBuffer[0])); return; } setHealthToOk(); } bool Module_PressureSensor::readRegister2(unsigned char reg, int size, unsigned char *ret_buf) { unsigned char address = getSettings().value("i2cAddress").toInt(); if (!uid->getUID()->I2C_Write(address, &reg, 1)) { setHealthToSick("UID reported error."); return false; } if (!uid->getUID()->I2C_Read(address, size, ret_buf)) { setHealthToSick("UID reported error."); return false; } return true; } bool Module_PressureSensor::readRegister(unsigned char reg, int size, unsigned char *ret_buf) { unsigned char address = getSettings().value("i2cAddress").toInt(); if (!uid->getUID()->I2C_ReadRegisters(address, reg, size, ret_buf)) { setHealthToSick("UID reported error."); return false; } return true; } <commit_msg>read out counter register<commit_after>#include "module_pressuresensor.h" #include "pressure_form.h" #include "module_uid.h" #define REGISTER_CALIB 00 // 8 bytes #define REGISTER_PRESSURE_RAW 8 #define REGISTER_TEMP_RAW 10 #define REGISTER_PRESSURE 12 #define REGISTER_TEMP 14 #define REGISTER_STATUS 17 #define REGISTER_COUNTER 20 // indicates problem between i2c-spi bridge and pressure sensor #define STATUS_MAGIC_VALUE 0x55 #define CALIB_MAGIC_VALUE 224 // pressure range. everything outside this range will be regarded as // a meassurement error #define PRESSURE_MIN 900 #define PRESSURE_MAX 3000 Module_PressureSensor::Module_PressureSensor(QString id, Module_UID *uid) : RobotModule(id) { this->uid=uid; setDefaultValue("i2cAddress", 0x50); setDefaultValue("frequency", 1); connect(&timer,SIGNAL(timeout()), this, SLOT(refreshData())); reset(); } Module_PressureSensor::~Module_PressureSensor() { } void Module_PressureSensor::terminate() { RobotModule::terminate(); timer.stop(); } void Module_PressureSensor::reset() { int freq = 1000/getSettings().value("frequency").toInt(); if (freq>0) timer.start(freq); else timer.stop(); } void Module_PressureSensor::refreshData() { if (!getSettings().value("enabled").toBool()) return; readPressure(); readTemperature(); readCounter(); if (getHealthStatus().isHealthOk()) { emit dataChanged(this); emit newDepthData(getDepth()); } } void Module_PressureSensor::readPressure() { unsigned char readBuffer[2]; if (!readRegister(REGISTER_PRESSURE, 2, readBuffer)) { setHealthToSick("UID reported error."); return; } // this is the pressure in mBar uint16_t pressure = (int)readBuffer[0] << 8 | (int)readBuffer[1]; data["pressure"] = pressure; // 100 mBar == ca. 1m wassersäule - druck an der luft data["depth"] = ((float)pressure-getSettings().value("airPressure").toFloat())/100; if (pressure < PRESSURE_MIN || pressure > PRESSURE_MAX) { setHealthToSick("Pressure of "+QString::number(pressure) + " doesn't make sense."); } } void Module_PressureSensor::readCounter() { unsigned char readBuffer[1]; if (!readRegister(REGISTER_COUNTER, 1, readBuffer)) { setHealthToSick("UID reported error."); return; } data["counter"] = readBuffer[0]; } void Module_PressureSensor::readTemperature() { unsigned char readBuffer[2]; if (!readRegister(REGISTER_TEMP, 2, readBuffer)) { setHealthToSick("UID reported error."); return; } // this is the temperature in 10/degree celsius uint16_t temp = (int)readBuffer[0] << 8 | (int)readBuffer[1]; data["temperature"] = ((float)temp)/10; } float Module_PressureSensor::getDepth() { float p = data["pressure"].toFloat(); if (p > 900 && p <= 2000) { return data["depth"].toFloat(); } else { setHealthToSick("Pressure of "+QString::number(p) + " doesn't make sense."); return 0; } } float Module_PressureSensor::getTemperature() { return data["temperature"].toFloat(); } QList<RobotModule*> Module_PressureSensor::getDependencies() { QList<RobotModule*> ret; ret.append(uid); return ret; } QWidget* Module_PressureSensor::createView(QWidget* parent) { return new Pressure_Form(this, parent); } void Module_PressureSensor::doHealthCheck() { if (!getSettings().value("enabled").toBool()) return; unsigned char readBuffer[1]; if (!readRegister(REGISTER_STATUS, 1, readBuffer)) { setHealthToSick("UID reported error."); return; } if (readBuffer[0] != STATUS_MAGIC_VALUE) { setHealthToSick("Status register doesn't match magic value: is="+QString::number(readBuffer[0])); return; } setHealthToOk(); } bool Module_PressureSensor::readRegister2(unsigned char reg, int size, unsigned char *ret_buf) { unsigned char address = getSettings().value("i2cAddress").toInt(); if (!uid->getUID()->I2C_Write(address, &reg, 1)) { setHealthToSick("UID reported error."); return false; } if (!uid->getUID()->I2C_Read(address, size, ret_buf)) { setHealthToSick("UID reported error."); return false; } return true; } bool Module_PressureSensor::readRegister(unsigned char reg, int size, unsigned char *ret_buf) { unsigned char address = getSettings().value("i2cAddress").toInt(); if (!uid->getUID()->I2C_ReadRegisters(address, reg, size, ret_buf)) { setHealthToSick("UID reported error."); return false; } return true; } <|endoftext|>
<commit_before>/* * rtc-drv.cpp * * Copyright (c) 2017, 2018 Lix N. Paulian (lix@paulian.net) * * 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. * * Created on: 15 Apr 2017 (LNP) */ /* * This file implements the low level functions to control the RTC. */ #include <cmsis-plus/rtos/os.h> #include <cmsis-plus/diag/trace.h> #include "rtc-drv.h" using namespace os; /** * @brief Constructor. * @param hrtc: HAL hrtc handle. */ rtc::rtc (RTC_HandleTypeDef* hrtc) { trace::printf ("%s(%p) @%p\n", __func__, hrtc, this); hrtc_ = hrtc; } /** * @brief Control the power state of the RTC peripheral. * @param state: new state, either true (power on) or false (power off). * @return rtc::ok if successful, or a RTC error. */ rtc::rtc_result_t rtc::power (bool state) { rtc_result_t result = rtc::ok; RCC_OscInitTypeDef RCC_OscInitStruct; RCC_PeriphCLKInitTypeDef PeriphClkInitStruct; PeriphClkInitStruct.PeriphClockSelection = RCC_PERIPHCLK_RTC; PeriphClkInitStruct.RTCClockSelection = RCC_RTCCLKSOURCE_LSE; HAL_RCCEx_PeriphCLKConfig (&PeriphClkInitStruct); hrtc_->Instance = RTC; if (state == true) { // we do a "hard" initialization only if the INITS flag is not set; // with a backup battery the RTC keeps its initialization after a reset. if (HAL_IS_BIT_CLR(RTC->ISR, RTC_FLAG_INITS)) { RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_LSE | RCC_OSCILLATORTYPE_LSI; RCC_OscInitStruct.LSEState = RCC_LSE_ON; RCC_OscInitStruct.LSIState = RCC_LSI_OFF; RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE; HAL_RCC_OscConfig (&RCC_OscInitStruct); __HAL_RCC_RTC_ENABLE(); hrtc_->Init.HourFormat = RTC_HOURFORMAT_24; hrtc_->Init.AsynchPrediv = RTC_ASYNC_PREDIV; hrtc_->Init.SynchPrediv = RTC_SYNC_PREDIV; hrtc_->Init.OutPut = RTC_OUTPUT_DISABLE; hrtc_->Init.OutPutPolarity = RTC_OUTPUT_POLARITY_HIGH; hrtc_->Init.OutPutType = RTC_OUTPUT_TYPE_OPENDRAIN; result = (rtc_result_t) HAL_RTC_Init (hrtc_); } // set interrupt priority and enable alarm interrupt HAL_NVIC_SetPriority ((IRQn_Type) RTC_Alarm_IRQn, 13, 0); HAL_NVIC_EnableIRQ ((IRQn_Type) RTC_Alarm_IRQn); } else { result = (rtc_result_t) HAL_RTC_DeInit (hrtc_); HAL_NVIC_DisableIRQ ((IRQn_Type) RTC_Alarm_IRQn); __HAL_RCC_RTC_DISABLE(); } return result; } /** * @brief Set the RTC from a Unix time value; this is always UTC. * @param u_time: pointer on a time_t Unix time value. * @return rtc::ok if successful, or a RTC error. */ rtc::rtc_result_t rtc::set_time (time_t* u_time) { RTC_TimeTypeDef RTC_TimeStructure; RTC_DateTypeDef RTC_DateStructure; rtc::rtc_result_t result = busy; struct tm tms, *timeptr; timeptr = gmtime_r (u_time, &tms); RTC_TimeStructure.TimeFormat = RTC_HOURFORMAT_24; RTC_TimeStructure.DayLightSaving = RTC_DAYLIGHTSAVING_NONE; RTC_TimeStructure.StoreOperation = RTC_STOREOPERATION_SET; RTC_TimeStructure.SubSeconds = 0; RTC_TimeStructure.Seconds = timeptr->tm_sec; RTC_TimeStructure.Minutes = timeptr->tm_min; RTC_TimeStructure.Hours = timeptr->tm_hour; RTC_DateStructure.Date = timeptr->tm_mday; RTC_DateStructure.Month = timeptr->tm_mon + 1; RTC_DateStructure.Year = timeptr->tm_year - 100; RTC_DateStructure.WeekDay = timeptr->tm_wday + 1; if (mutex_.timed_lock (RTC_TIMEOUT) == rtos::result::ok) { result = (rtc_result_t) HAL_RTC_SetTime (hrtc_, &RTC_TimeStructure, FORMAT_BIN); if (result == ok) { result = (rtc_result_t) HAL_RTC_SetDate (hrtc_, &RTC_DateStructure, FORMAT_BIN); } mutex_.unlock (); } return result; } /** * @brief Return the current RTC value as Unix time; this is always UTC. * @param u_time: pointer on a time_t. * @return rtc::ok if successful, or a RTC error. */ rtc::rtc_result_t rtc::get_time (time_t* u_time) { RTC_TimeTypeDef RTC_TimeStructure; RTC_DateTypeDef RTC_DateStructure; rtc::rtc_result_t result = busy; struct tm timestruct, tmp; memset (&timestruct, 0, sizeof(struct tm)); if (mutex_.timed_lock (RTC_TIMEOUT) == rtos::result::ok) { result = (rtc_result_t) HAL_RTC_GetTime (hrtc_, &RTC_TimeStructure, FORMAT_BIN); if (result == ok) { result = (rtc_result_t) HAL_RTC_GetDate (hrtc_, &RTC_DateStructure, FORMAT_BIN); if (result == ok) { timestruct.tm_sec = RTC_TimeStructure.Seconds; timestruct.tm_min = RTC_TimeStructure.Minutes; timestruct.tm_hour = RTC_TimeStructure.Hours; timestruct.tm_mday = RTC_DateStructure.Date; timestruct.tm_mon = RTC_DateStructure.Month - 1; timestruct.tm_year = RTC_DateStructure.Year + 100; timestruct.tm_wday = RTC_DateStructure.WeekDay - 1; /* as we don't have the timegm () function, we do this trick * to compensate for the time zone offset: remember, we work * with the RTC only in UTC! */ *u_time = mktime (&timestruct); *u_time -= difftime (mktime (gmtime_r (u_time, &tmp)), mktime (localtime_r (u_time, &tmp))); } } mutex_.unlock (); } return result; } /** * @brief Set the calibration factor. * @param cal_factor: calibration factor (from -511 to +512). * @return rtc::ok if successful, or a RTC error. */ rtc::rtc_result_t rtc::set_cal_factor (int cal_factor) { uint32_t calib_minus_pulses_val; uint32_t calib_plus_pulses; rtc::rtc_result_t result = invalid_param; if (cal_factor >= -511 && cal_factor <= 512) { if (cal_factor > 0) { calib_minus_pulses_val = 512 - cal_factor; calib_plus_pulses = RTC_SMOOTHCALIB_PLUSPULSES_SET; } else { cal_factor *= -1; // transform to absolute value calib_minus_pulses_val = cal_factor; calib_plus_pulses = RTC_SMOOTHCALIB_PLUSPULSES_RESET; } result = (rtc_result_t) HAL_RTCEx_SetSmoothCalib ( hrtc_, // RTC_SMOOTHCALIB_PERIOD_32SEC, calib_plus_pulses, calib_minus_pulses_val); } return result; } /** * @brief Get the current calibration factor. * @return The current calibration factor (-511 to +512). */ int rtc::get_cal_factor (void) { int cal_factor; uint32_t rtc_calr = RTC->CALR; cal_factor = (rtc_calr & 0x8000) ? 512 : 0; cal_factor -= (rtc_calr & 0x1FF); return cal_factor; } /** * @brief Set an alarm. Note that alarm values must be specified in UTC! * Obviously, if the alarm definition includes only seconds and minutes, * then it makes no difference. * @param which: which alarm, for the STM32F7xxx there are two alarms, one of * rtc::alarm_a or rtc::alarm_b. * @param when: a struct tm containing the alarm's specification. * @return rtc::ok if successful, or a RTC error. */ rtc::rtc_result_t rtc::set_alarm (int which, struct tm* when) { RTC_AlarmTypeDef alarm; rtc::rtc_result_t result; result = (rtc_result_t) HAL_RTC_DeactivateAlarm (hrtc_, which); if (result == ok) { alarm.AlarmMask = 0; if (when->tm_wday < 0 && when->tm_mday < 0) { // no weekday, no month-day specified, therefore mask the day alarm.AlarmMask |= RTC_ALARMMASK_DATEWEEKDAY; alarm.AlarmDateWeekDaySel = RTC_ALARMDATEWEEKDAYSEL_DATE; alarm.AlarmDateWeekDay = 1; // still need a valid day here } else { if (when->tm_mday > 0) { // day of month specified alarm.AlarmDateWeekDay = (uint8_t) when->tm_mday; alarm.AlarmDateWeekDaySel = RTC_ALARMDATEWEEKDAYSEL_DATE; } else { // day of week specified alarm.AlarmDateWeekDay = (uint8_t) when->tm_wday; alarm.AlarmDateWeekDaySel = RTC_ALARMDATEWEEKDAYSEL_WEEKDAY; } } if (when->tm_hour < 0) { // no hours specified, so we mask the hours alarm.AlarmMask |= RTC_ALARMMASK_HOURS; alarm.AlarmTime.Hours = 0; } else { alarm.AlarmTime.Hours = (uint8_t) when->tm_hour; } if (when->tm_min < 0) { // no minutes specified, so we mask the minutes alarm.AlarmMask |= RTC_ALARMMASK_MINUTES; alarm.AlarmTime.Minutes = 0; } else { alarm.AlarmTime.Minutes = when->tm_min; } if (when->tm_sec < 0) { // no seconds specified, so we mask the seconds alarm.AlarmMask |= RTC_ALARMMASK_SECONDS; alarm.AlarmTime.Seconds = 0; } else { alarm.AlarmTime.Seconds = when->tm_sec; } // initialize the rest alarm.Alarm = which; alarm.AlarmSubSecondMask = RTC_ALARMSUBSECONDMASK_NONE; alarm.AlarmTime.DayLightSaving = RTC_DAYLIGHTSAVING_NONE; alarm.AlarmTime.TimeFormat = RTC_HOURFORMAT12_AM; alarm.AlarmTime.SubSeconds = 0; alarm.AlarmTime.SecondFraction = 0; alarm.AlarmTime.StoreOperation = RTC_STOREOPERATION_RESET; result = (rtc_result_t) HAL_RTC_SetAlarm_IT (hrtc_, &alarm, FORMAT_BIN); } return result; } /** * @brief Get the current values of an alarm. * @param which: which alarm, rtc::alarm_a or rtc::alarm_b. * @param when: pointer to a struct tm returning the current alarm values. * @return rtc::ok if successful, or a RTC error. */ rtc::rtc_result_t rtc::get_alarm (int which, struct tm* when) { RTC_AlarmTypeDef alarm; rtc::rtc_result_t result; result = (rtc_result_t) HAL_RTC_GetAlarm (hrtc_, &alarm, which, FORMAT_BIN); if (result == rtc::ok) { when->tm_wday = (alarm.AlarmMask & RTC_ALARMMASK_DATEWEEKDAY) ? alarm.AlarmDateWeekDay : alarm_ignored; when->tm_mday = (alarm.AlarmMask & RTC_ALARMDATEWEEKDAYSEL_DATE) ? alarm.AlarmDateWeekDay : alarm_ignored; when->tm_hour = (alarm.AlarmMask & RTC_ALARMMASK_HOURS) ? alarm.AlarmTime.Hours : alarm_ignored; when->tm_min = (alarm.AlarmMask & RTC_ALARMMASK_MINUTES) ? alarm.AlarmTime.Minutes : alarm_ignored; when->tm_sec = (alarm.AlarmMask |= RTC_ALARMMASK_SECONDS) ? alarm.AlarmTime.Seconds : alarm_ignored; } return result; } /** * @brief Read a backup register. * @param reg_nr: the number of the register to read (0 to 31). * @return Value read out of the specified register. */ uint32_t rtc::get_bk_register (uint8_t reg_nr) { return HAL_RTCEx_BKUPRead(hrtc_, reg_nr); } /** * @brief Write a backup register. * @param reg_nr: the number of the register to write (0 to 31). * @param value: Value to be written in the specified register. */ void rtc::set_bk_register (uint8_t reg_nr, uint32_t value) { HAL_RTCEx_BKUPWrite (hrtc_, reg_nr, value); } <commit_msg>Mask subseconds, as they should not be taken into account for alarms.<commit_after>/* * rtc-drv.cpp * * Copyright (c) 2017, 2018 Lix N. Paulian (lix@paulian.net) * * 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. * * Created on: 15 Apr 2017 (LNP) */ /* * This file implements the low level functions to control the RTC. */ #include <cmsis-plus/rtos/os.h> #include <cmsis-plus/diag/trace.h> #include "rtc-drv.h" using namespace os; /** * @brief Constructor. * @param hrtc: HAL hrtc handle. */ rtc::rtc (RTC_HandleTypeDef* hrtc) { trace::printf ("%s(%p) @%p\n", __func__, hrtc, this); hrtc_ = hrtc; } /** * @brief Control the power state of the RTC peripheral. * @param state: new state, either true (power on) or false (power off). * @return rtc::ok if successful, or a RTC error. */ rtc::rtc_result_t rtc::power (bool state) { rtc_result_t result = rtc::ok; RCC_OscInitTypeDef RCC_OscInitStruct; RCC_PeriphCLKInitTypeDef PeriphClkInitStruct; PeriphClkInitStruct.PeriphClockSelection = RCC_PERIPHCLK_RTC; PeriphClkInitStruct.RTCClockSelection = RCC_RTCCLKSOURCE_LSE; HAL_RCCEx_PeriphCLKConfig (&PeriphClkInitStruct); hrtc_->Instance = RTC; if (state == true) { // we do a "hard" initialization only if the INITS flag is not set; // with a backup battery the RTC keeps its initialization after a reset. if (HAL_IS_BIT_CLR(RTC->ISR, RTC_FLAG_INITS)) { RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_LSE | RCC_OSCILLATORTYPE_LSI; RCC_OscInitStruct.LSEState = RCC_LSE_ON; RCC_OscInitStruct.LSIState = RCC_LSI_OFF; RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE; HAL_RCC_OscConfig (&RCC_OscInitStruct); __HAL_RCC_RTC_ENABLE(); hrtc_->Init.HourFormat = RTC_HOURFORMAT_24; hrtc_->Init.AsynchPrediv = RTC_ASYNC_PREDIV; hrtc_->Init.SynchPrediv = RTC_SYNC_PREDIV; hrtc_->Init.OutPut = RTC_OUTPUT_DISABLE; hrtc_->Init.OutPutPolarity = RTC_OUTPUT_POLARITY_HIGH; hrtc_->Init.OutPutType = RTC_OUTPUT_TYPE_OPENDRAIN; result = (rtc_result_t) HAL_RTC_Init (hrtc_); } // set interrupt priority and enable alarm interrupt HAL_NVIC_SetPriority ((IRQn_Type) RTC_Alarm_IRQn, 13, 0); HAL_NVIC_EnableIRQ ((IRQn_Type) RTC_Alarm_IRQn); } else { result = (rtc_result_t) HAL_RTC_DeInit (hrtc_); HAL_NVIC_DisableIRQ ((IRQn_Type) RTC_Alarm_IRQn); __HAL_RCC_RTC_DISABLE(); } return result; } /** * @brief Set the RTC from a Unix time value; this is always UTC. * @param u_time: pointer on a time_t Unix time value. * @return rtc::ok if successful, or a RTC error. */ rtc::rtc_result_t rtc::set_time (time_t* u_time) { RTC_TimeTypeDef RTC_TimeStructure; RTC_DateTypeDef RTC_DateStructure; rtc::rtc_result_t result = busy; struct tm tms, *timeptr; timeptr = gmtime_r (u_time, &tms); RTC_TimeStructure.TimeFormat = RTC_HOURFORMAT_24; RTC_TimeStructure.DayLightSaving = RTC_DAYLIGHTSAVING_NONE; RTC_TimeStructure.StoreOperation = RTC_STOREOPERATION_SET; RTC_TimeStructure.SubSeconds = 0; RTC_TimeStructure.Seconds = timeptr->tm_sec; RTC_TimeStructure.Minutes = timeptr->tm_min; RTC_TimeStructure.Hours = timeptr->tm_hour; RTC_DateStructure.Date = timeptr->tm_mday; RTC_DateStructure.Month = timeptr->tm_mon + 1; RTC_DateStructure.Year = timeptr->tm_year - 100; RTC_DateStructure.WeekDay = timeptr->tm_wday + 1; if (mutex_.timed_lock (RTC_TIMEOUT) == rtos::result::ok) { result = (rtc_result_t) HAL_RTC_SetTime (hrtc_, &RTC_TimeStructure, FORMAT_BIN); if (result == ok) { result = (rtc_result_t) HAL_RTC_SetDate (hrtc_, &RTC_DateStructure, FORMAT_BIN); } mutex_.unlock (); } return result; } /** * @brief Return the current RTC value as Unix time; this is always UTC. * @param u_time: pointer on a time_t. * @return rtc::ok if successful, or a RTC error. */ rtc::rtc_result_t rtc::get_time (time_t* u_time) { RTC_TimeTypeDef RTC_TimeStructure; RTC_DateTypeDef RTC_DateStructure; rtc::rtc_result_t result = busy; struct tm timestruct, tmp; memset (&timestruct, 0, sizeof(struct tm)); if (mutex_.timed_lock (RTC_TIMEOUT) == rtos::result::ok) { result = (rtc_result_t) HAL_RTC_GetTime (hrtc_, &RTC_TimeStructure, FORMAT_BIN); if (result == ok) { result = (rtc_result_t) HAL_RTC_GetDate (hrtc_, &RTC_DateStructure, FORMAT_BIN); if (result == ok) { timestruct.tm_sec = RTC_TimeStructure.Seconds; timestruct.tm_min = RTC_TimeStructure.Minutes; timestruct.tm_hour = RTC_TimeStructure.Hours; timestruct.tm_mday = RTC_DateStructure.Date; timestruct.tm_mon = RTC_DateStructure.Month - 1; timestruct.tm_year = RTC_DateStructure.Year + 100; timestruct.tm_wday = RTC_DateStructure.WeekDay - 1; /* as we don't have the timegm () function, we do this trick * to compensate for the time zone offset: remember, we work * with the RTC only in UTC! */ *u_time = mktime (&timestruct); *u_time -= difftime (mktime (gmtime_r (u_time, &tmp)), mktime (localtime_r (u_time, &tmp))); } } mutex_.unlock (); } return result; } /** * @brief Set the calibration factor. * @param cal_factor: calibration factor (from -511 to +512). * @return rtc::ok if successful, or a RTC error. */ rtc::rtc_result_t rtc::set_cal_factor (int cal_factor) { uint32_t calib_minus_pulses_val; uint32_t calib_plus_pulses; rtc::rtc_result_t result = invalid_param; if (cal_factor >= -511 && cal_factor <= 512) { if (cal_factor > 0) { calib_minus_pulses_val = 512 - cal_factor; calib_plus_pulses = RTC_SMOOTHCALIB_PLUSPULSES_SET; } else { cal_factor *= -1; // transform to absolute value calib_minus_pulses_val = cal_factor; calib_plus_pulses = RTC_SMOOTHCALIB_PLUSPULSES_RESET; } result = (rtc_result_t) HAL_RTCEx_SetSmoothCalib ( hrtc_, // RTC_SMOOTHCALIB_PERIOD_32SEC, calib_plus_pulses, calib_minus_pulses_val); } return result; } /** * @brief Get the current calibration factor. * @return The current calibration factor (-511 to +512). */ int rtc::get_cal_factor (void) { int cal_factor; uint32_t rtc_calr = RTC->CALR; cal_factor = (rtc_calr & 0x8000) ? 512 : 0; cal_factor -= (rtc_calr & 0x1FF); return cal_factor; } /** * @brief Set an alarm. Note that alarm values must be specified in UTC! * Obviously, if the alarm definition includes only seconds and minutes, * then it makes no difference. * @param which: which alarm, for the STM32F7xxx there are two alarms, one of * rtc::alarm_a or rtc::alarm_b. * @param when: a struct tm containing the alarm's specification. * @return rtc::ok if successful, or a RTC error. */ rtc::rtc_result_t rtc::set_alarm (int which, struct tm* when) { RTC_AlarmTypeDef alarm; rtc::rtc_result_t result; result = (rtc_result_t) HAL_RTC_DeactivateAlarm (hrtc_, which); if (result == ok) { alarm.AlarmMask = 0; if (when->tm_wday < 0 && when->tm_mday < 0) { // no weekday, no month-day specified, therefore mask the day alarm.AlarmMask |= RTC_ALARMMASK_DATEWEEKDAY; alarm.AlarmDateWeekDaySel = RTC_ALARMDATEWEEKDAYSEL_DATE; alarm.AlarmDateWeekDay = 1; // still need a valid day here } else { if (when->tm_mday > 0) { // day of month specified alarm.AlarmDateWeekDay = (uint8_t) when->tm_mday; alarm.AlarmDateWeekDaySel = RTC_ALARMDATEWEEKDAYSEL_DATE; } else { // day of week specified alarm.AlarmDateWeekDay = (uint8_t) when->tm_wday; alarm.AlarmDateWeekDaySel = RTC_ALARMDATEWEEKDAYSEL_WEEKDAY; } } if (when->tm_hour < 0) { // no hours specified, so we mask the hours alarm.AlarmMask |= RTC_ALARMMASK_HOURS; alarm.AlarmTime.Hours = 0; } else { alarm.AlarmTime.Hours = (uint8_t) when->tm_hour; } if (when->tm_min < 0) { // no minutes specified, so we mask the minutes alarm.AlarmMask |= RTC_ALARMMASK_MINUTES; alarm.AlarmTime.Minutes = 0; } else { alarm.AlarmTime.Minutes = when->tm_min; } if (when->tm_sec < 0) { // no seconds specified, so we mask the seconds alarm.AlarmMask |= RTC_ALARMMASK_SECONDS; alarm.AlarmTime.Seconds = 0; } else { alarm.AlarmTime.Seconds = when->tm_sec; } // initialize the rest alarm.Alarm = which; alarm.AlarmSubSecondMask = RTC_ALARMSUBSECONDMASK_ALL; alarm.AlarmTime.DayLightSaving = RTC_DAYLIGHTSAVING_NONE; alarm.AlarmTime.TimeFormat = RTC_HOURFORMAT12_AM; alarm.AlarmTime.SubSeconds = 0; alarm.AlarmTime.SecondFraction = 0; alarm.AlarmTime.StoreOperation = RTC_STOREOPERATION_RESET; result = (rtc_result_t) HAL_RTC_SetAlarm_IT (hrtc_, &alarm, FORMAT_BIN); } return result; } /** * @brief Get the current values of an alarm. * @param which: which alarm, rtc::alarm_a or rtc::alarm_b. * @param when: pointer to a struct tm returning the current alarm values. * @return rtc::ok if successful, or a RTC error. */ rtc::rtc_result_t rtc::get_alarm (int which, struct tm* when) { RTC_AlarmTypeDef alarm; rtc::rtc_result_t result; result = (rtc_result_t) HAL_RTC_GetAlarm (hrtc_, &alarm, which, FORMAT_BIN); if (result == rtc::ok) { when->tm_wday = (alarm.AlarmMask & RTC_ALARMMASK_DATEWEEKDAY) ? alarm.AlarmDateWeekDay : alarm_ignored; when->tm_mday = (alarm.AlarmMask & RTC_ALARMDATEWEEKDAYSEL_DATE) ? alarm.AlarmDateWeekDay : alarm_ignored; when->tm_hour = (alarm.AlarmMask & RTC_ALARMMASK_HOURS) ? alarm.AlarmTime.Hours : alarm_ignored; when->tm_min = (alarm.AlarmMask & RTC_ALARMMASK_MINUTES) ? alarm.AlarmTime.Minutes : alarm_ignored; when->tm_sec = (alarm.AlarmMask |= RTC_ALARMMASK_SECONDS) ? alarm.AlarmTime.Seconds : alarm_ignored; } return result; } /** * @brief Read a backup register. * @param reg_nr: the number of the register to read (0 to 31). * @return Value read out of the specified register. */ uint32_t rtc::get_bk_register (uint8_t reg_nr) { return HAL_RTCEx_BKUPRead(hrtc_, reg_nr); } /** * @brief Write a backup register. * @param reg_nr: the number of the register to write (0 to 31). * @param value: Value to be written in the specified register. */ void rtc::set_bk_register (uint8_t reg_nr, uint32_t value) { HAL_RTCEx_BKUPWrite (hrtc_, reg_nr, value); } <|endoftext|>
<commit_before>// Copyright (c) 2013 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 "ui/message_center/views/message_popup_collection.h" #include <set> #include "base/bind.h" #include "base/timer.h" #include "ui/gfx/screen.h" #include "ui/message_center/message_center_constants.h" #include "ui/message_center/notification.h" #include "ui/message_center/notification_list.h" #include "ui/message_center/views/message_view.h" #include "ui/message_center/views/notification_view.h" #include "ui/views/background.h" #include "ui/views/layout/fill_layout.h" #include "ui/views/view.h" #include "ui/views/widget/widget.h" namespace message_center { class ToastContentsView : public views::WidgetDelegateView { public: ToastContentsView(const Notification* notification, MessageView* view, MessagePopupCollection* collection) : collection_(collection) { DCHECK(collection_); set_notify_enter_exit_on_child(true); SetLayoutManager(new views::FillLayout()); // Sets the transparent background. Then, when the message view is slid out, // the whole toast seems to slide although the actual bound of the widget // remains. This is hacky but easier to keep the consistency. set_background(views::Background::CreateSolidBackground(0, 0, 0, 0)); AddChildView(view); int seconds = kAutocloseDefaultDelaySeconds; if (notification->priority() > DEFAULT_PRIORITY) seconds = kAutocloseHighPriorityDelaySeconds; delay_ = base::TimeDelta::FromSeconds(seconds); } views::Widget* CreateWidget(gfx::NativeView context) { views::Widget::InitParams params( views::Widget::InitParams::TYPE_WINDOW_FRAMELESS); params.keep_on_top = true; params.context = context; params.transparent = true; // The origin of the initial bounds are set to (0, 0). It'll then moved by // MessagePopupCollection. params.bounds = gfx::Rect( gfx::Size(kWebNotificationWidth, GetPreferredSize().height())); params.delegate = this; views::Widget* widget = new views::Widget(); widget->Init(params); return widget; } void SuspendTimer() { timer_.Reset(); } void RestartTimer() { base::TimeDelta passed = base::Time::Now() - start_time_; if (passed > delay_) { GetWidget()->Close(); } else { delay_ -= passed; StartTimer(); } } void StartTimer() { start_time_ = base::Time::Now(); timer_.Start(FROM_HERE, delay_, base::Bind(&views::Widget::Close, base::Unretained(GetWidget()))); } // views::WidgetDelegate overrides: virtual views::View* GetContentsView() OVERRIDE { return this; } virtual void WindowClosing() OVERRIDE { if (timer_.IsRunning()) SuspendTimer(); } virtual bool CanActivate() const OVERRIDE { return false; } // views::View overrides: virtual void OnMouseEntered(const ui::MouseEvent& event) OVERRIDE { collection_->OnMouseEntered(); } virtual void OnMouseExited(const ui::MouseEvent& event) OVERRIDE { collection_->OnMouseExited(); } private: base::TimeDelta delay_; base::Time start_time_; base::OneShotTimer<views::Widget> timer_; MessagePopupCollection* collection_; DISALLOW_COPY_AND_ASSIGN(ToastContentsView); }; MessagePopupCollection::MessagePopupCollection( gfx::NativeView context, NotificationList::Delegate* list_delegate) : context_(context), list_delegate_(list_delegate) { DCHECK(list_delegate_); } MessagePopupCollection::~MessagePopupCollection() { CloseAllWidgets(); } void MessagePopupCollection::UpdatePopups() { NotificationList::PopupNotifications popups = list_delegate_->GetNotificationList()->GetPopupNotifications(); if (popups.empty()) { CloseAllWidgets(); return; } gfx::Screen* screen = gfx::Screen::GetScreenFor(context_); gfx::Rect work_area = screen->GetDisplayNearestWindow(context_).work_area(); std::set<std::string> old_toast_ids; for (ToastContainer::iterator iter = toasts_.begin(); iter != toasts_.end(); ++iter) { old_toast_ids.insert(iter->first); } int total_height = 0; std::vector<views::Widget*> widgets; for (NotificationList::PopupNotifications::const_iterator iter = popups.begin(); iter != popups.end(); ++iter) { ToastContainer::iterator toast_iter = toasts_.find((*iter)->id()); views::Widget* widget = NULL; if (toast_iter != toasts_.end()) { widget = toast_iter->second->GetWidget(); old_toast_ids.erase((*iter)->id()); } else { MessageView* view = NotificationView::Create(*(*iter), list_delegate_); ToastContentsView* toast = new ToastContentsView(*iter, view, this); widget = toast->CreateWidget(context_); widget->AddObserver(this); toast->StartTimer(); toasts_[(*iter)->id()] = toast; } if (widget) { gfx::Rect bounds = widget->GetWindowBoundsInScreen(); int new_height = total_height + bounds.height() + kMarginBetweenItems; if (new_height < work_area.height()) { total_height = new_height; widgets.push_back(widget); } else { if (toast_iter != toasts_.end()) toasts_.erase(toast_iter); delete widget; break; } } } for (std::set<std::string>::const_iterator iter = old_toast_ids.begin(); iter != old_toast_ids.end(); ++iter) { ToastContainer::iterator toast_iter = toasts_.find(*iter); DCHECK(toast_iter != toasts_.end()); views::Widget* widget = toast_iter->second->GetWidget(); widget->RemoveObserver(this); widget->Close(); toasts_.erase(toast_iter); } // Place/move the toast widgets. Currently it stacks the widgets from the // right-bottom of the work area. // TODO(mukai): allow to specify the placement policy from outside of this // class. The policy should be specified from preference on Windows, or // the launcher alignment on ChromeOS. int top = work_area.bottom() - total_height; int left = work_area.right() - kWebNotificationWidth - kMarginBetweenItems; for (size_t i = 0; i < widgets.size(); ++i) { gfx::Rect widget_bounds = widgets[i]->GetWindowBoundsInScreen(); widgets[i]->SetBounds(gfx::Rect( left, top, widget_bounds.width(), widget_bounds.height())); if (!widgets[i]->IsVisible()) widgets[i]->Show(); top += widget_bounds.height() + kMarginBetweenItems; } } void MessagePopupCollection::OnMouseEntered() { for (ToastContainer::iterator iter = toasts_.begin(); iter != toasts_.end(); ++iter) { iter->second->SuspendTimer(); } } void MessagePopupCollection::OnMouseExited() { for (ToastContainer::iterator iter = toasts_.begin(); iter != toasts_.end(); ++iter) { iter->second->RestartTimer(); } } void MessagePopupCollection::CloseAllWidgets() { for (ToastContainer::iterator iter = toasts_.begin(); iter != toasts_.end(); ++iter) { iter->second->SuspendTimer(); views::Widget* widget = iter->second->GetWidget(); widget->RemoveObserver(this); widget->Close(); } toasts_.clear(); } void MessagePopupCollection::OnWidgetDestroying(views::Widget* widget) { widget->RemoveObserver(this); for (ToastContainer::iterator iter = toasts_.begin(); iter != toasts_.end(); ++iter) { if (iter->second->GetWidget() == widget) { list_delegate_->GetNotificationList()->MarkSinglePopupAsShown( iter->first, false); toasts_.erase(iter); break; } } UpdatePopups(); } } // namespace message_center <commit_msg>Do not reuse the old NotificationView in PopupCollection.<commit_after>// Copyright (c) 2013 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 "ui/message_center/views/message_popup_collection.h" #include <set> #include "base/bind.h" #include "base/timer.h" #include "ui/gfx/screen.h" #include "ui/message_center/message_center_constants.h" #include "ui/message_center/notification.h" #include "ui/message_center/notification_list.h" #include "ui/message_center/views/message_view.h" #include "ui/message_center/views/notification_view.h" #include "ui/views/background.h" #include "ui/views/layout/fill_layout.h" #include "ui/views/view.h" #include "ui/views/widget/widget.h" namespace message_center { class ToastContentsView : public views::WidgetDelegateView { public: ToastContentsView(const Notification* notification, MessagePopupCollection* collection) : collection_(collection) { DCHECK(collection_); set_notify_enter_exit_on_child(true); SetLayoutManager(new views::FillLayout()); // Sets the transparent background. Then, when the message view is slid out, // the whole toast seems to slide although the actual bound of the widget // remains. This is hacky but easier to keep the consistency. set_background(views::Background::CreateSolidBackground(0, 0, 0, 0)); int seconds = kAutocloseDefaultDelaySeconds; if (notification->priority() > DEFAULT_PRIORITY) seconds = kAutocloseHighPriorityDelaySeconds; delay_ = base::TimeDelta::FromSeconds(seconds); } views::Widget* CreateWidget(gfx::NativeView context) { views::Widget::InitParams params( views::Widget::InitParams::TYPE_WINDOW_FRAMELESS); params.keep_on_top = true; params.context = context; params.transparent = true; // The origin of the initial bounds are set to (0, 0). It'll then moved by // MessagePopupCollection. params.bounds = gfx::Rect( gfx::Size(kWebNotificationWidth, GetPreferredSize().height())); params.delegate = this; views::Widget* widget = new views::Widget(); widget->Init(params); return widget; } void SetContents(MessageView* view) { RemoveAllChildViews(true); AddChildView(view); Layout(); } void SuspendTimer() { timer_.Reset(); } void RestartTimer() { base::TimeDelta passed = base::Time::Now() - start_time_; if (passed > delay_) { GetWidget()->Close(); } else { delay_ -= passed; StartTimer(); } } void StartTimer() { start_time_ = base::Time::Now(); timer_.Start(FROM_HERE, delay_, base::Bind(&views::Widget::Close, base::Unretained(GetWidget()))); } // views::WidgetDelegate overrides: virtual views::View* GetContentsView() OVERRIDE { return this; } virtual void WindowClosing() OVERRIDE { if (timer_.IsRunning()) SuspendTimer(); } virtual bool CanActivate() const OVERRIDE { return false; } // views::View overrides: virtual void OnMouseEntered(const ui::MouseEvent& event) OVERRIDE { collection_->OnMouseEntered(); } virtual void OnMouseExited(const ui::MouseEvent& event) OVERRIDE { collection_->OnMouseExited(); } private: base::TimeDelta delay_; base::Time start_time_; base::OneShotTimer<views::Widget> timer_; MessagePopupCollection* collection_; DISALLOW_COPY_AND_ASSIGN(ToastContentsView); }; MessagePopupCollection::MessagePopupCollection( gfx::NativeView context, NotificationList::Delegate* list_delegate) : context_(context), list_delegate_(list_delegate) { DCHECK(list_delegate_); } MessagePopupCollection::~MessagePopupCollection() { CloseAllWidgets(); } void MessagePopupCollection::UpdatePopups() { NotificationList::PopupNotifications popups = list_delegate_->GetNotificationList()->GetPopupNotifications(); if (popups.empty()) { CloseAllWidgets(); return; } gfx::Screen* screen = gfx::Screen::GetScreenFor(context_); gfx::Rect work_area = screen->GetDisplayNearestWindow(context_).work_area(); std::set<std::string> old_toast_ids; for (ToastContainer::iterator iter = toasts_.begin(); iter != toasts_.end(); ++iter) { old_toast_ids.insert(iter->first); } int total_height = 0; std::vector<views::Widget*> widgets; for (NotificationList::PopupNotifications::const_iterator iter = popups.begin(); iter != popups.end(); ++iter) { ToastContainer::iterator toast_iter = toasts_.find((*iter)->id()); views::Widget* widget = NULL; MessageView* view = NotificationView::Create(*(*iter), list_delegate_); if (toast_iter != toasts_.end()) { widget = toast_iter->second->GetWidget(); old_toast_ids.erase((*iter)->id()); // Need to replace the contents because |view| can be updated, like // image loads. toast_iter->second->SetContents(view); } else { ToastContentsView* toast = new ToastContentsView(*iter, this); toast->SetContents(view); widget = toast->CreateWidget(context_); widget->AddObserver(this); toast->StartTimer(); toasts_[(*iter)->id()] = toast; } if (widget) { gfx::Rect bounds = widget->GetWindowBoundsInScreen(); int new_height = total_height + bounds.height() + kMarginBetweenItems; if (new_height < work_area.height()) { total_height = new_height; widgets.push_back(widget); } else { if (toast_iter != toasts_.end()) toasts_.erase(toast_iter); delete widget; break; } } } for (std::set<std::string>::const_iterator iter = old_toast_ids.begin(); iter != old_toast_ids.end(); ++iter) { ToastContainer::iterator toast_iter = toasts_.find(*iter); DCHECK(toast_iter != toasts_.end()); views::Widget* widget = toast_iter->second->GetWidget(); widget->RemoveObserver(this); widget->Close(); toasts_.erase(toast_iter); } // Place/move the toast widgets. Currently it stacks the widgets from the // right-bottom of the work area. // TODO(mukai): allow to specify the placement policy from outside of this // class. The policy should be specified from preference on Windows, or // the launcher alignment on ChromeOS. int top = work_area.bottom() - total_height; int left = work_area.right() - kWebNotificationWidth - kMarginBetweenItems; for (size_t i = 0; i < widgets.size(); ++i) { gfx::Rect widget_bounds = widgets[i]->GetWindowBoundsInScreen(); widgets[i]->SetBounds(gfx::Rect( left, top, widget_bounds.width(), widget_bounds.height())); if (!widgets[i]->IsVisible()) widgets[i]->Show(); top += widget_bounds.height() + kMarginBetweenItems; } } void MessagePopupCollection::OnMouseEntered() { for (ToastContainer::iterator iter = toasts_.begin(); iter != toasts_.end(); ++iter) { iter->second->SuspendTimer(); } } void MessagePopupCollection::OnMouseExited() { for (ToastContainer::iterator iter = toasts_.begin(); iter != toasts_.end(); ++iter) { iter->second->RestartTimer(); } } void MessagePopupCollection::CloseAllWidgets() { for (ToastContainer::iterator iter = toasts_.begin(); iter != toasts_.end(); ++iter) { iter->second->SuspendTimer(); views::Widget* widget = iter->second->GetWidget(); widget->RemoveObserver(this); widget->Close(); } toasts_.clear(); } void MessagePopupCollection::OnWidgetDestroying(views::Widget* widget) { widget->RemoveObserver(this); for (ToastContainer::iterator iter = toasts_.begin(); iter != toasts_.end(); ++iter) { if (iter->second->GetWidget() == widget) { list_delegate_->GetNotificationList()->MarkSinglePopupAsShown( iter->first, false); toasts_.erase(iter); break; } } UpdatePopups(); } } // namespace message_center <|endoftext|>
<commit_before>/* * MPITestLayer.cpp * * Created on: Sep 27, 2011 * Author: gkenyon */ #include "MPITestLayer.hpp" #include "../PetaVision/src/utils/conversions.h" namespace PV { MPITestLayer::MPITestLayer(const char * name, HyPerCol * hc, int numChannels) : ANNLayer(name, hc, numChannels) { initialize(); } MPITestLayer::MPITestLayer(const char * name, HyPerCol * hc) : ANNLayer(name, hc, MAX_CHANNELS) { initialize(); } // set V to global x/y/f position int MPITestLayer::setVtoGlobalPos(){ for (int kLocal = 0; kLocal < clayer->numNeurons; kLocal++){ int kGlobal = globalIndexFromLocal(kLocal, clayer->loc); int kxGlobal = kxPos(kGlobal, clayer->loc.nxGlobal, clayer->loc.nyGlobal, clayer->loc.nf); float xScaleLog2 = clayer->xScale; float x0 = xOriginGlobal(xScaleLog2); float dx = deltaX(xScaleLog2); float x_global_pos = (x0 + dx * kxGlobal); clayer->V[kLocal] = x_global_pos; } return PV_SUCCESS; } // set activity to global x/y/f position, using position in border/margin as required int MPITestLayer::setActivitytoGlobalPos(){ for (int kLocalExt = 0; kLocalExt < clayer->numExtended; kLocalExt++){ int kxLocalExt = kxPos(kLocalExt, clayer->loc.nx + 2*clayer->loc.nb, clayer->loc.ny + 2*clayer->loc.nb, clayer->loc.nf) - clayer->loc.nb; int kxGlobalExt = kxLocalExt + clayer->loc.kx0; float xScaleLog2 = clayer->xScale; float x0 = xOriginGlobal(xScaleLog2); float dx = deltaX(xScaleLog2); float x_global_pos = (x0 + dx * kxGlobalExt); clayer->activity->data[kLocalExt] = x_global_pos; } return PV_SUCCESS; } int MPITestLayer::initialize(){ //int status = ANNLayer::initialize(); // parent class inialize already called in constructor (!!!violation of PV convention) setVtoGlobalPos(); setActivitytoGlobalPos(); return PV_SUCCESS; } int MPITestLayer::updateState(float time, float dt) { //updateV(); //setActivity(); //resetGSynBuffers(); //updateActiveIndices(); return PV_SUCCESS; } int MPITestLayer::publish(InterColComm* comm, float time) { setActivitytoGlobalPos(); int status = comm->publish(this, clayer->activity); return status; //return HyPerLayer::publish(comm, time); } } /* namespace PV */ <commit_msg>Change MPITestLayer so that only external borders, not borders between processes, are initialized. The internal borders should be filled by MPI routines.<commit_after>/* * MPITestLayer.cpp * * Created on: Sep 27, 2011 * Author: gkenyon */ #include "MPITestLayer.hpp" #include "../PetaVision/src/utils/conversions.h" namespace PV { MPITestLayer::MPITestLayer(const char * name, HyPerCol * hc, int numChannels) : ANNLayer(name, hc, numChannels) { initialize(); } MPITestLayer::MPITestLayer(const char * name, HyPerCol * hc) : ANNLayer(name, hc, MAX_CHANNELS) { initialize(); } // set V to global x/y/f position int MPITestLayer::setVtoGlobalPos(){ for (int kLocal = 0; kLocal < clayer->numNeurons; kLocal++){ int kGlobal = globalIndexFromLocal(kLocal, clayer->loc); int kxGlobal = kxPos(kGlobal, clayer->loc.nxGlobal, clayer->loc.nyGlobal, clayer->loc.nf); float xScaleLog2 = clayer->xScale; float x0 = xOriginGlobal(xScaleLog2); float dx = deltaX(xScaleLog2); float x_global_pos = (x0 + dx * kxGlobal); clayer->V[kLocal] = x_global_pos; } return PV_SUCCESS; } // set activity to global x/y/f position, using position in border/margin as required int MPITestLayer::setActivitytoGlobalPos(){ for (int kLocalExt = 0; kLocalExt < clayer->numExtended; kLocalExt++){ int kxLocalExt = kxPos(kLocalExt, clayer->loc.nx + 2*clayer->loc.nb, clayer->loc.ny + 2*clayer->loc.nb, clayer->loc.nf) - clayer->loc.nb; int kxGlobalExt = kxLocalExt + clayer->loc.kx0; float xScaleLog2 = clayer->xScale; float x0 = xOriginGlobal(xScaleLog2); float dx = deltaX(xScaleLog2); float x_global_pos = (x0 + dx * kxGlobalExt); if( x_global_pos < 0 || x_global_pos > clayer->loc.nxGlobal || (x_global_pos > clayer->loc.kx0 && x_global_pos < clayer->loc.kx0 + clayer->loc.nx) ) { clayer->activity->data[kLocalExt] = x_global_pos; } } return PV_SUCCESS; } int MPITestLayer::initialize(){ //int status = ANNLayer::initialize(); // parent class initialize already called in constructor (!!!violation of PV convention) setVtoGlobalPos(); setActivitytoGlobalPos(); return PV_SUCCESS; } int MPITestLayer::updateState(float time, float dt) { //updateV(); //setActivity(); //resetGSynBuffers(); //updateActiveIndices(); return PV_SUCCESS; } int MPITestLayer::publish(InterColComm* comm, float time) { setActivitytoGlobalPos(); int status = comm->publish(this, clayer->activity); return status; //return HyPerLayer::publish(comm, time); } } /* namespace PV */ <|endoftext|>
<commit_before>// Copyright (c) 2012 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 "sandbox/win/src/service_resolver.h" #include "base/memory/scoped_ptr.h" #include "sandbox/win/src/sandbox_nt_util.h" #include "sandbox/win/src/win_utils.h" namespace { #pragma pack(push, 1) const ULONG kMmovR10EcxMovEax = 0xB8D18B4C; const USHORT kSyscall = 0x050F; const BYTE kRetNp = 0xC3; const ULONG64 kMov1 = 0x54894808244C8948; const ULONG64 kMov2 = 0x4C182444894C1024; const ULONG kMov3 = 0x20244C89; // Service code for 64 bit systems. struct ServiceEntry { // This struct contains roughly the following code: // 00 mov r10,rcx // 03 mov eax,52h // 08 syscall // 0a ret // 0b xchg ax,ax // 0e xchg ax,ax ULONG mov_r10_rcx_mov_eax; // = 4C 8B D1 B8 ULONG service_id; USHORT syscall; // = 0F 05 BYTE ret; // = C3 BYTE pad; // = 66 USHORT xchg_ax_ax1; // = 66 90 USHORT xchg_ax_ax2; // = 66 90 }; // Service code for 64 bit Windows 8. struct ServiceEntryW8 { // This struct contains the following code: // 00 48894c2408 mov [rsp+8], rcx // 05 4889542410 mov [rsp+10], rdx // 0a 4c89442418 mov [rsp+18], r8 // 0f 4c894c2420 mov [rsp+20], r9 // 14 4c8bd1 mov r10,rcx // 17 b825000000 mov eax,25h // 1c 0f05 syscall // 1e c3 ret // 1f 90 nop ULONG64 mov_1; // = 48 89 4C 24 08 48 89 54 ULONG64 mov_2; // = 24 10 4C 89 44 24 18 4C ULONG mov_3; // = 89 4C 24 20 ULONG mov_r10_rcx_mov_eax; // = 4C 8B D1 B8 ULONG service_id; USHORT syscall; // = 0F 05 BYTE ret; // = C3 BYTE nop; // = 90 }; // We don't have an internal thunk for x64. struct ServiceFullThunk { union { ServiceEntry original; ServiceEntryW8 original_w8; }; }; #pragma pack(pop) bool IsService(const void* source) { const ServiceEntry* service = reinterpret_cast<const ServiceEntry*>(source); return (kMmovR10EcxMovEax == service->mov_r10_rcx_mov_eax && kSyscall == service->syscall && kRetNp == service->ret); } }; // namespace namespace sandbox { NTSTATUS ServiceResolverThunk::Setup(const void* target_module, const void* interceptor_module, const char* target_name, const char* interceptor_name, const void* interceptor_entry_point, void* thunk_storage, size_t storage_bytes, size_t* storage_used) { NTSTATUS ret = Init(target_module, interceptor_module, target_name, interceptor_name, interceptor_entry_point, thunk_storage, storage_bytes); if (!NT_SUCCESS(ret)) return ret; size_t thunk_bytes = GetThunkSize(); scoped_ptr<char[]> thunk_buffer(new char[thunk_bytes]); ServiceFullThunk* thunk = reinterpret_cast<ServiceFullThunk*>( thunk_buffer.get()); if (!IsFunctionAService(&thunk->original)) return STATUS_UNSUCCESSFUL; ret = PerformPatch(thunk, thunk_storage); if (NULL != storage_used) *storage_used = thunk_bytes; return ret; } size_t ServiceResolverThunk::GetThunkSize() const { return sizeof(ServiceFullThunk); } NTSTATUS ServiceResolverThunk::CopyThunk(const void* target_module, const char* target_name, BYTE* thunk_storage, size_t storage_bytes, size_t* storage_used) { NTSTATUS ret = ResolveTarget(target_module, target_name, &target_); if (!NT_SUCCESS(ret)) return ret; size_t thunk_bytes = GetThunkSize(); if (storage_bytes < thunk_bytes) return STATUS_UNSUCCESSFUL; ServiceFullThunk* thunk = reinterpret_cast<ServiceFullThunk*>(thunk_storage); if (!IsFunctionAService(&thunk->original)) return STATUS_UNSUCCESSFUL; if (NULL != storage_used) *storage_used = thunk_bytes; return ret; } bool ServiceResolverThunk::IsFunctionAService(void* local_thunk) const { ServiceFullThunk function_code; SIZE_T read; if (!::ReadProcessMemory(process_, target_, &function_code, sizeof(function_code), &read)) return false; if (sizeof(function_code) != read) return false; if (!IsService(&function_code)) { // See if it's the Win8 signature. ServiceEntryW8* w8_service = &function_code.original_w8; if (!IsService(&w8_service->mov_r10_rcx_mov_eax) || w8_service->mov_1 != kMov1 || w8_service->mov_1 != kMov1 || w8_service->mov_1 != kMov1) { return false; } } // Save the verified code. memcpy(local_thunk, &function_code, sizeof(function_code)); return true; } NTSTATUS ServiceResolverThunk::PerformPatch(void* local_thunk, void* remote_thunk) { // Patch the original code. ServiceEntry local_service; DCHECK_NT(GetInternalThunkSize() >= sizeof(local_service)); if (!SetInternalThunk(&local_service, sizeof(local_service), NULL, interceptor_)) return STATUS_UNSUCCESSFUL; // Copy the local thunk buffer to the child. SIZE_T actual; if (!::WriteProcessMemory(process_, remote_thunk, local_thunk, sizeof(ServiceFullThunk), &actual)) return STATUS_UNSUCCESSFUL; if (sizeof(ServiceFullThunk) != actual) return STATUS_UNSUCCESSFUL; // And now change the function to intercept, on the child. if (NULL != ntdll_base_) { // Running a unit test. if (!::WriteProcessMemory(process_, target_, &local_service, sizeof(local_service), &actual)) return STATUS_UNSUCCESSFUL; } else { if (!WriteProtectedChildMemory(process_, target_, &local_service, sizeof(local_service))) return STATUS_UNSUCCESSFUL; } return STATUS_SUCCESS; } bool Wow64ResolverThunk::IsFunctionAService(void* local_thunk) const { NOTREACHED_NT(); return false; } } // namespace sandbox <commit_msg>service_resolver_64: Correctly check all the bytes of the service code.<commit_after>// Copyright (c) 2012 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 "sandbox/win/src/service_resolver.h" #include "base/memory/scoped_ptr.h" #include "sandbox/win/src/sandbox_nt_util.h" #include "sandbox/win/src/win_utils.h" namespace { #pragma pack(push, 1) const ULONG kMmovR10EcxMovEax = 0xB8D18B4C; const USHORT kSyscall = 0x050F; const BYTE kRetNp = 0xC3; const ULONG64 kMov1 = 0x54894808244C8948; const ULONG64 kMov2 = 0x4C182444894C1024; const ULONG kMov3 = 0x20244C89; // Service code for 64 bit systems. struct ServiceEntry { // This struct contains roughly the following code: // 00 mov r10,rcx // 03 mov eax,52h // 08 syscall // 0a ret // 0b xchg ax,ax // 0e xchg ax,ax ULONG mov_r10_rcx_mov_eax; // = 4C 8B D1 B8 ULONG service_id; USHORT syscall; // = 0F 05 BYTE ret; // = C3 BYTE pad; // = 66 USHORT xchg_ax_ax1; // = 66 90 USHORT xchg_ax_ax2; // = 66 90 }; // Service code for 64 bit Windows 8. struct ServiceEntryW8 { // This struct contains the following code: // 00 48894c2408 mov [rsp+8], rcx // 05 4889542410 mov [rsp+10], rdx // 0a 4c89442418 mov [rsp+18], r8 // 0f 4c894c2420 mov [rsp+20], r9 // 14 4c8bd1 mov r10,rcx // 17 b825000000 mov eax,25h // 1c 0f05 syscall // 1e c3 ret // 1f 90 nop ULONG64 mov_1; // = 48 89 4C 24 08 48 89 54 ULONG64 mov_2; // = 24 10 4C 89 44 24 18 4C ULONG mov_3; // = 89 4C 24 20 ULONG mov_r10_rcx_mov_eax; // = 4C 8B D1 B8 ULONG service_id; USHORT syscall; // = 0F 05 BYTE ret; // = C3 BYTE nop; // = 90 }; // We don't have an internal thunk for x64. struct ServiceFullThunk { union { ServiceEntry original; ServiceEntryW8 original_w8; }; }; #pragma pack(pop) bool IsService(const void* source) { const ServiceEntry* service = reinterpret_cast<const ServiceEntry*>(source); return (kMmovR10EcxMovEax == service->mov_r10_rcx_mov_eax && kSyscall == service->syscall && kRetNp == service->ret); } }; // namespace namespace sandbox { NTSTATUS ServiceResolverThunk::Setup(const void* target_module, const void* interceptor_module, const char* target_name, const char* interceptor_name, const void* interceptor_entry_point, void* thunk_storage, size_t storage_bytes, size_t* storage_used) { NTSTATUS ret = Init(target_module, interceptor_module, target_name, interceptor_name, interceptor_entry_point, thunk_storage, storage_bytes); if (!NT_SUCCESS(ret)) return ret; size_t thunk_bytes = GetThunkSize(); scoped_ptr<char[]> thunk_buffer(new char[thunk_bytes]); ServiceFullThunk* thunk = reinterpret_cast<ServiceFullThunk*>( thunk_buffer.get()); if (!IsFunctionAService(&thunk->original)) return STATUS_UNSUCCESSFUL; ret = PerformPatch(thunk, thunk_storage); if (NULL != storage_used) *storage_used = thunk_bytes; return ret; } size_t ServiceResolverThunk::GetThunkSize() const { return sizeof(ServiceFullThunk); } NTSTATUS ServiceResolverThunk::CopyThunk(const void* target_module, const char* target_name, BYTE* thunk_storage, size_t storage_bytes, size_t* storage_used) { NTSTATUS ret = ResolveTarget(target_module, target_name, &target_); if (!NT_SUCCESS(ret)) return ret; size_t thunk_bytes = GetThunkSize(); if (storage_bytes < thunk_bytes) return STATUS_UNSUCCESSFUL; ServiceFullThunk* thunk = reinterpret_cast<ServiceFullThunk*>(thunk_storage); if (!IsFunctionAService(&thunk->original)) return STATUS_UNSUCCESSFUL; if (NULL != storage_used) *storage_used = thunk_bytes; return ret; } bool ServiceResolverThunk::IsFunctionAService(void* local_thunk) const { ServiceFullThunk function_code; SIZE_T read; if (!::ReadProcessMemory(process_, target_, &function_code, sizeof(function_code), &read)) return false; if (sizeof(function_code) != read) return false; if (!IsService(&function_code)) { // See if it's the Win8 signature. ServiceEntryW8* w8_service = &function_code.original_w8; if (!IsService(&w8_service->mov_r10_rcx_mov_eax) || w8_service->mov_1 != kMov1 || w8_service->mov_2 != kMov2 || w8_service->mov_3 != kMov3) { return false; } } // Save the verified code. memcpy(local_thunk, &function_code, sizeof(function_code)); return true; } NTSTATUS ServiceResolverThunk::PerformPatch(void* local_thunk, void* remote_thunk) { // Patch the original code. ServiceEntry local_service; DCHECK_NT(GetInternalThunkSize() >= sizeof(local_service)); if (!SetInternalThunk(&local_service, sizeof(local_service), NULL, interceptor_)) return STATUS_UNSUCCESSFUL; // Copy the local thunk buffer to the child. SIZE_T actual; if (!::WriteProcessMemory(process_, remote_thunk, local_thunk, sizeof(ServiceFullThunk), &actual)) return STATUS_UNSUCCESSFUL; if (sizeof(ServiceFullThunk) != actual) return STATUS_UNSUCCESSFUL; // And now change the function to intercept, on the child. if (NULL != ntdll_base_) { // Running a unit test. if (!::WriteProcessMemory(process_, target_, &local_service, sizeof(local_service), &actual)) return STATUS_UNSUCCESSFUL; } else { if (!WriteProtectedChildMemory(process_, target_, &local_service, sizeof(local_service))) return STATUS_UNSUCCESSFUL; } return STATUS_SUCCESS; } bool Wow64ResolverThunk::IsFunctionAService(void* local_thunk) const { NOTREACHED_NT(); return false; } } // namespace sandbox <|endoftext|>
<commit_before>#include <ostream> #include <vector> #include <string> #include <algorithm> #include <iterator> #include "sevensegment.h" namespace sevensegment { const static std::vector< std::vector<std::string> > digits { { " - ", "| |", " ", "| |", " - " }, // 0 { " ", " |", " ", " |", " " }, // 1 { " - ", " |", " - ", "| ", " - " }, // 2 { " - ", " |", " - ", " |", " - " }, // 3 { " ", "| |", " - ", " |", " " }, // 4 { " - ", "| ", " - ", " |", " - " }, // 5 { " - ", "| ", " - ", "| |", " - " }, // 6 { " - ", " |", " ", " |", " " }, // 7 { " - ", "| |", " - ", "| |", " - " }, // 8 { " - ", "| |", " - ", " |", " - " } // 9 }; const static std::vector<std::string> minus_sign { " ", " ", " - ", " ", " " }; // - const static std::vector< std::vector<std::string> > error { { " - ", "| ", " - ", "| ", " - " }, // E { " ", " ", " - ", "| ", " " }, // r { " ", " ", " - ", "| ", " " }, // r { " ", " ", " - ", "| |", " - " }, // o { " ", " ", " - ", "| ", " " }, // r }; std::string stretchLine(const std::string &line, unsigned n) { std::string stretched_line(n+2, line[1]); stretched_line.front() = line[0]; stretched_line.back() = line[2]; return stretched_line; } void printLargeDigit(unsigned i, std::ostream &out, unsigned n) { auto digit = digits.at(i); std::ostream_iterator<std::string> out_it(out, "\n"); auto second_line = stretchLine(digit[1], n); auto fourth_line = stretchLine(digit[3], n); out << stretchLine(digit[0], n) << '\n'; std::generate_n(out_it, n, [&](){return second_line;}); out << stretchLine(digit[2], n) << '\n'; std::generate_n(out_it, n, [&](){return fourth_line;}); out << stretchLine(digit[4], n) << '\n'; } std::vector< std::vector<std::string> > split_digits(int i, std::vector< std::vector<std::string> > &vector) { if(i >= 10) split_digits(i / 10, vector); vector.push_back(digits.at(i % 10)); return vector; } std::vector< std::vector<std::string> > split_digits(int i) { std::vector< std::vector<std::string> > vector {}; if (i<0) { vector.push_back(minus_sign); i = -i; } return split_digits(i, vector); } std::string lineOfLargeDigits(const std::vector< std::vector<std::string> > &digits_vector, unsigned line_nr, unsigned n){ std::string line {}; for_each(digits_vector.begin(), digits_vector.end(), [&](std::vector<std::string> digit){ line.append(stretchLine(digit[line_nr], n)); line.append(n/2, ' '); // letter spacing for readability }); return line; } void printDigitSequence(std::vector< std::vector<std::string> > digits_vector, std::ostream &out, unsigned n){ unsigned line_nr {0}; std::ostream_iterator<std::string> out_it(out, "\n"); for_each(digits_vector.front().begin(), digits_vector.front().end(), [&](std::string _){ if (line_nr == 1 || line_nr == 3) { auto line = lineOfLargeDigits(digits_vector, line_nr, n); std::generate_n(out_it, n, [&](){return line;}); } else { out << lineOfLargeDigits(digits_vector, line_nr, n) << '\n'; } line_nr++; }); } void printLargeNumber(int i, std::ostream &out, unsigned n) { auto digits_vector = split_digits(i); printDigitSequence(digits_vector, out, n); } void printLargeError(std::ostream &out, unsigned n) { printDigitSequence(error, out, n); } } <commit_msg>no need to give param a name, add useful comment<commit_after>#include <ostream> #include <vector> #include <string> #include <algorithm> #include <iterator> #include "sevensegment.h" namespace sevensegment { const static std::vector< std::vector<std::string> > digits { { " - ", "| |", " ", "| |", " - " }, // 0 { " ", " |", " ", " |", " " }, // 1 { " - ", " |", " - ", "| ", " - " }, // 2 { " - ", " |", " - ", " |", " - " }, // 3 { " ", "| |", " - ", " |", " " }, // 4 { " - ", "| ", " - ", " |", " - " }, // 5 { " - ", "| ", " - ", "| |", " - " }, // 6 { " - ", " |", " ", " |", " " }, // 7 { " - ", "| |", " - ", "| |", " - " }, // 8 { " - ", "| |", " - ", " |", " - " } // 9 }; const static std::vector<std::string> minus_sign { " ", " ", " - ", " ", " " }; // - const static std::vector< std::vector<std::string> > error { { " - ", "| ", " - ", "| ", " - " }, // E { " ", " ", " - ", "| ", " " }, // r { " ", " ", " - ", "| ", " " }, // r { " ", " ", " - ", "| |", " - " }, // o { " ", " ", " - ", "| ", " " }, // r }; std::string stretchLine(const std::string &line, unsigned n) { std::string stretched_line(n+2, line[1]); stretched_line.front() = line[0]; stretched_line.back() = line[2]; return stretched_line; } void printLargeDigit(unsigned i, std::ostream &out, unsigned n) { auto digit = digits.at(i); std::ostream_iterator<std::string> out_it(out, "\n"); auto second_line = stretchLine(digit[1], n); auto fourth_line = stretchLine(digit[3], n); out << stretchLine(digit[0], n) << '\n'; std::generate_n(out_it, n, [&](){return second_line;}); out << stretchLine(digit[2], n) << '\n'; std::generate_n(out_it, n, [&](){return fourth_line;}); out << stretchLine(digit[4], n) << '\n'; } std::vector< std::vector<std::string> > split_digits(int i, std::vector< std::vector<std::string> > &vector) { if(i >= 10) split_digits(i / 10, vector); vector.push_back(digits.at(i % 10)); return vector; } std::vector< std::vector<std::string> > split_digits(int i) { std::vector< std::vector<std::string> > vector {}; if (i<0) { vector.push_back(minus_sign); i = -i; } return split_digits(i, vector); } std::string lineOfLargeDigits(const std::vector< std::vector<std::string> > &digits_vector, unsigned line_nr, unsigned n){ std::string line {}; for_each(digits_vector.begin(), digits_vector.end(), [&](std::vector<std::string> digit){ line.append(stretchLine(digit[line_nr], n)); line.append(n/2, ' '); // letter spacing for readability }); return line; } void printDigitSequence(std::vector< std::vector<std::string> > digits_vector, std::ostream &out, unsigned n){ unsigned line_nr {0}; std::ostream_iterator<std::string> out_it(out, "\n"); // iterate through lines, not digits // OPTIMIZE: transpose vector first for_each(digits_vector.front().begin(), digits_vector.front().end(), [&](std::string){ if (line_nr == 1 || line_nr == 3) { auto line = lineOfLargeDigits(digits_vector, line_nr, n); std::generate_n(out_it, n, [&](){return line;}); } else { out << lineOfLargeDigits(digits_vector, line_nr, n) << '\n'; } line_nr++; }); } void printLargeNumber(int i, std::ostream &out, unsigned n) { auto digits_vector = split_digits(i); printDigitSequence(digits_vector, out, n); } void printLargeError(std::ostream &out, unsigned n) { printDigitSequence(error, out, n); } } <|endoftext|>
<commit_before>// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #ifndef _SILENCE_ALL_CXX17_DEPRECATION_WARNINGS #define _SILENCE_ALL_CXX17_DEPRECATION_WARNINGS #endif // LotusRT #include "core/framework/allocatormgr.h" #include "core/common/logging/logging.h" #include "core/common/logging/sinks/clog_sink.h" #include "protobufHelpers.h" #include <fstream> using namespace wss; using namespace wfc; using namespace winml; // Copy and pasted from LOTUS as is. temporary code to load tensors from protobufs int FdOpen(const std::string& name) { int fd = -1; #ifdef _WIN32 _sopen_s(&fd, name.c_str(), _O_RDONLY | _O_SEQUENTIAL | _O_BINARY, _SH_DENYWR, _S_IREAD | _S_IWRITE); #else fd = open(name.c_str(), O_RDONLY); #endif return fd; }; // Copy and pasted from LOTUS as is. temporary code to load tensors from protobufs void FdClose(int fd) { if (fd >= 0) { #ifdef _WIN32 _close(fd); #else close(fd); #endif } } // Load Onnx TensorProto from Protobuf File bool ProtobufHelpers::LoadOnnxTensorFromProtobufFile(onnx::TensorProto& tensor, std::wstring filePath) { // setup a string converter using convert_type = std::codecvt_utf8<wchar_t>; std::wstring_convert<convert_type, wchar_t> converter; // use converter (.to_bytes: wstr->str, .from_bytes: str->wstr) std::string file = converter.to_bytes(filePath.c_str()); std::ifstream stream(file, std::ios::binary | std::ios::ate); std::streamsize size = stream.tellg(); stream.seekg(0, std::ios::beg); std::vector<char> buffer(static_cast<size_t>(size)); if (stream.read(buffer.data(), size)) { return tensor.ParseFromArray(buffer.data(), static_cast<int>(size)); } else { return false; } } template <typename DataType> std::vector<DataType> GetTypeSpecificDataFromTensorProto( onnx::TensorProto /*tensorProto*/) { static_assert(false, "UNDEFINED! TensorProto methods aren't templated, so add a new template specialization."); } template <> std::vector<float> GetTypeSpecificDataFromTensorProto( onnx::TensorProto tensorProto) { return std::vector<float>(std::begin(tensorProto.float_data()), std::end(tensorProto.float_data())); } template <> std::vector<int32_t> GetTypeSpecificDataFromTensorProto( onnx::TensorProto tensorProto) { return std::vector<int32_t>(std::begin(tensorProto.int32_data()), std::end(tensorProto.int32_data())); } template <> std::vector<int64_t> GetTypeSpecificDataFromTensorProto( onnx::TensorProto tensorProto) { return std::vector<int64_t>(std::begin(tensorProto.int64_data()), std::end(tensorProto.int64_data())); } template <typename DataType> std::vector<DataType> GetTensorDataFromTensorProto( onnx::TensorProto tensorProto, uint64_t elementCount) { if (tensorProto.has_raw_data()) { std::vector<DataType> tensorData; auto& values = tensorProto.raw_data(); if (elementCount != values.size() / sizeof(DataType)) { throw winrt::hresult_invalid_argument(L"TensorProto element count should match raw data buffer size in elements."); } tensorData = std::vector<DataType>(static_cast<size_t>(elementCount)); memcpy(tensorData.data(), values.data(), values.size()); return tensorData; } else { return GetTypeSpecificDataFromTensorProto<DataType>(tensorProto); } } static std::vector<winrt::hstring> GetTensorStringDataFromTensorProto( onnx::TensorProto tensorProto, uint64_t elementCount) { if(tensorProto.string_data_size() != elementCount) { throw winrt::hresult_invalid_argument(L"Number of elements in TensorProto does not match expected element count."); } auto& values = tensorProto.string_data(); auto returnVector = std::vector<winrt::hstring>(static_cast<size_t>(elementCount)); std::transform(std::begin(values), std::end(values), std::begin(returnVector), [](auto& value) { return winrt::to_hstring(value); }); return returnVector; } ITensor ProtobufHelpers::LoadTensorFromProtobufFile( const std::wstring& filePath, bool isFp16) { // load from the file path into the onnx format onnx::TensorProto tensorProto; if (LoadOnnxTensorFromProtobufFile(tensorProto, filePath)) { std::vector<int64_t> tensorShape = std::vector<int64_t>(tensorProto.dims().begin(), tensorProto.dims().end()); int64_t initialValue = 1; int64_t elementCount = std::accumulate(tensorShape.begin(), tensorShape.end(), initialValue, std::multiplies<int64_t>()); if (!tensorProto.has_data_type()) { std::cerr << "WARNING: Loading unknown TensorProto datatype.\n"; } if (isFp16) { return TensorFloat16Bit::CreateFromIterable(tensorShape, GetTensorDataFromTensorProto<float>(tensorProto, elementCount)); } switch (tensorProto.data_type()) { case (onnx::TensorProto::DataType::TensorProto_DataType_FLOAT): return TensorFloat::CreateFromIterable(tensorShape, GetTensorDataFromTensorProto<float>(tensorProto, elementCount)); case (onnx::TensorProto::DataType::TensorProto_DataType_INT32): return TensorInt32Bit::CreateFromIterable(tensorShape, GetTensorDataFromTensorProto<int32_t>(tensorProto, elementCount)); case (onnx::TensorProto::DataType::TensorProto_DataType_INT64): return TensorInt64Bit::CreateFromIterable(tensorShape, GetTensorDataFromTensorProto<int64_t>(tensorProto, elementCount)); case (onnx::TensorProto::DataType::TensorProto_DataType_STRING): return TensorString::CreateFromIterable(tensorShape, GetTensorStringDataFromTensorProto(tensorProto, elementCount)); default: throw winrt::hresult_invalid_argument(L"Tensor type for creating tensor from protobuf file not supported."); break; } } return nullptr; } TensorFloat16Bit ProtobufHelpers::LoadTensorFloat16FromProtobufFile( const std::wstring& filePath) { // load from the file path into the onnx format onnx::TensorProto tensorProto; if (LoadOnnxTensorFromProtobufFile(tensorProto, filePath)) { if (tensorProto.has_data_type()) { if(onnx::TensorProto::DataType::TensorProto_DataType_FLOAT16 != tensorProto.data_type()) { throw winrt::hresult_invalid_argument(L"TensorProto datatype isn't of type Float16."); } } else { std::cerr << "Loading unknown TensorProto datatype as TensorFloat16Bit.\n"; } auto shape = winrt::single_threaded_vector<int64_t>(std::vector<int64_t>(tensorProto.dims().begin(), tensorProto.dims().end())); TensorFloat16Bit singleTensorValue = TensorFloat16Bit::Create(shape.GetView()); uint16_t* data; winrt::com_ptr<ITensorNative> spTensorValueNative; singleTensorValue.as(spTensorValueNative); uint32_t sizeInBytes; spTensorValueNative->GetBuffer(reinterpret_cast<BYTE**>(&data), &sizeInBytes); if (!tensorProto.has_raw_data()) { throw winrt::hresult_invalid_argument(L"Float16 tensor proto buffers are expected to contain raw data."); } auto& raw_data = tensorProto.raw_data(); auto buff = raw_data.c_str(); const size_t type_size = sizeof(uint16_t); memcpy((void*)data, (void*)buff, raw_data.size() * sizeof(char)); return singleTensorValue; } return nullptr; } winml::LearningModel ProtobufHelpers::CreateModel( winml::TensorKind kind, const std::vector<int64_t>& shape, uint32_t num_elements) { onnx::ModelProto model; model.set_ir_version(onnx::Version::IR_VERSION); // Set opset import auto opsetimportproto = model.add_opset_import(); opsetimportproto->set_version(7); onnx::GraphProto& graph = *model.mutable_graph(); uint32_t begin = 0; uint32_t end = num_elements - 1; for (uint32_t i = begin; i <= end; i++) { onnx::NodeProto& node = *graph.add_node(); node.set_op_type("Identity"); if (i == begin && i == end) { node.add_input("input"); node.add_output("output"); } else if (i == begin) { node.add_input("input"); node.add_output("output" + std::to_string(i)); } else if (i == end) { node.add_input("output" + std::to_string(i - 1)); node.add_output("output"); } else { node.add_input("output" + std::to_string(i - 1)); node.add_output("output" + std::to_string(i)); } } onnx::TensorProto_DataType dataType; switch (kind) { case TensorKind::Float: dataType = onnx::TensorProto_DataType_FLOAT; break; case TensorKind::UInt8: dataType = onnx::TensorProto_DataType_UINT8; break; case TensorKind::Int8: dataType = onnx::TensorProto_DataType_INT8; break; case TensorKind::UInt16: dataType = onnx::TensorProto_DataType_UINT16; break; case TensorKind::Int16: dataType = onnx::TensorProto_DataType_INT16; break; case TensorKind::Int32: dataType = onnx::TensorProto_DataType_INT32; break; case TensorKind::Int64: dataType = onnx::TensorProto_DataType_INT64; break; case TensorKind::String: dataType = onnx::TensorProto_DataType_STRING; break; case TensorKind::Boolean: dataType = onnx::TensorProto_DataType_BOOL; break; case TensorKind::Float16: dataType = onnx::TensorProto_DataType_FLOAT16; break; case TensorKind::Double: dataType = onnx::TensorProto_DataType_DOUBLE; break; case TensorKind::UInt32: dataType = onnx::TensorProto_DataType_UINT32; break; case TensorKind::UInt64: dataType = onnx::TensorProto_DataType_UINT64; break; default: return nullptr; } char dim_param = 'a'; // input { onnx::ValueInfoProto& variable = *graph.add_input(); variable.set_name("input"); variable.mutable_type()->mutable_tensor_type()->set_elem_type(dataType); for (auto dim : shape) { if (dim == -1) { variable.mutable_type()->mutable_tensor_type()->mutable_shape()->add_dim()->set_dim_param(&dim_param, 1); dim_param++; } else { variable.mutable_type()->mutable_tensor_type()->mutable_shape()->add_dim()->set_dim_value(dim); } } if (shape.size() > 0) { variable.mutable_type()->mutable_tensor_type()->mutable_shape()->mutable_dim(0)->set_denotation("DATA_BATCH"); } } // output { onnx::ValueInfoProto& variable = *graph.add_output(); variable.set_name("output"); variable.mutable_type()->mutable_tensor_type()->set_elem_type(dataType); for (auto dim : shape) { if (dim == -1) { variable.mutable_type()->mutable_tensor_type()->mutable_shape()->add_dim()->set_dim_param(&dim_param, 1); dim_param++; } else { variable.mutable_type()->mutable_tensor_type()->mutable_shape()->add_dim()->set_dim_value(dim); } } } struct BufferStreamAdapter : public std::streambuf { RandomAccessStreamReference BufferAsRandomAccessStreamReference() { auto buffer = m_dataWriter.DetachBuffer(); m_dataWriter = DataWriter(); InMemoryRandomAccessStream stream; stream.WriteAsync(buffer).get(); return RandomAccessStreamReference::CreateFromStream(stream); } protected: virtual int_type overflow(int_type c) { if (c != EOF) { // convert lowercase to uppercase auto temp = static_cast<char>(c); m_dataWriter.WriteByte(temp); } return c; } private: DataWriter m_dataWriter; }; auto size = model.ByteSizeLong(); auto raw_array = std::unique_ptr<char[]>(new char[size]); model.SerializeToArray(raw_array.get(), static_cast<int>(size)); BufferStreamAdapter buffer; std::ostream os(&buffer); os.write(raw_array.get(), size); return LearningModel::LoadFromStream(buffer.BufferAsRandomAccessStreamReference()); } <commit_msg>add double and uint8_t datatypes (#4603)<commit_after>// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #ifndef _SILENCE_ALL_CXX17_DEPRECATION_WARNINGS #define _SILENCE_ALL_CXX17_DEPRECATION_WARNINGS #endif // LotusRT #include "core/framework/allocatormgr.h" #include "core/common/logging/logging.h" #include "core/common/logging/sinks/clog_sink.h" #include "protobufHelpers.h" #include <fstream> using namespace wss; using namespace wfc; using namespace winml; // Copy and pasted from LOTUS as is. temporary code to load tensors from protobufs int FdOpen(const std::string& name) { int fd = -1; #ifdef _WIN32 _sopen_s(&fd, name.c_str(), _O_RDONLY | _O_SEQUENTIAL | _O_BINARY, _SH_DENYWR, _S_IREAD | _S_IWRITE); #else fd = open(name.c_str(), O_RDONLY); #endif return fd; }; // Copy and pasted from LOTUS as is. temporary code to load tensors from protobufs void FdClose(int fd) { if (fd >= 0) { #ifdef _WIN32 _close(fd); #else close(fd); #endif } } // Load Onnx TensorProto from Protobuf File bool ProtobufHelpers::LoadOnnxTensorFromProtobufFile(onnx::TensorProto& tensor, std::wstring filePath) { // setup a string converter using convert_type = std::codecvt_utf8<wchar_t>; std::wstring_convert<convert_type, wchar_t> converter; // use converter (.to_bytes: wstr->str, .from_bytes: str->wstr) std::string file = converter.to_bytes(filePath.c_str()); std::ifstream stream(file, std::ios::binary | std::ios::ate); std::streamsize size = stream.tellg(); stream.seekg(0, std::ios::beg); std::vector<char> buffer(static_cast<size_t>(size)); if (stream.read(buffer.data(), size)) { return tensor.ParseFromArray(buffer.data(), static_cast<int>(size)); } else { return false; } } template <typename DataType> std::vector<DataType> GetTypeSpecificDataFromTensorProto( onnx::TensorProto /*tensorProto*/) { static_assert(false, "UNDEFINED! TensorProto methods aren't templated, so add a new template specialization."); } template <> std::vector<float> GetTypeSpecificDataFromTensorProto( onnx::TensorProto tensorProto) { return std::vector<float>(std::begin(tensorProto.float_data()), std::end(tensorProto.float_data())); } template <> std::vector<int32_t> GetTypeSpecificDataFromTensorProto( onnx::TensorProto tensorProto) { return std::vector<int32_t>(std::begin(tensorProto.int32_data()), std::end(tensorProto.int32_data())); } template <> std::vector<int64_t> GetTypeSpecificDataFromTensorProto( onnx::TensorProto tensorProto) { return std::vector<int64_t>(std::begin(tensorProto.int64_data()), std::end(tensorProto.int64_data())); } template <> std::vector<uint8_t> GetTypeSpecificDataFromTensorProto( onnx::TensorProto tensorProto) { return std::vector<uint8_t>(std::begin(tensorProto.int32_data()), std::end(tensorProto.int32_data())); } template <> std::vector<double> GetTypeSpecificDataFromTensorProto( onnx::TensorProto tensorProto) { return std::vector<double>(std::begin(tensorProto.double_data()), std::end(tensorProto.double_data())); } template <typename DataType> std::vector<DataType> GetTensorDataFromTensorProto( onnx::TensorProto tensorProto, uint64_t elementCount) { if (tensorProto.has_raw_data()) { std::vector<DataType> tensorData; auto& values = tensorProto.raw_data(); if (elementCount != values.size() / sizeof(DataType)) { throw winrt::hresult_invalid_argument(L"TensorProto element count should match raw data buffer size in elements."); } tensorData = std::vector<DataType>(static_cast<size_t>(elementCount)); memcpy(tensorData.data(), values.data(), values.size()); return tensorData; } else { return GetTypeSpecificDataFromTensorProto<DataType>(tensorProto); } } static std::vector<winrt::hstring> GetTensorStringDataFromTensorProto( onnx::TensorProto tensorProto, uint64_t elementCount) { if(tensorProto.string_data_size() != elementCount) { throw winrt::hresult_invalid_argument(L"Number of elements in TensorProto does not match expected element count."); } auto& values = tensorProto.string_data(); auto returnVector = std::vector<winrt::hstring>(static_cast<size_t>(elementCount)); std::transform(std::begin(values), std::end(values), std::begin(returnVector), [](auto& value) { return winrt::to_hstring(value); }); return returnVector; } ITensor ProtobufHelpers::LoadTensorFromProtobufFile( const std::wstring& filePath, bool isFp16) { // load from the file path into the onnx format onnx::TensorProto tensorProto; if (LoadOnnxTensorFromProtobufFile(tensorProto, filePath)) { std::vector<int64_t> tensorShape = std::vector<int64_t>(tensorProto.dims().begin(), tensorProto.dims().end()); int64_t initialValue = 1; int64_t elementCount = std::accumulate(tensorShape.begin(), tensorShape.end(), initialValue, std::multiplies<int64_t>()); if (!tensorProto.has_data_type()) { std::cerr << "WARNING: Loading unknown TensorProto datatype.\n"; } if (isFp16) { return TensorFloat16Bit::CreateFromIterable(tensorShape, GetTensorDataFromTensorProto<float>(tensorProto, elementCount)); } switch (tensorProto.data_type()) { case (onnx::TensorProto::DataType::TensorProto_DataType_FLOAT): return TensorFloat::CreateFromIterable(tensorShape, GetTensorDataFromTensorProto<float>(tensorProto, elementCount)); case (onnx::TensorProto::DataType::TensorProto_DataType_INT32): return TensorInt32Bit::CreateFromIterable(tensorShape, GetTensorDataFromTensorProto<int32_t>(tensorProto, elementCount)); case (onnx::TensorProto::DataType::TensorProto_DataType_INT64): return TensorInt64Bit::CreateFromIterable(tensorShape, GetTensorDataFromTensorProto<int64_t>(tensorProto, elementCount)); case (onnx::TensorProto::DataType::TensorProto_DataType_STRING): return TensorString::CreateFromIterable(tensorShape, GetTensorStringDataFromTensorProto(tensorProto, elementCount)); case (onnx::TensorProto::DataType::TensorProto_DataType_UINT8): return TensorUInt8Bit::CreateFromIterable(tensorShape, GetTensorDataFromTensorProto<uint8_t>(tensorProto, elementCount)); case (onnx::TensorProto::DataType::TensorProto_DataType_DOUBLE): return TensorDouble::CreateFromIterable(tensorShape, GetTensorDataFromTensorProto<double>(tensorProto, elementCount)); default: throw winrt::hresult_invalid_argument(L"Tensor type for creating tensor from protobuf file not supported."); break; } } return nullptr; } TensorFloat16Bit ProtobufHelpers::LoadTensorFloat16FromProtobufFile( const std::wstring& filePath) { // load from the file path into the onnx format onnx::TensorProto tensorProto; if (LoadOnnxTensorFromProtobufFile(tensorProto, filePath)) { if (tensorProto.has_data_type()) { if(onnx::TensorProto::DataType::TensorProto_DataType_FLOAT16 != tensorProto.data_type()) { throw winrt::hresult_invalid_argument(L"TensorProto datatype isn't of type Float16."); } } else { std::cerr << "Loading unknown TensorProto datatype as TensorFloat16Bit.\n"; } auto shape = winrt::single_threaded_vector<int64_t>(std::vector<int64_t>(tensorProto.dims().begin(), tensorProto.dims().end())); TensorFloat16Bit singleTensorValue = TensorFloat16Bit::Create(shape.GetView()); uint16_t* data; winrt::com_ptr<ITensorNative> spTensorValueNative; singleTensorValue.as(spTensorValueNative); uint32_t sizeInBytes; spTensorValueNative->GetBuffer(reinterpret_cast<BYTE**>(&data), &sizeInBytes); if (!tensorProto.has_raw_data()) { throw winrt::hresult_invalid_argument(L"Float16 tensor proto buffers are expected to contain raw data."); } auto& raw_data = tensorProto.raw_data(); auto buff = raw_data.c_str(); const size_t type_size = sizeof(uint16_t); memcpy((void*)data, (void*)buff, raw_data.size() * sizeof(char)); return singleTensorValue; } return nullptr; } winml::LearningModel ProtobufHelpers::CreateModel( winml::TensorKind kind, const std::vector<int64_t>& shape, uint32_t num_elements) { onnx::ModelProto model; model.set_ir_version(onnx::Version::IR_VERSION); // Set opset import auto opsetimportproto = model.add_opset_import(); opsetimportproto->set_version(7); onnx::GraphProto& graph = *model.mutable_graph(); uint32_t begin = 0; uint32_t end = num_elements - 1; for (uint32_t i = begin; i <= end; i++) { onnx::NodeProto& node = *graph.add_node(); node.set_op_type("Identity"); if (i == begin && i == end) { node.add_input("input"); node.add_output("output"); } else if (i == begin) { node.add_input("input"); node.add_output("output" + std::to_string(i)); } else if (i == end) { node.add_input("output" + std::to_string(i - 1)); node.add_output("output"); } else { node.add_input("output" + std::to_string(i - 1)); node.add_output("output" + std::to_string(i)); } } onnx::TensorProto_DataType dataType; switch (kind) { case TensorKind::Float: dataType = onnx::TensorProto_DataType_FLOAT; break; case TensorKind::UInt8: dataType = onnx::TensorProto_DataType_UINT8; break; case TensorKind::Int8: dataType = onnx::TensorProto_DataType_INT8; break; case TensorKind::UInt16: dataType = onnx::TensorProto_DataType_UINT16; break; case TensorKind::Int16: dataType = onnx::TensorProto_DataType_INT16; break; case TensorKind::Int32: dataType = onnx::TensorProto_DataType_INT32; break; case TensorKind::Int64: dataType = onnx::TensorProto_DataType_INT64; break; case TensorKind::String: dataType = onnx::TensorProto_DataType_STRING; break; case TensorKind::Boolean: dataType = onnx::TensorProto_DataType_BOOL; break; case TensorKind::Float16: dataType = onnx::TensorProto_DataType_FLOAT16; break; case TensorKind::Double: dataType = onnx::TensorProto_DataType_DOUBLE; break; case TensorKind::UInt32: dataType = onnx::TensorProto_DataType_UINT32; break; case TensorKind::UInt64: dataType = onnx::TensorProto_DataType_UINT64; break; default: return nullptr; } char dim_param = 'a'; // input { onnx::ValueInfoProto& variable = *graph.add_input(); variable.set_name("input"); variable.mutable_type()->mutable_tensor_type()->set_elem_type(dataType); for (auto dim : shape) { if (dim == -1) { variable.mutable_type()->mutable_tensor_type()->mutable_shape()->add_dim()->set_dim_param(&dim_param, 1); dim_param++; } else { variable.mutable_type()->mutable_tensor_type()->mutable_shape()->add_dim()->set_dim_value(dim); } } if (shape.size() > 0) { variable.mutable_type()->mutable_tensor_type()->mutable_shape()->mutable_dim(0)->set_denotation("DATA_BATCH"); } } // output { onnx::ValueInfoProto& variable = *graph.add_output(); variable.set_name("output"); variable.mutable_type()->mutable_tensor_type()->set_elem_type(dataType); for (auto dim : shape) { if (dim == -1) { variable.mutable_type()->mutable_tensor_type()->mutable_shape()->add_dim()->set_dim_param(&dim_param, 1); dim_param++; } else { variable.mutable_type()->mutable_tensor_type()->mutable_shape()->add_dim()->set_dim_value(dim); } } } struct BufferStreamAdapter : public std::streambuf { RandomAccessStreamReference BufferAsRandomAccessStreamReference() { auto buffer = m_dataWriter.DetachBuffer(); m_dataWriter = DataWriter(); InMemoryRandomAccessStream stream; stream.WriteAsync(buffer).get(); return RandomAccessStreamReference::CreateFromStream(stream); } protected: virtual int_type overflow(int_type c) { if (c != EOF) { // convert lowercase to uppercase auto temp = static_cast<char>(c); m_dataWriter.WriteByte(temp); } return c; } private: DataWriter m_dataWriter; }; auto size = model.ByteSizeLong(); auto raw_array = std::unique_ptr<char[]>(new char[size]); model.SerializeToArray(raw_array.get(), static_cast<int>(size)); BufferStreamAdapter buffer; std::ostream os(&buffer); os.write(raw_array.get(), size); return LearningModel::LoadFromStream(buffer.BufferAsRandomAccessStreamReference()); } <|endoftext|>
<commit_before>#include "CplusPlusExe.h" //Exe6_51 void f() { cout << " f with null parameters\n"; } void f(int ival) { cout << "f with one int parameter:" << ival << endl; } void f(int ival1, int ival2) { cout << "f with two int parameters :" << ival1 << " " << ival2 << endl; } void f(double dval1, double dval2 = 3.14) { cout << "f with two double parameters :" << dval1 << " " << dval2 << endl; } //test for recusion loop int recloop(int val) { if (val > 1) return recloop(val - 1) * val; return 1; }; // int array[10]; // int( &func() ) [10] // { // return array; // } int main() { //cout << Exe6_27({1}); //Exe5_21(); /*vector<int> v = { 1, 2, 3, 4, 5 }; Exe6_33(v);*/ // f(2.56, 3.14); // Exe8_4(); // val.push_back(12); // cout<<a<<endl; // Exe8_6("../Salesdata.bin"); // Exe8_7("../Salesdata.bin", "outfile"); // Exe8_8("../Salesdata.bin", "outfile"); // string cin2string; // getline(cin, cin2string); // istringstream indata(cin2string); // Exe8_9(indata); ostream_iterator<int> out(cout, " "); vector<int> vi(10); for_each(vi.begin(), vi.end(), [&](int &i)->void{ static int cnt = 0;i = cnt++;}); auto one = find(vi.crbegin(), vi.crend(), 5); for_each(vi.cbegin(), one.base(), [&](int i){*out++ = i;}); // copy(vi.crbegin(), vi.crend(), out); // Exe8_13("../Salesdata.bin"); #ifdef __WINDOWS_ system(" pause "); #endif return 0; }<commit_msg>fix a little bug...<commit_after>#include "CplusPlusExe.h" //Exe6_51 void f() { cout << " f with null parameters\n"; } void f(int ival) { cout << "f with one int parameter:" << ival << endl; } void f(int ival1, int ival2) { cout << "f with two int parameters :" << ival1 << " " << ival2 << endl; } void f(double dval1, double dval2 = 3.14) { cout << "f with two double parameters :" << dval1 << " " << dval2 << endl; } //test for recusion loop int recloop(int val) { if (val > 1) return recloop(val - 1) * val; return 1; }; // int array[10]; // int( &func() ) [10] // { // return array; // } int main() { //cout << Exe6_27({1}); //Exe5_21(); /*vector<int> v = { 1, 2, 3, 4, 5 }; Exe6_33(v);*/ // f(2.56, 3.14); // Exe8_4(); // val.push_back(12); // cout<<a<<endl; // Exe8_6("../Salesdata.bin"); // Exe8_7("../Salesdata.bin", "outfile"); // Exe8_8("../Salesdata.bin", "outfile"); // string cin2string; // getline(cin, cin2string); // istringstream indata(cin2string); // Exe8_9(indata); ostream_iterator<int> out(cout, " "); vector<int> vi(10); for_each(vi.begin(), vi.end(), [&](int &i)->void{ static int cnt = 0;i = cnt++;}); auto one = find(vi.crbegin(), vi.crend(), 5); for_each(vi.cbegin(), one.base(), [&](int i){*out++ = i;}); // copy(vi.crbegin(), vi.crend(), out); // Exe8_13("../Salesdata.bin"); for (auto i :vi) { cout<<i; } #ifdef __WINDOWS_ system(" pause "); #endif return 0; }<|endoftext|>
<commit_before>/// \file /// \ingroup tutorial_eve /// Shows CMS geometry in stereo mode. /// This requires quad-buffer support in the OpenGL hardware / driver, /// otheriwse a fatal error occurs. /// /// \image html eve_geom_cms_stereo.png /// \macro_code /// /// \author Matevz Tadel void geom_cms_stereo(Bool_t quad_buf=kTRUE) { TEveManager::Create(); TFile::SetCacheFileDir("."); gGeoManager = gEve->GetGeometry("http://root.cern.ch/files/cms.root"); gGeoManager->DefaultColors(); TGeoVolume* top = gGeoManager->GetTopVolume()->FindNode("CMSE_1")->GetVolume(); TEveGeoTopNode* trk = new TEveGeoTopNode(gGeoManager, top->FindNode("TRAK_1")); trk->SetVisLevel(6); gEve->AddGlobalElement(trk); TEveGeoTopNode* calo = new TEveGeoTopNode(gGeoManager, top->FindNode("CALO_1")); calo->SetVisLevel(3); gEve->AddGlobalElement(calo); TEveGeoTopNode* muon = new TEveGeoTopNode(gGeoManager, top->FindNode("MUON_1")); muon->SetVisLevel(4); gEve->AddGlobalElement(muon); // --- Stereo --- TEveWindowSlot* slot = 0; slot = TEveWindow::CreateWindowInTab(gEve->GetBrowser()->GetTabRight()); TEveViewer* sv = new TEveViewer("Stereo GL", "Stereoscopic view"); sv->SpawnGLViewer(gEve->GetEditor(), kTRUE, quad_buf); sv->AddScene(gEve->GetGlobalScene()); slot->ReplaceWindow(sv); gEve->GetViewers()->AddElement(sv); gEve->GetBrowser()->GetTabRight()->SetTab(1); // --- Redraw --- gEve->FullRedraw3D(kTRUE); gEve->EditElement(sv); // --- Fix editor --- // EClipType not exported to CINT (see TGLUtil.h): // 0 - no clip, 1 - clip plane, 2 - clip box TGLViewer *v = gEve->GetDefaultGLViewer(); v->GetClipSet()->SetClipType(TGLClip::EType(1)); v->ColorSet().Background().SetColor(kMagenta+4); v->SetGuideState(TGLUtil::kAxesEdge, kTRUE, kFALSE, 0); v->RefreshPadEditor(v); v->CurrentCamera().RotateRad(-1.2, 0.5); v->DoDraw(); } <commit_msg>- spell check - use auto<commit_after>/// \file /// \ingroup tutorial_eve /// Shows CMS geometry in stereo mode. /// This requires quad-buffer support in the OpenGL hardware / driver, /// otherwise a fatal error occurs. /// /// \image html eve_geom_cms_stereo.png /// \macro_code /// /// \author Matevz Tadel void geom_cms_stereo(Bool_t quad_buf=kTRUE) { TEveManager::Create(); TFile::SetCacheFileDir("."); gGeoManager = gEve->GetGeometry("http://root.cern.ch/files/cms.root"); gGeoManager->DefaultColors(); auto top = gGeoManager->GetTopVolume()->FindNode("CMSE_1")->GetVolume(); auto trk = new TEveGeoTopNode(gGeoManager, top->FindNode("TRAK_1")); trk->SetVisLevel(6); gEve->AddGlobalElement(trk); auto calo = new TEveGeoTopNode(gGeoManager, top->FindNode("CALO_1")); calo->SetVisLevel(3); gEve->AddGlobalElement(calo); auto muon = new TEveGeoTopNode(gGeoManager, top->FindNode("MUON_1")); muon->SetVisLevel(4); gEve->AddGlobalElement(muon); // --- Stereo --- TEveWindowSlot* slot = 0; slot = TEveWindow::CreateWindowInTab(gEve->GetBrowser()->GetTabRight()); auto sv = new TEveViewer("Stereo GL", "Stereoscopic view"); sv->SpawnGLViewer(gEve->GetEditor(), kTRUE, quad_buf); sv->AddScene(gEve->GetGlobalScene()); slot->ReplaceWindow(sv); gEve->GetViewers()->AddElement(sv); gEve->GetBrowser()->GetTabRight()->SetTab(1); // --- Redraw --- gEve->FullRedraw3D(kTRUE); gEve->EditElement(sv); // --- Fix editor --- // EClipType not exported to CINT (see TGLUtil.h): // 0 - no clip, 1 - clip plane, 2 - clip box auto v = gEve->GetDefaultGLViewer(); v->GetClipSet()->SetClipType(TGLClip::EType(1)); v->ColorSet().Background().SetColor(kMagenta+4); v->SetGuideState(TGLUtil::kAxesEdge, kTRUE, kFALSE, 0); v->RefreshPadEditor(v); v->CurrentCamera().RotateRad(-1.2, 0.5); v->DoDraw(); } <|endoftext|>
<commit_before>#include <AST/visitors/IrtBuilderVisitor.h> using namespace AstTree; IRTree::TOperatorType CIrtBuilderVisitor::operatorFromAstToIr( TOperatorType type ) const { IRTree::TOperatorType typeResult; switch ( type ) { case TOperatorType::OT_Plus: typeResult = IRTree::TOperatorType::OT_Plus; case TOperatorType::OT_Minus: typeResult = IRTree::TOperatorType::OT_Minus; case TOperatorType::OT_Times: typeResult = IRTree::TOperatorType::OT_Times; case TOperatorType::OT_Div: typeResult = IRTree::TOperatorType::OT_Div; case TOperatorType::OT_Mod: typeResult = IRTree::TOperatorType::OT_Mod; case TOperatorType::OT_And: typeResult = IRTree::TOperatorType::OT_And; case TOperatorType::OT_Or: typeResult = IRTree::TOperatorType::OT_Or; default: { // such cases should never happen assert( false ) ; } } return typeResult; } void CIrtBuilderVisitor::updateSubtreeWrapper( const IRTree::ISubtreeWrapper* wrapperNew ) { subtreeWrapper = std::unique_ptr<const IRTree::ISubtreeWrapper>( wrapperNew ); } /*__________ Access Modifiers __________*/ void CIrtBuilderVisitor::Visit( const CPublicAccessModifier* modifier ) { std::string nodeName = generateNodeName( CAstNodeNames::ACCESS_MOD_PUBLIC ); onNodeEnter( nodeName ); // such calls should never happen assert( false ); onNodeExit( nodeName ); } void CIrtBuilderVisitor::Visit( const CPrivateAccessModifier* modifier ) { std::string nodeName = generateNodeName( CAstNodeNames::ACCESS_MOD_PRIVATE ); onNodeEnter( nodeName ); // such calls should never happen assert( false ); onNodeExit( nodeName ); } /*__________ Expressions __________*/ void CIrtBuilderVisitor::Visit( const CBinaryExpression* expression ) { std::string nodeName = generateNodeName( CAstNodeNames::EXP_BINARY ); onNodeEnter( nodeName ); expression->LeftOperand()->Accept( this ); const IRTree::CExpression* expressionLeft = subtreeWrapper->ToExpression(); expression->RightOperand()->Accept( this ); const IRTree::CExpression* expressionRight = subtreeWrapper->ToExpression(); if ( expression->Operation() == TOperatorType::OT_LT ) { updateSubtreeWrapper( new IRTree::CRelativeConditionalWrapper( IRTree::TLogicOperatorType::LOT_LT, expressionLeft, expressionRight ) ); } else { IRTree::TOperatorType operatorType = operatorFromAstToIr( expression->Operation() ); updateSubtreeWrapper( new IRTree::CExpressionWrapper( new IRTree::CBinaryExpression( operatorType, expressionLeft, expressionRight ) ) ); } onNodeExit( nodeName ); } void CIrtBuilderVisitor::Visit( const CBracketExpression* expression ) { std::string nodeName = generateNodeName( CAstNodeNames::EXP_BRACKET ); onNodeEnter( nodeName ); // write your code here onNodeExit( nodeName ); } void CIrtBuilderVisitor::Visit( const CNumberExpression* expression ) { std::string nodeName = generateNodeName( CAstNodeNames::EXP_NUMBER ); onNodeEnter( nodeName ); updateSubtreeWrapper( new IRTree::CExpressionWrapper( new IRTree::CConstExpression( expression->Value() ) ) ); onNodeExit( nodeName ); } void CIrtBuilderVisitor::Visit( const CLogicExpression* expression ) { std::string nodeName = generateNodeName( CAstNodeNames::EXP_LOGIC ); onNodeEnter( nodeName ); updateSubtreeWrapper( new IRTree::CExpressionWrapper( new IRTree::CConstExpression( expression->Value() ? 1 : 0 ) ) ); onNodeExit( nodeName ); } void CIrtBuilderVisitor::Visit( const CIdExpression* expression ) { std::string nodeName = generateNodeName( CAstNodeNames::EXP_ID ); onNodeEnter( nodeName ); // write your code here onNodeExit( nodeName ); } void CIrtBuilderVisitor::Visit( const CLengthExpression* expression ) { std::string nodeName = generateNodeName( CAstNodeNames::EXP_LENGTH ); onNodeEnter( nodeName ); // write your code here onNodeExit( nodeName ); } void CIrtBuilderVisitor::Visit( const CMethodExpression* expression ) { std::string nodeName = generateNodeName( CAstNodeNames::EXP_METHOD ); onNodeEnter( nodeName ); // write your code here onNodeExit( nodeName ); } void CIrtBuilderVisitor::Visit( const CThisExpression* expression ) { std::string nodeName = generateNodeName( CAstNodeNames::EXP_THIS ); onNodeEnter( nodeName ); // write your code here onNodeExit( nodeName ); } void CIrtBuilderVisitor::Visit( const CNewArrayExpression* expression ) { std::string nodeName = generateNodeName( CAstNodeNames::EXP_NEW_ARRAY ); onNodeEnter( nodeName ); expression->LengthExpression->Accept( this ); const IRTree::CExpression* expressionLength = subtreeWrapper->ToExpression(); updateSubtreeWrapper( new IRTree::CExpressionWrapper( frame.ExternalCall("initArray", new IRTree::CExpressionList( expressionLength ) ); ) ); onNodeExit( nodeName ); } void CIrtBuilderVisitor::Visit( const CNewIdExpression* expression ) { std::string nodeName = generateNodeName( CAstNodeNames::EXP_NEW_ID ); onNodeEnter( nodeName ); const IRTree::CExpression* tempExpression = new IRTree::CTempExpression( CTemp() ); updateSubtreeWrapper( new IRTree::CExpressionWrapper( new IRTree::CEseqExpression( new IRTree::CMoveStatement( tempExpression, frame.ExternalCall("malloc", new IRTree::CExpressionList( IRTree::CConstExpression( /*TODO*/0 ) )) ) ) ) ); onNodeExit( nodeName ); } void CIrtBuilderVisitor::Visit( const CNegateExpression* expression ) { std::string nodeName = generateNodeName( CAstNodeNames::EXP_NEGATE ); onNodeEnter( nodeName ); expression->TargetExpression()->Accept( this ); updateSubtreeWrapper( new IRTree::CNegateConditionalWrapper( subtreeWrapper ) ); onNodeExit( nodeName ); } /*__________ Statements __________*/ void CIrtBuilderVisitor::Visit( const CAssignIdStatement* statement ) { std::string nodeName = generateNodeName( CAstNodeNames::STAT_ASSIGN_ID ); onNodeEnter( nodeName ); statement->LeftPart()->Accept( this ); std::unique_ptr<const IRTree::ISubtreeWrapper> wrapperLeftPart = subtreeWrapper; statement->RightPart()->Accept( this ); std::unique_ptr<const IRTree::ISubtreeWrapper> wrapperRightPart = subtreeWrapper; updateSubtreeWrapper( new IRTree::CStatementWrapper( new CMoveStatement( wrapperLeftPart.ToExpression(), wrapperRightPart.ToExpression() ) ) ); onNodeExit( nodeName ); } void CIrtBuilderVisitor::Visit( const CAssignIdWithIndexStatement* statement ) { std::string nodeName = generateNodeName( CAstNodeNames::STAT_ASSIGN_ID_WITH_INDEX ); onNodeEnter( nodeName ); // write your code here onNodeExit( nodeName ); } void CIrtBuilderVisitor::Visit( const CPrintStatement* statement ) { std::string nodeName = generateNodeName( CAstNodeNames::STAT_PRINT ); onNodeEnter( nodeName ); // write your code here onNodeExit( nodeName ); } void CIrtBuilderVisitor::Visit( const CConditionalStatement* statement ) { std::string nodeName = generateNodeName( CAstNodeNames::STAT_CONDITIONAL ); onNodeEnter( nodeName ); statement->Condition()->Accept( this ); std::unique_ptr<const IRTree::ISubtreeWrapper> wrapperCondition = subtreeWrapper; statement->PositiveTarget()->Accept( this ); std::unique_ptr<const IRTree::ISubtreeWrapper> wrapperTargetPositive = subtreeWrapper; statement->NegativeTarget()->Accept( this ); std::unique_ptr<const IRTree::ISubtreeWrapper> wrapperTargetNegative = subtreeWrapper; IRTree::CLabel labelTrue; IRTree::CLabel labelFalse; IRTree::CLabel labelJoin; updateSubtreeWrapper( new IRTree::CStatementWrapper( new IRTree::CSeqStatement( wrapperCondition->ToCondition( labelTrue, labelFalse ), new IRTree::CSeqStatement( new IRTree::CLabelStatement( labelTrue ), new IRTree::CSeqStatement( wrapperTargetPositive->ToStatement(), new IRTree::CSeqStatement( new IRTree::CJumpStatement( labelJoin ), new IRTree::CSeqStatement( new IRTree::CLabelStatement( labelFalse ), new IRTree::CSeqStatement( wrapperTargetNegative->ToStatement(), new IRTree::CLabelStatement( IRTree::CLabel() ) ) ) ) ) ) ) ) ); onNodeExit( nodeName ); } void CIrtBuilderVisitor::Visit( const CWhileLoopStatement* statement ) { std::string nodeName = generateNodeName( CAstNodeNames::STAT_WHILE_LOOP ); onNodeEnter( nodeName ); statement->Condition()->Accept( this ); std::unique_ptr<const IRTree::ISubtreeWrapper> wrapperCondition = subtreeWrapper; statement->Body()->Accept( this ); std::unique_ptr<const IRTree::ISubtreeWrapper> wrapperBody = subtreeWrapper; IRTree::CLabel labelLoop; IRTree::CLabel labelBody; IRTree::CLabel labelDone; updateSubtreeWrapper( new IRTree::CStatementWrapper( new IRTree::CSeqStatement( new IRTree::CLabelStatement( labelLoop ), new IRTree::CSeqStatement( wrapperCondition->ToCondition( labelBody, labelDone ), new IRTree::CSeqStatement( new IRTree::CLabelStatement( labelBody ), new IRTree::CSeqStatement( wrapperBody->ToStatement(), new IRTree::CSeqStatement( new IRTree::CJumpStatement( labelLoop ), new IRTree::CLabelStatement( labelDone ) ) ) ) ) ) ) ); onNodeExit( nodeName ); } void CIrtBuilderVisitor::Visit( const CBracesStatement* statement ) { std::string nodeName = generateNodeName( CAstNodeNames::STAT_BRACES ); onNodeEnter( nodeName ); // write your code here onNodeExit( nodeName ); } /*__________ Type Modifiers __________*/ void CIrtBuilderVisitor::Visit( const CIntTypeModifier* typeModifier ) { std::string nodeName = generateNodeName( CAstNodeNames::TYPE_MOD_INT ); onNodeEnter( nodeName ); // write your code here onNodeExit( nodeName ); } void CIrtBuilderVisitor::Visit( const CBooleanTypeModifier* typeModifier ) { std::string nodeName = generateNodeName( CAstNodeNames::TYPE_MOD_BOOL ); onNodeEnter( nodeName ); // write your code here onNodeExit( nodeName ); } void CIrtBuilderVisitor::Visit( const CIntArrayTypeModifier* typeModifier ) { std::string nodeName = generateNodeName( CAstNodeNames::TYPE_MOD_INT_ARRAY ); onNodeEnter( nodeName ); // write your code here onNodeExit( nodeName ); } void CIrtBuilderVisitor::Visit( const CIdTypeModifier* typeModifier ) { std::string nodeName = generateNodeName( CAstNodeNames::TYPE_MOD_ID ); onNodeEnter( nodeName ); // write your code here onNodeExit( nodeName ); } /*__________ Other (except lists) __________*/ void CIrtBuilderVisitor::Visit( const CVarDeclaration* declaration ) { std::string nodeName = generateNodeName( CAstNodeNames::VAR_DECL ); onNodeEnter( nodeName ); // write your code here onNodeExit( nodeName ); } void CIrtBuilderVisitor::Visit( const CMethodArgument* argument ) { std::string nodeName = generateNodeName( CAstNodeNames::METH_ARG ); onNodeEnter( nodeName ); // write your code here onNodeExit( nodeName ); } void CIrtBuilderVisitor::Visit( const CMethodDeclaration* declaration ) { std::string nodeName = generateNodeName( CAstNodeNames::METH_DECL ); onNodeEnter( nodeName ); // write your code here onNodeExit( nodeName ); } void CIrtBuilderVisitor::Visit( const CMainClass* mainClass ) { std::string nodeName = generateNodeName( CAstNodeNames::MAIN_CLASS ); onNodeEnter( nodeName ); // write your code here onNodeExit( nodeName ); } void CIrtBuilderVisitor::Visit( const CClassDeclaration* declaration ) { std::string nodeName = generateNodeName( CAstNodeNames::CLASS_DECL ); onNodeEnter( nodeName ); // write your code here onNodeExit( nodeName ); } void CIrtBuilderVisitor::Visit( const CProgram* program ) { std::string nodeName = generateNodeName( CAstNodeNames::PROGRAM ); onNodeEnter( nodeName ); // write your code here onNodeExit( nodeName ); } /*__________ Lists __________*/ void CIrtBuilderVisitor::Visit( const CExpressionList* list ) { std::string nodeName = generateNodeName( CAstNodeNames::EXP_LIST ); onNodeEnter( nodeName ); // write your code here onNodeExit( nodeName ); } void CIrtBuilderVisitor::Visit( const CStatementList* list ) { std::string nodeName = generateNodeName( CAstNodeNames::STAT_LIST ); onNodeEnter( nodeName ); // write your code here onNodeExit( nodeName ); } void CIrtBuilderVisitor::Visit( const CVarDeclarationList* list ) { std::string nodeName = generateNodeName( CAstNodeNames::VAR_DECL_LIST ); onNodeEnter( nodeName ); // write your code here onNodeExit( nodeName ); } void CIrtBuilderVisitor::Visit( const CMethodArgumentList* list ) { std::string nodeName = generateNodeName( CAstNodeNames::METH_ARG_LIST ); onNodeEnter( nodeName ); // write your code here onNodeExit( nodeName ); } void CIrtBuilderVisitor::Visit( const CMethodDeclarationList* list ) { std::string nodeName = generateNodeName( CAstNodeNames::METH_DECL_LIST ); onNodeEnter( nodeName ); // write your code here onNodeExit( nodeName ); } void CIrtBuilderVisitor::Visit( const CClassDeclarationList* list ) { std::string nodeName = generateNodeName( CAstNodeNames::CLASS_DECL_LIST ); onNodeEnter( nodeName ); // write your code here onNodeExit( nodeName ); } <commit_msg>CBracesStatement translated<commit_after>#include <AST/visitors/IrtBuilderVisitor.h> using namespace AstTree; IRTree::TOperatorType CIrtBuilderVisitor::operatorFromAstToIr( TOperatorType type ) const { IRTree::TOperatorType typeResult; switch ( type ) { case TOperatorType::OT_Plus: typeResult = IRTree::TOperatorType::OT_Plus; case TOperatorType::OT_Minus: typeResult = IRTree::TOperatorType::OT_Minus; case TOperatorType::OT_Times: typeResult = IRTree::TOperatorType::OT_Times; case TOperatorType::OT_Div: typeResult = IRTree::TOperatorType::OT_Div; case TOperatorType::OT_Mod: typeResult = IRTree::TOperatorType::OT_Mod; case TOperatorType::OT_And: typeResult = IRTree::TOperatorType::OT_And; case TOperatorType::OT_Or: typeResult = IRTree::TOperatorType::OT_Or; default: { // such cases should never happen assert( false ) ; } } return typeResult; } void CIrtBuilderVisitor::updateSubtreeWrapper( const IRTree::ISubtreeWrapper* wrapperNew ) { subtreeWrapper = std::unique_ptr<const IRTree::ISubtreeWrapper>( wrapperNew ); } /*__________ Access Modifiers __________*/ void CIrtBuilderVisitor::Visit( const CPublicAccessModifier* modifier ) { std::string nodeName = generateNodeName( CAstNodeNames::ACCESS_MOD_PUBLIC ); onNodeEnter( nodeName ); // such calls should never happen assert( false ); onNodeExit( nodeName ); } void CIrtBuilderVisitor::Visit( const CPrivateAccessModifier* modifier ) { std::string nodeName = generateNodeName( CAstNodeNames::ACCESS_MOD_PRIVATE ); onNodeEnter( nodeName ); // such calls should never happen assert( false ); onNodeExit( nodeName ); } /*__________ Expressions __________*/ void CIrtBuilderVisitor::Visit( const CBinaryExpression* expression ) { std::string nodeName = generateNodeName( CAstNodeNames::EXP_BINARY ); onNodeEnter( nodeName ); expression->LeftOperand()->Accept( this ); const IRTree::CExpression* expressionLeft = subtreeWrapper->ToExpression(); expression->RightOperand()->Accept( this ); const IRTree::CExpression* expressionRight = subtreeWrapper->ToExpression(); if ( expression->Operation() == TOperatorType::OT_LT ) { updateSubtreeWrapper( new IRTree::CRelativeConditionalWrapper( IRTree::TLogicOperatorType::LOT_LT, expressionLeft, expressionRight ) ); } else { IRTree::TOperatorType operatorType = operatorFromAstToIr( expression->Operation() ); updateSubtreeWrapper( new IRTree::CExpressionWrapper( new IRTree::CBinaryExpression( operatorType, expressionLeft, expressionRight ) ) ); } onNodeExit( nodeName ); } void CIrtBuilderVisitor::Visit( const CBracketExpression* expression ) { std::string nodeName = generateNodeName( CAstNodeNames::EXP_BRACKET ); onNodeEnter( nodeName ); // write your code here onNodeExit( nodeName ); } void CIrtBuilderVisitor::Visit( const CNumberExpression* expression ) { std::string nodeName = generateNodeName( CAstNodeNames::EXP_NUMBER ); onNodeEnter( nodeName ); updateSubtreeWrapper( new IRTree::CExpressionWrapper( new IRTree::CConstExpression( expression->Value() ) ) ); onNodeExit( nodeName ); } void CIrtBuilderVisitor::Visit( const CLogicExpression* expression ) { std::string nodeName = generateNodeName( CAstNodeNames::EXP_LOGIC ); onNodeEnter( nodeName ); updateSubtreeWrapper( new IRTree::CExpressionWrapper( new IRTree::CConstExpression( expression->Value() ? 1 : 0 ) ) ); onNodeExit( nodeName ); } void CIrtBuilderVisitor::Visit( const CIdExpression* expression ) { std::string nodeName = generateNodeName( CAstNodeNames::EXP_ID ); onNodeEnter( nodeName ); // write your code here onNodeExit( nodeName ); } void CIrtBuilderVisitor::Visit( const CLengthExpression* expression ) { std::string nodeName = generateNodeName( CAstNodeNames::EXP_LENGTH ); onNodeEnter( nodeName ); // write your code here onNodeExit( nodeName ); } void CIrtBuilderVisitor::Visit( const CMethodExpression* expression ) { std::string nodeName = generateNodeName( CAstNodeNames::EXP_METHOD ); onNodeEnter( nodeName ); // write your code here onNodeExit( nodeName ); } void CIrtBuilderVisitor::Visit( const CThisExpression* expression ) { std::string nodeName = generateNodeName( CAstNodeNames::EXP_THIS ); onNodeEnter( nodeName ); // write your code here onNodeExit( nodeName ); } void CIrtBuilderVisitor::Visit( const CNewArrayExpression* expression ) { std::string nodeName = generateNodeName( CAstNodeNames::EXP_NEW_ARRAY ); onNodeEnter( nodeName ); expression->LengthExpression->Accept( this ); const IRTree::CExpression* expressionLength = subtreeWrapper->ToExpression(); updateSubtreeWrapper( new IRTree::CExpressionWrapper( frame.ExternalCall("initArray", new IRTree::CExpressionList( expressionLength ) ); ) ); onNodeExit( nodeName ); } void CIrtBuilderVisitor::Visit( const CNewIdExpression* expression ) { std::string nodeName = generateNodeName( CAstNodeNames::EXP_NEW_ID ); onNodeEnter( nodeName ); const IRTree::CExpression* tempExpression = new IRTree::CTempExpression( CTemp() ); updateSubtreeWrapper( new IRTree::CExpressionWrapper( new IRTree::CEseqExpression( new IRTree::CMoveStatement( tempExpression, frame.ExternalCall("malloc", new IRTree::CExpressionList( IRTree::CConstExpression( /*TODO*/0 ) )) ) ) ) ); onNodeExit( nodeName ); } void CIrtBuilderVisitor::Visit( const CNegateExpression* expression ) { std::string nodeName = generateNodeName( CAstNodeNames::EXP_NEGATE ); onNodeEnter( nodeName ); expression->TargetExpression()->Accept( this ); updateSubtreeWrapper( new IRTree::CNegateConditionalWrapper( subtreeWrapper ) ); onNodeExit( nodeName ); } /*__________ Statements __________*/ void CIrtBuilderVisitor::Visit( const CAssignIdStatement* statement ) { std::string nodeName = generateNodeName( CAstNodeNames::STAT_ASSIGN_ID ); onNodeEnter( nodeName ); statement->LeftPart()->Accept( this ); std::unique_ptr<const IRTree::ISubtreeWrapper> wrapperLeftPart = subtreeWrapper; statement->RightPart()->Accept( this ); std::unique_ptr<const IRTree::ISubtreeWrapper> wrapperRightPart = subtreeWrapper; updateSubtreeWrapper( new IRTree::CStatementWrapper( new CMoveStatement( wrapperLeftPart.ToExpression(), wrapperRightPart.ToExpression() ) ) ); onNodeExit( nodeName ); } void CIrtBuilderVisitor::Visit( const CAssignIdWithIndexStatement* statement ) { std::string nodeName = generateNodeName( CAstNodeNames::STAT_ASSIGN_ID_WITH_INDEX ); onNodeEnter( nodeName ); // write your code here onNodeExit( nodeName ); } void CIrtBuilderVisitor::Visit( const CPrintStatement* statement ) { std::string nodeName = generateNodeName( CAstNodeNames::STAT_PRINT ); onNodeEnter( nodeName ); // write your code here onNodeExit( nodeName ); } void CIrtBuilderVisitor::Visit( const CConditionalStatement* statement ) { std::string nodeName = generateNodeName( CAstNodeNames::STAT_CONDITIONAL ); onNodeEnter( nodeName ); statement->Condition()->Accept( this ); std::unique_ptr<const IRTree::ISubtreeWrapper> wrapperCondition = subtreeWrapper; statement->PositiveTarget()->Accept( this ); std::unique_ptr<const IRTree::ISubtreeWrapper> wrapperTargetPositive = subtreeWrapper; statement->NegativeTarget()->Accept( this ); std::unique_ptr<const IRTree::ISubtreeWrapper> wrapperTargetNegative = subtreeWrapper; IRTree::CLabel labelTrue; IRTree::CLabel labelFalse; IRTree::CLabel labelJoin; updateSubtreeWrapper( new IRTree::CStatementWrapper( new IRTree::CSeqStatement( wrapperCondition->ToCondition( labelTrue, labelFalse ), new IRTree::CSeqStatement( new IRTree::CLabelStatement( labelTrue ), new IRTree::CSeqStatement( wrapperTargetPositive->ToStatement(), new IRTree::CSeqStatement( new IRTree::CJumpStatement( labelJoin ), new IRTree::CSeqStatement( new IRTree::CLabelStatement( labelFalse ), new IRTree::CSeqStatement( wrapperTargetNegative->ToStatement(), new IRTree::CLabelStatement( IRTree::CLabel() ) ) ) ) ) ) ) ) ); onNodeExit( nodeName ); } void CIrtBuilderVisitor::Visit( const CWhileLoopStatement* statement ) { std::string nodeName = generateNodeName( CAstNodeNames::STAT_WHILE_LOOP ); onNodeEnter( nodeName ); statement->Condition()->Accept( this ); std::unique_ptr<const IRTree::ISubtreeWrapper> wrapperCondition = subtreeWrapper; statement->Body()->Accept( this ); std::unique_ptr<const IRTree::ISubtreeWrapper> wrapperBody = subtreeWrapper; IRTree::CLabel labelLoop; IRTree::CLabel labelBody; IRTree::CLabel labelDone; updateSubtreeWrapper( new IRTree::CStatementWrapper( new IRTree::CSeqStatement( new IRTree::CLabelStatement( labelLoop ), new IRTree::CSeqStatement( wrapperCondition->ToCondition( labelBody, labelDone ), new IRTree::CSeqStatement( new IRTree::CLabelStatement( labelBody ), new IRTree::CSeqStatement( wrapperBody->ToStatement(), new IRTree::CSeqStatement( new IRTree::CJumpStatement( labelLoop ), new IRTree::CLabelStatement( labelDone ) ) ) ) ) ) ) ); onNodeExit( nodeName ); } void CIrtBuilderVisitor::Visit( const CBracesStatement* statement ) { std::string nodeName = generateNodeName( CAstNodeNames::STAT_BRACES ); onNodeEnter( nodeName ); statement->List()->Accept( this ); onNodeExit( nodeName ); } /*__________ Type Modifiers __________*/ void CIrtBuilderVisitor::Visit( const CIntTypeModifier* typeModifier ) { std::string nodeName = generateNodeName( CAstNodeNames::TYPE_MOD_INT ); onNodeEnter( nodeName ); // write your code here onNodeExit( nodeName ); } void CIrtBuilderVisitor::Visit( const CBooleanTypeModifier* typeModifier ) { std::string nodeName = generateNodeName( CAstNodeNames::TYPE_MOD_BOOL ); onNodeEnter( nodeName ); // write your code here onNodeExit( nodeName ); } void CIrtBuilderVisitor::Visit( const CIntArrayTypeModifier* typeModifier ) { std::string nodeName = generateNodeName( CAstNodeNames::TYPE_MOD_INT_ARRAY ); onNodeEnter( nodeName ); // write your code here onNodeExit( nodeName ); } void CIrtBuilderVisitor::Visit( const CIdTypeModifier* typeModifier ) { std::string nodeName = generateNodeName( CAstNodeNames::TYPE_MOD_ID ); onNodeEnter( nodeName ); // write your code here onNodeExit( nodeName ); } /*__________ Other (except lists) __________*/ void CIrtBuilderVisitor::Visit( const CVarDeclaration* declaration ) { std::string nodeName = generateNodeName( CAstNodeNames::VAR_DECL ); onNodeEnter( nodeName ); // write your code here onNodeExit( nodeName ); } void CIrtBuilderVisitor::Visit( const CMethodArgument* argument ) { std::string nodeName = generateNodeName( CAstNodeNames::METH_ARG ); onNodeEnter( nodeName ); // write your code here onNodeExit( nodeName ); } void CIrtBuilderVisitor::Visit( const CMethodDeclaration* declaration ) { std::string nodeName = generateNodeName( CAstNodeNames::METH_DECL ); onNodeEnter( nodeName ); // write your code here onNodeExit( nodeName ); } void CIrtBuilderVisitor::Visit( const CMainClass* mainClass ) { std::string nodeName = generateNodeName( CAstNodeNames::MAIN_CLASS ); onNodeEnter( nodeName ); // write your code here onNodeExit( nodeName ); } void CIrtBuilderVisitor::Visit( const CClassDeclaration* declaration ) { std::string nodeName = generateNodeName( CAstNodeNames::CLASS_DECL ); onNodeEnter( nodeName ); // write your code here onNodeExit( nodeName ); } void CIrtBuilderVisitor::Visit( const CProgram* program ) { std::string nodeName = generateNodeName( CAstNodeNames::PROGRAM ); onNodeEnter( nodeName ); // write your code here onNodeExit( nodeName ); } /*__________ Lists __________*/ void CIrtBuilderVisitor::Visit( const CExpressionList* list ) { std::string nodeName = generateNodeName( CAstNodeNames::EXP_LIST ); onNodeEnter( nodeName ); // write your code here onNodeExit( nodeName ); } void CIrtBuilderVisitor::Visit( const CStatementList* list ) { std::string nodeName = generateNodeName( CAstNodeNames::STAT_LIST ); onNodeEnter( nodeName ); // write your code here onNodeExit( nodeName ); } void CIrtBuilderVisitor::Visit( const CVarDeclarationList* list ) { std::string nodeName = generateNodeName( CAstNodeNames::VAR_DECL_LIST ); onNodeEnter( nodeName ); // write your code here onNodeExit( nodeName ); } void CIrtBuilderVisitor::Visit( const CMethodArgumentList* list ) { std::string nodeName = generateNodeName( CAstNodeNames::METH_ARG_LIST ); onNodeEnter( nodeName ); // write your code here onNodeExit( nodeName ); } void CIrtBuilderVisitor::Visit( const CMethodDeclarationList* list ) { std::string nodeName = generateNodeName( CAstNodeNames::METH_DECL_LIST ); onNodeEnter( nodeName ); // write your code here onNodeExit( nodeName ); } void CIrtBuilderVisitor::Visit( const CClassDeclarationList* list ) { std::string nodeName = generateNodeName( CAstNodeNames::CLASS_DECL_LIST ); onNodeEnter( nodeName ); // write your code here onNodeExit( nodeName ); } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: txtparai.hxx,v $ * * $Revision: 1.7 $ * * last change: $Author: rt $ $Date: 2005-11-08 17:06:34 $ * * 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 _XMLOFF_TEXTPARAI_HXX_ #define _XMLOFF_TEXTPARAI_HXX_ #ifndef _COM_SUN_STAR_UNO_REFERENCE_H_ #include <com/sun/star/uno/Reference.h> #endif #ifndef _XMLOFF_XMLICTXT_HXX #include "xmlictxt.hxx" #endif class XMLHints_Impl; namespace com { namespace sun { namespace star { namespace text { class XTextRange; } namespace xml { namespace sax { class XAttributeList; } } } } } #ifdef CONV_STAR_FONTS #define CONV_FROM_STAR_BATS 1 #define CONV_FROM_STAR_MATH 2 #define CONV_STAR_FONT_FLAGS_VALID 4 #endif class XMLParaContext : public SvXMLImportContext { ::com::sun::star::uno::Reference < ::com::sun::star::text::XTextRange > xStart; // xub_StrLen nStart; ::rtl::OUString sStyleName; ::rtl::OUString sId; sal_Int8 nOutlineLevel; XMLHints_Impl *pHints; sal_Bool bIgnoreLeadingSpace; sal_Bool bHeading; sal_Bool bIsListHeader; sal_Bool bIsRestart; sal_Int16 nStartValue; #ifdef CONV_STAR_FONTS sal_uInt8 nStarFontsConvFlags; #endif public: TYPEINFO(); XMLParaContext( SvXMLImport& rImport, sal_uInt16 nPrfx, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > & xAttrList, sal_Bool bHeading ); virtual ~XMLParaContext(); virtual SvXMLImportContext *CreateChildContext( sal_uInt16 nPrefix, const ::rtl::OUString& rLocalName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > & xAttrList ); virtual void Characters( const ::rtl::OUString& rChars ); }; #endif <commit_msg>INTEGRATION: CWS knumber (1.6.42); FILE MERGED 2005/11/14 08:58:53 flr 1.6.42.1: #i52127# implement first step of numbered-paragraph<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: txtparai.hxx,v $ * * $Revision: 1.8 $ * * last change: $Author: rt $ $Date: 2005-11-14 09:10:47 $ * * 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 _XMLOFF_TEXTPARAI_HXX_ #define _XMLOFF_TEXTPARAI_HXX_ #ifndef _COM_SUN_STAR_UNO_REFERENCE_H_ #include <com/sun/star/uno/Reference.h> #endif #ifndef _XMLOFF_XMLICTXT_HXX #include "xmlictxt.hxx" #endif class XMLHints_Impl; namespace com { namespace sun { namespace star { namespace text { class XTextRange; } namespace xml { namespace sax { class XAttributeList; } } } } } #ifdef CONV_STAR_FONTS #define CONV_FROM_STAR_BATS 1 #define CONV_FROM_STAR_MATH 2 #define CONV_STAR_FONT_FLAGS_VALID 4 #endif class XMLParaContext : public SvXMLImportContext { ::com::sun::star::uno::Reference < ::com::sun::star::text::XTextRange > xStart; // xub_StrLen nStart; ::rtl::OUString sStyleName; ::rtl::OUString sId; sal_Int8 nOutlineLevel; XMLHints_Impl *pHints; sal_Bool bIgnoreLeadingSpace; sal_Bool bHeading; sal_Bool bIsListHeader; sal_Bool bIsRestart; sal_Int16 nStartValue; #ifdef CONV_STAR_FONTS sal_uInt8 nStarFontsConvFlags; #endif public: TYPEINFO(); XMLParaContext( SvXMLImport& rImport, sal_uInt16 nPrfx, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > & xAttrList, sal_Bool bHeading ); virtual ~XMLParaContext(); virtual SvXMLImportContext *CreateChildContext( sal_uInt16 nPrefix, const ::rtl::OUString& rLocalName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > & xAttrList ); virtual void Characters( const ::rtl::OUString& rChars ); }; class XMLNumberedParaContext : public SvXMLImportContext { public: TYPEINFO(); XMLNumberedParaContext( SvXMLImport& rImport, sal_uInt16 nPrfx, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > & xAttrList ); virtual ~XMLNumberedParaContext(); virtual SvXMLImportContext *CreateChildContext( sal_uInt16 nPrefix, const ::rtl::OUString& rLocalName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > & xAttrList ); virtual void Characters( const ::rtl::OUString& rChars ); }; #endif <|endoftext|>
<commit_before>/*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include <mitkLabelSet.h> #include <mitkLabelSetImage.h> #include <mitkStringProperty.h> #include <mitkTestFixture.h> #include <mitkTestingMacros.h> class mitkLabelSetTestSuite : public mitk::TestFixture { CPPUNIT_TEST_SUITE(mitkLabelSetTestSuite); MITK_TEST(TestSetLayer); MITK_TEST(TestSetActiveLabel); MITK_TEST(TestRemoveLabel); MITK_TEST(TestAddLabel); MITK_TEST(TestRenameLabel); MITK_TEST(TestSetAllLabelsVisible); MITK_TEST(TestSetAllLabelsLocked); MITK_TEST(TestRemoveAllLabels); CPPUNIT_TEST_SUITE_END(); private: mitk::LabelSet::Pointer m_LabelSet; mitk::LabelSet::PixelType m_InitialNumberOfLabels; void AddLabels(mitk::LabelSet::PixelType numOfLabels) { mitk::Label::Pointer label; const std::string namePrefix = "Label_"; const mitk::Color gray(0.5f); for (mitk::Label::PixelType i = 0; i < numOfLabels; ++i) { label = mitk::Label::New(); label->SetName(namePrefix + std::to_string(i)); label->SetValue(i); label->SetVisible((i % 2 == 0)); label->SetLayer(i % 3); label->SetColor(gray); m_LabelSet->AddLabel(label); } } public: void setUp() override { m_InitialNumberOfLabels = 6; m_LabelSet = mitk::LabelSet::New(); this->AddLabels(m_InitialNumberOfLabels); m_LabelSet->SetLayer(0); m_LabelSet->SetActiveLabel(0); } void tearDown() override { m_LabelSet = nullptr; } void TestSetLayer() { CPPUNIT_ASSERT_MESSAGE("Wrong initial layer", m_LabelSet->GetLayer() == 0); m_LabelSet->SetLayer(1); CPPUNIT_ASSERT_MESSAGE("Wrong layer", m_LabelSet->GetLayer() == 1); } void TestSetActiveLabel() { CPPUNIT_ASSERT_MESSAGE("Wrong initial active label", m_LabelSet->GetActiveLabel()->GetValue() == 0); m_LabelSet->SetActiveLabel(1); CPPUNIT_ASSERT_MESSAGE("Wrong layer", m_LabelSet->GetActiveLabel()->GetValue() == 1); } void TestRemoveLabel() { CPPUNIT_ASSERT_MESSAGE("Wrong initial number of label", m_LabelSet->GetNumberOfLabels() == m_InitialNumberOfLabels); // Remove a label that is not the active label m_LabelSet->SetActiveLabel(2); m_LabelSet->RemoveLabel(1); mitk::LabelSet::PixelType numLabels = m_InitialNumberOfLabels - 1; CPPUNIT_ASSERT_MESSAGE("Label was not removed", m_LabelSet->ExistLabel(1) == false); CPPUNIT_ASSERT_MESSAGE("Wrong number of label", m_LabelSet->GetNumberOfLabels() == numLabels); CPPUNIT_ASSERT_MESSAGE("Wrong active label", m_LabelSet->GetActiveLabel()->GetValue() == 2); // Remove active label - now the succeeding label should be active m_LabelSet->RemoveLabel(2); CPPUNIT_ASSERT_MESSAGE("Wrong layer", m_LabelSet->GetActiveLabel()->GetValue() == 3); CPPUNIT_ASSERT_MESSAGE("Label was not removed", m_LabelSet->ExistLabel(2) == false); CPPUNIT_ASSERT_MESSAGE("Wrong initial number of label", m_LabelSet->GetNumberOfLabels() == --numLabels); } void TestAddLabel() { auto newLabel = mitk::Label::New(); newLabel->SetValue(1); m_LabelSet->AddLabel(newLabel); // Since label with value 1 already exists the new label will get the value m_InitialNumberOfValues CPPUNIT_ASSERT_MESSAGE("Wrong label value", m_LabelSet->GetActiveLabel()->GetValue() == m_InitialNumberOfLabels); CPPUNIT_ASSERT_MESSAGE("Wrong number of label", m_LabelSet->GetNumberOfLabels() == m_InitialNumberOfLabels + 1); } void TestRenameLabel() { const mitk::Color white(1.0f); const std::string name = "MyAwesomeLabel"; m_LabelSet->RenameLabel(0, name, white); const auto* label = m_LabelSet->GetLabel(0); CPPUNIT_ASSERT_MESSAGE("Wrong label name", label->GetName() == name ); const auto& color = label->GetColor(); CPPUNIT_ASSERT_MESSAGE("Wrong color", color == white); } void TestSetAllLabelsVisible() { const auto numLabels = static_cast<mitk::LabelSet::PixelType>(m_LabelSet->GetNumberOfLabels()); m_LabelSet->SetAllLabelsVisible(true); for (mitk::LabelSet::PixelType i = 0; i < numLabels; ++i) CPPUNIT_ASSERT_MESSAGE("Label not visible", m_LabelSet->GetLabel(i)->GetVisible() == true); m_LabelSet->SetAllLabelsVisible(false); for (mitk::LabelSet::PixelType i = 0; i < numLabels; ++i) CPPUNIT_ASSERT_MESSAGE("Label visible", m_LabelSet->GetLabel(i)->GetVisible() == false); } void TestSetAllLabelsLocked() { const auto numLabels = static_cast<mitk::LabelSet::PixelType>(m_LabelSet->GetNumberOfLabels()); m_LabelSet->SetAllLabelsLocked(true); for (mitk::LabelSet::PixelType i = 0; i < numLabels; ++i) CPPUNIT_ASSERT_MESSAGE("Label not locked", m_LabelSet->GetLabel(i)->GetLocked() == true); m_LabelSet->SetAllLabelsLocked(false); for (mitk::LabelSet::PixelType i = 0; i < numLabels; ++i) CPPUNIT_ASSERT_MESSAGE("Label locked", m_LabelSet->GetLabel(i)->GetLocked() == false); } void TestRemoveAllLabels() { m_LabelSet->RemoveAllLabels(); CPPUNIT_ASSERT_MESSAGE("Not all labels were removed", m_LabelSet->GetNumberOfLabels() == 0); } }; MITK_TEST_SUITE_REGISTRATION(mitkLabelSet) <commit_msg>Fix comparison between signed and unsigned integers<commit_after>/*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include <mitkLabelSet.h> #include <mitkLabelSetImage.h> #include <mitkStringProperty.h> #include <mitkTestFixture.h> #include <mitkTestingMacros.h> class mitkLabelSetTestSuite : public mitk::TestFixture { CPPUNIT_TEST_SUITE(mitkLabelSetTestSuite); MITK_TEST(TestSetLayer); MITK_TEST(TestSetActiveLabel); MITK_TEST(TestRemoveLabel); MITK_TEST(TestAddLabel); MITK_TEST(TestRenameLabel); MITK_TEST(TestSetAllLabelsVisible); MITK_TEST(TestSetAllLabelsLocked); MITK_TEST(TestRemoveAllLabels); CPPUNIT_TEST_SUITE_END(); private: mitk::LabelSet::Pointer m_LabelSet; mitk::LabelSet::PixelType m_InitialNumberOfLabels; void AddLabels(mitk::LabelSet::PixelType numOfLabels) { mitk::Label::Pointer label; const std::string namePrefix = "Label_"; const mitk::Color gray(0.5f); for (mitk::Label::PixelType i = 0; i < numOfLabels; ++i) { label = mitk::Label::New(); label->SetName(namePrefix + std::to_string(i)); label->SetValue(i); label->SetVisible((i % 2 == 0)); label->SetLayer(i % 3); label->SetColor(gray); m_LabelSet->AddLabel(label); } } public: void setUp() override { m_InitialNumberOfLabels = 6; m_LabelSet = mitk::LabelSet::New(); this->AddLabels(m_InitialNumberOfLabels); m_LabelSet->SetLayer(0); m_LabelSet->SetActiveLabel(0); } void tearDown() override { m_LabelSet = nullptr; } void TestSetLayer() { CPPUNIT_ASSERT_MESSAGE("Wrong initial layer", m_LabelSet->GetLayer() == 0); m_LabelSet->SetLayer(1); CPPUNIT_ASSERT_MESSAGE("Wrong layer", m_LabelSet->GetLayer() == 1); } void TestSetActiveLabel() { CPPUNIT_ASSERT_MESSAGE("Wrong initial active label", m_LabelSet->GetActiveLabel()->GetValue() == 0); m_LabelSet->SetActiveLabel(1); CPPUNIT_ASSERT_MESSAGE("Wrong layer", m_LabelSet->GetActiveLabel()->GetValue() == 1); } void TestRemoveLabel() { CPPUNIT_ASSERT_MESSAGE("Wrong initial number of label", m_LabelSet->GetNumberOfLabels() == m_InitialNumberOfLabels); // Remove a label that is not the active label m_LabelSet->SetActiveLabel(2); m_LabelSet->RemoveLabel(1); mitk::LabelSet::PixelType numLabels = m_InitialNumberOfLabels - 1; CPPUNIT_ASSERT_MESSAGE("Label was not removed", m_LabelSet->ExistLabel(1) == false); CPPUNIT_ASSERT_MESSAGE("Wrong number of label", m_LabelSet->GetNumberOfLabels() == numLabels); CPPUNIT_ASSERT_MESSAGE("Wrong active label", m_LabelSet->GetActiveLabel()->GetValue() == 2); // Remove active label - now the succeeding label should be active m_LabelSet->RemoveLabel(2); CPPUNIT_ASSERT_MESSAGE("Wrong layer", m_LabelSet->GetActiveLabel()->GetValue() == 3); CPPUNIT_ASSERT_MESSAGE("Label was not removed", m_LabelSet->ExistLabel(2) == false); CPPUNIT_ASSERT_MESSAGE("Wrong initial number of label", m_LabelSet->GetNumberOfLabels() == --numLabels); } void TestAddLabel() { auto newLabel = mitk::Label::New(); newLabel->SetValue(1); m_LabelSet->AddLabel(newLabel); // Since label with value 1 already exists the new label will get the value m_InitialNumberOfValues CPPUNIT_ASSERT_MESSAGE("Wrong label value", m_LabelSet->GetActiveLabel()->GetValue() == m_InitialNumberOfLabels); CPPUNIT_ASSERT_MESSAGE("Wrong number of label", m_LabelSet->GetNumberOfLabels() == static_cast<decltype(m_LabelSet->GetNumberOfLabels())>(m_InitialNumberOfLabels + 1)); } void TestRenameLabel() { const mitk::Color white(1.0f); const std::string name = "MyAwesomeLabel"; m_LabelSet->RenameLabel(0, name, white); const auto* label = m_LabelSet->GetLabel(0); CPPUNIT_ASSERT_MESSAGE("Wrong label name", label->GetName() == name ); const auto& color = label->GetColor(); CPPUNIT_ASSERT_MESSAGE("Wrong color", color == white); } void TestSetAllLabelsVisible() { const auto numLabels = static_cast<mitk::LabelSet::PixelType>(m_LabelSet->GetNumberOfLabels()); m_LabelSet->SetAllLabelsVisible(true); for (mitk::LabelSet::PixelType i = 0; i < numLabels; ++i) CPPUNIT_ASSERT_MESSAGE("Label not visible", m_LabelSet->GetLabel(i)->GetVisible() == true); m_LabelSet->SetAllLabelsVisible(false); for (mitk::LabelSet::PixelType i = 0; i < numLabels; ++i) CPPUNIT_ASSERT_MESSAGE("Label visible", m_LabelSet->GetLabel(i)->GetVisible() == false); } void TestSetAllLabelsLocked() { const auto numLabels = static_cast<mitk::LabelSet::PixelType>(m_LabelSet->GetNumberOfLabels()); m_LabelSet->SetAllLabelsLocked(true); for (mitk::LabelSet::PixelType i = 0; i < numLabels; ++i) CPPUNIT_ASSERT_MESSAGE("Label not locked", m_LabelSet->GetLabel(i)->GetLocked() == true); m_LabelSet->SetAllLabelsLocked(false); for (mitk::LabelSet::PixelType i = 0; i < numLabels; ++i) CPPUNIT_ASSERT_MESSAGE("Label locked", m_LabelSet->GetLabel(i)->GetLocked() == false); } void TestRemoveAllLabels() { m_LabelSet->RemoveAllLabels(); CPPUNIT_ASSERT_MESSAGE("Not all labels were removed", m_LabelSet->GetNumberOfLabels() == 0); } }; MITK_TEST_SUITE_REGISTRATION(mitkLabelSet) <|endoftext|>
<commit_before>/* * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES) * * This file is part of Orfeo Toolbox * * https://www.orfeo-toolbox.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 "otbWrapperChoiceParameter.h" #include "otbWrapperListViewParameter.h" #include "otbWrapperBoolParameter.h" #include "otbWrapperApplicationRegistry.h" #include "otbWrapperTypes.h" #include "otbWrapperApplication.h" #include <vector> #include <string> #include <iostream> #include <cassert> #include <fstream> int main(int argc, char* argv[]) { if (argc < 3) { std::cerr << "Usage : " << argv[0] << " name OTB_APPLICATION_PATH [out_dir]" << std::endl; return EXIT_FAILURE; } using namespace otb::Wrapper; const std::string module(argv[1]); /* TestApplication is removed in CMakeLists.txt */ #if 0 if (module == "TestApplication") return EXIT_SUCCESS; #endif ApplicationRegistry::AddApplicationPath(argv[2]); Application::Pointer appli = ApplicationRegistry::CreateApplicationFaster(module.c_str()); assert(!appli.IsNull()); std::map<ParameterType, std::string> parameterTypeToString; parameterTypeToString[ParameterType_Empty] = "QgsProcessingParameterBoolean"; parameterTypeToString[ParameterType_Bool] = "QgsProcessingParameterBoolean"; parameterTypeToString[ParameterType_Int] = "QgsProcessingParameterNumber"; parameterTypeToString[ParameterType_Float] = "QgsProcessingParameterNumber"; parameterTypeToString[ParameterType_RAM] = "QgsProcessingParameterNumber"; parameterTypeToString[ParameterType_Radius] = "QgsProcessingParameterNumber"; parameterTypeToString[ParameterType_Choice] = "OTBParameterChoice"; parameterTypeToString[ParameterType_String] = "QgsProcessingParameterString"; parameterTypeToString[ParameterType_InputImage] = "QgsProcessingParameterRasterLayer"; parameterTypeToString[ParameterType_InputFilename] = "QgsProcessingParameterFile"; parameterTypeToString[ParameterType_InputImageList] = "QgsProcessingParameterMultipleLayers"; parameterTypeToString[ParameterType_InputVectorData] = "QgsProcessingParameterVectorLayer"; parameterTypeToString[ParameterType_InputFilenameList] = "QgsProcessingParameterMultipleLayers"; parameterTypeToString[ParameterType_InputVectorDataList] = "QgsProcessingParameterMultipleLayers"; parameterTypeToString[ParameterType_OutputImage] = "QgsProcessingParameterRasterDestination"; parameterTypeToString[ParameterType_OutputVectorData] = "QgsProcessingParameterVectorDestination"; parameterTypeToString[ParameterType_OutputFilename] = "QgsProcessingParameterFileDestination"; parameterTypeToString[ParameterType_Directory] = "QgsProcessingParameterFile"; //TODO parameterTypeToString[ParameterType_StringList] = "QgsProcessingParameterString"; //ListView parameters are treated as plain string (QLineEdit) in qgis processing ui. //This seems rather unpleasant when comparing Qgis processing with Monteverdi/Mapla in OTB //We tried to push something simple with checkboxes but its too risky for this version //and clock is ticking... // parameterTypeToString[ParameterType_ListView] = "QgsProcessingParameterString"; //For next update of plugin code ListView should use a custom widget wrapper and behave //exactly like OTB Mapla. And this #if 0 block is our TODO remainder. #if 0 parameterTypeToString[ParameterType_ListView] = "OTBParameterListView"; #endif const std::vector<std::string> appKeyList = appli->GetParametersKeys(true); const unsigned int nbOfParam = appKeyList.size(); std::string output_file = module + ".txt"; std::string algs_txt = "algs.txt"; if (argc > 3) { output_file = std::string(argv[3]) + module + ".txt"; algs_txt = std::string(argv[3]) + "algs.txt"; } std::ofstream dFile; dFile.open (output_file, std::ios::out); std::cerr << "Writing " << output_file << std::endl; std::string output_parameter_name; bool hasRasterOutput = false; { for (unsigned int i = 0; i < nbOfParam; i++) { Parameter::Pointer param = appli->GetParameterByKey(appKeyList[i]); if (param->GetMandatory()) { ParameterType type = appli->GetParameterType(appKeyList[i]); if (type == ParameterType_OutputImage ) { output_parameter_name = appKeyList[i]; hasRasterOutput = true; } } } } if(output_parameter_name.empty()) dFile << module << std::endl; else dFile << module << "|" << output_parameter_name << std::endl; dFile << appli->GetDescription() << std::endl; const std::string group = appli->GetDocTags().size() > 0 ? appli->GetDocTags()[0] : "UNCLASSIFIED"; dFile << group << std::endl; for (unsigned int i = 0; i < nbOfParam; i++) { const std::string name = appKeyList[i]; Parameter::Pointer param = appli->GetParameterByKey(name); ParameterType type = appli->GetParameterType(name); const std::string description = param->GetName(); std::string qgis_type = parameterTypeToString[type]; #if 0 if (type == ParameterType_ListView) { ListViewParameter *lv_param = dynamic_cast<ListViewParameter*>(param.GetPointer()); std::cerr << "lv_param->GetSingleSelection()" << lv_param->GetSingleSelection() << std::endl; if (lv_param->GetSingleSelection()) { qgis_type = "QgsProcessingParameterEnum"; std::vector<std::string> key_list = appli->GetChoiceKeys(name); std::string values = ""; for( auto k : key_list) values += k + ";"; values.pop_back(); dFile << "|" << values ; } } #endif if ( type == ParameterType_Group || type == ParameterType_OutputProcessXML || type == ParameterType_InputProcessXML || type == ParameterType_RAM ) { // group parameter cannot have any value. //outxml and inxml parameters are not relevant for QGIS and is considered a bit noisy //ram is added by qgis-otb processing provider plugin as an advanced parameter for all apps continue; } assert(!qgis_type.empty()); if(qgis_type.empty()) { std::cerr << "No mapping found for parameter '" <<name <<"' type=" << type << std::endl; return EXIT_FAILURE; } bool isDestination = false; dFile << qgis_type << "|" << name << "|" << description; std::string default_value = "None"; if (type == ParameterType_Int) { dFile << "|QgsProcessingParameterNumber.Integer"; default_value = param->HasValue() ? appli->GetParameterAsString(name): "0"; } else if (type == ParameterType_Float) { dFile << "|QgsProcessingParameterNumber.Double"; default_value = param->HasValue() ? appli->GetParameterAsString(name): "0"; } else if (type == ParameterType_Radius) { dFile << "|QgsProcessingParameterNumber.Integer"; default_value = param->HasValue() ? appli->GetParameterAsString(name): "0"; } else if(type == ParameterType_InputFilename) { dFile << "|QgsProcessingParameterFile.File|txt"; } else if(type == ParameterType_Directory) { dFile << "|QgsProcessingParameterFile.Folder|False"; } else if (type == ParameterType_InputImageList) { dFile << "|3"; } else if (type == ParameterType_InputVectorDataList) { dFile << "|-1"; } else if (type == ParameterType_InputVectorData) { dFile << "|-1"; } else if(type == ParameterType_InputFilenameList) { dFile << "|4"; } else if (type == ParameterType_InputImage) { //default is None and nothing to add to dFile } else if(type ==ParameterType_String) { //default is None and nothing to add to dFile } else if(type ==ParameterType_StringList) { //default is None and nothing to add to dFile } else if(type ==ParameterType_ListView) { //default is None and nothing to add to dFile } else if(type == ParameterType_Bool) { default_value = appli->GetParameterAsString(name); } else if(type == ParameterType_Choice) { std::vector<std::string> key_list = appli->GetChoiceKeys(name); std::string values = ""; for( auto k : key_list) values += k + ";"; values.pop_back(); dFile << "|" << values ; ChoiceParameter *cparam = dynamic_cast<ChoiceParameter*>(param.GetPointer()); default_value = std::to_string(cparam->GetValue()); } else if(type == ParameterType_OutputVectorData || type == ParameterType_OutputImage || type == ParameterType_OutputFilename) { //no need for default_value, optional and extra fields in dFile //if parameter is a destination type. qgis_type|name|description is enough. //so we simply set isDestination to true and skip to end to append a new line. isDestination = true; } else { std::cout << "ERROR: default_value is empty for '" << name << "' type='" << qgis_type << "'" << std::endl; return EXIT_FAILURE; } if (!isDestination) { //const char* optional = param->GetMandatory() ? "False" : "True"; std::string optional; if (param->GetMandatory()) if (param->HasValue()) { optional = "True"; } else{ optional = "False"; } else { optional = "True"; } dFile << "|" << default_value << "|" << optional; } dFile << std::endl; } dFile.close(); std::ofstream indexFile; indexFile.open (algs_txt, std::ios::out | std::ios::app ); indexFile << group << "|" << module << std::endl; indexFile.close(); return EXIT_SUCCESS; } <commit_msg>BUG: stringlist is optional even if no default<commit_after>/* * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES) * * This file is part of Orfeo Toolbox * * https://www.orfeo-toolbox.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 "otbWrapperChoiceParameter.h" #include "otbWrapperListViewParameter.h" #include "otbWrapperBoolParameter.h" #include "otbWrapperApplicationRegistry.h" #include "otbWrapperTypes.h" #include "otbWrapperApplication.h" #include <vector> #include <string> #include <iostream> #include <cassert> #include <fstream> int main(int argc, char* argv[]) { if (argc < 3) { std::cerr << "Usage : " << argv[0] << " name OTB_APPLICATION_PATH [out_dir]" << std::endl; return EXIT_FAILURE; } using namespace otb::Wrapper; const std::string module(argv[1]); /* TestApplication is removed in CMakeLists.txt */ #if 0 if (module == "TestApplication") return EXIT_SUCCESS; #endif ApplicationRegistry::AddApplicationPath(argv[2]); Application::Pointer appli = ApplicationRegistry::CreateApplicationFaster(module.c_str()); assert(!appli.IsNull()); std::map<ParameterType, std::string> parameterTypeToString; parameterTypeToString[ParameterType_Empty] = "QgsProcessingParameterBoolean"; parameterTypeToString[ParameterType_Bool] = "QgsProcessingParameterBoolean"; parameterTypeToString[ParameterType_Int] = "QgsProcessingParameterNumber"; parameterTypeToString[ParameterType_Float] = "QgsProcessingParameterNumber"; parameterTypeToString[ParameterType_RAM] = "QgsProcessingParameterNumber"; parameterTypeToString[ParameterType_Radius] = "QgsProcessingParameterNumber"; parameterTypeToString[ParameterType_Choice] = "OTBParameterChoice"; parameterTypeToString[ParameterType_String] = "QgsProcessingParameterString"; parameterTypeToString[ParameterType_InputImage] = "QgsProcessingParameterRasterLayer"; parameterTypeToString[ParameterType_InputFilename] = "QgsProcessingParameterFile"; parameterTypeToString[ParameterType_InputImageList] = "QgsProcessingParameterMultipleLayers"; parameterTypeToString[ParameterType_InputVectorData] = "QgsProcessingParameterVectorLayer"; parameterTypeToString[ParameterType_InputFilenameList] = "QgsProcessingParameterMultipleLayers"; parameterTypeToString[ParameterType_InputVectorDataList] = "QgsProcessingParameterMultipleLayers"; parameterTypeToString[ParameterType_OutputImage] = "QgsProcessingParameterRasterDestination"; parameterTypeToString[ParameterType_OutputVectorData] = "QgsProcessingParameterVectorDestination"; parameterTypeToString[ParameterType_OutputFilename] = "QgsProcessingParameterFileDestination"; parameterTypeToString[ParameterType_Directory] = "QgsProcessingParameterFile"; //TODO parameterTypeToString[ParameterType_StringList] = "QgsProcessingParameterString"; //ListView parameters are treated as plain string (QLineEdit) in qgis processing ui. //This seems rather unpleasant when comparing Qgis processing with Monteverdi/Mapla in OTB //We tried to push something simple with checkboxes but its too risky for this version //and clock is ticking... // parameterTypeToString[ParameterType_ListView] = "QgsProcessingParameterString"; //For next update of plugin code ListView should use a custom widget wrapper and behave //exactly like OTB Mapla. And this #if 0 block is our TODO remainder. #if 0 parameterTypeToString[ParameterType_ListView] = "OTBParameterListView"; #endif const std::vector<std::string> appKeyList = appli->GetParametersKeys(true); const unsigned int nbOfParam = appKeyList.size(); std::string output_file = module + ".txt"; std::string algs_txt = "algs.txt"; if (argc > 3) { output_file = std::string(argv[3]) + module + ".txt"; algs_txt = std::string(argv[3]) + "algs.txt"; } std::ofstream dFile; dFile.open (output_file, std::ios::out); std::cerr << "Writing " << output_file << std::endl; std::string output_parameter_name; bool hasRasterOutput = false; { for (unsigned int i = 0; i < nbOfParam; i++) { Parameter::Pointer param = appli->GetParameterByKey(appKeyList[i]); if (param->GetMandatory()) { ParameterType type = appli->GetParameterType(appKeyList[i]); if (type == ParameterType_OutputImage ) { output_parameter_name = appKeyList[i]; hasRasterOutput = true; } } } } if(output_parameter_name.empty()) dFile << module << std::endl; else dFile << module << "|" << output_parameter_name << std::endl; dFile << appli->GetDescription() << std::endl; const std::string group = appli->GetDocTags().size() > 0 ? appli->GetDocTags()[0] : "UNCLASSIFIED"; dFile << group << std::endl; for (unsigned int i = 0; i < nbOfParam; i++) { const std::string name = appKeyList[i]; Parameter::Pointer param = appli->GetParameterByKey(name); ParameterType type = appli->GetParameterType(name); const std::string description = param->GetName(); std::string qgis_type = parameterTypeToString[type]; #if 0 if (type == ParameterType_ListView) { ListViewParameter *lv_param = dynamic_cast<ListViewParameter*>(param.GetPointer()); std::cerr << "lv_param->GetSingleSelection()" << lv_param->GetSingleSelection() << std::endl; if (lv_param->GetSingleSelection()) { qgis_type = "QgsProcessingParameterEnum"; std::vector<std::string> key_list = appli->GetChoiceKeys(name); std::string values = ""; for( auto k : key_list) values += k + ";"; values.pop_back(); dFile << "|" << values ; } } #endif if ( type == ParameterType_Group || type == ParameterType_OutputProcessXML || type == ParameterType_InputProcessXML || type == ParameterType_RAM ) { // group parameter cannot have any value. //outxml and inxml parameters are not relevant for QGIS and is considered a bit noisy //ram is added by qgis-otb processing provider plugin as an advanced parameter for all apps continue; } assert(!qgis_type.empty()); if(qgis_type.empty()) { std::cerr << "No mapping found for parameter '" <<name <<"' type=" << type << std::endl; return EXIT_FAILURE; } bool isDestination = false; dFile << qgis_type << "|" << name << "|" << description; std::string default_value = "None"; if (type == ParameterType_Int) { dFile << "|QgsProcessingParameterNumber.Integer"; default_value = param->HasValue() ? appli->GetParameterAsString(name): "0"; } else if (type == ParameterType_Float) { dFile << "|QgsProcessingParameterNumber.Double"; default_value = param->HasValue() ? appli->GetParameterAsString(name): "0"; } else if (type == ParameterType_Radius) { dFile << "|QgsProcessingParameterNumber.Integer"; default_value = param->HasValue() ? appli->GetParameterAsString(name): "0"; } else if(type == ParameterType_InputFilename) { dFile << "|QgsProcessingParameterFile.File|txt"; } else if(type == ParameterType_Directory) { dFile << "|QgsProcessingParameterFile.Folder|False"; } else if (type == ParameterType_InputImageList) { dFile << "|3"; } else if (type == ParameterType_InputVectorDataList) { dFile << "|-1"; } else if (type == ParameterType_InputVectorData) { dFile << "|-1"; } else if(type == ParameterType_InputFilenameList) { dFile << "|4"; } else if (type == ParameterType_InputImage) { //default is None and nothing to add to dFile } else if(type ==ParameterType_String) { //default is None and nothing to add to dFile } else if(type ==ParameterType_StringList) { //default is None and nothing to add to dFile } else if(type ==ParameterType_ListView) { //default is None and nothing to add to dFile } else if(type == ParameterType_Bool) { default_value = appli->GetParameterAsString(name); } else if(type == ParameterType_Choice) { std::vector<std::string> key_list = appli->GetChoiceKeys(name); std::string values = ""; for( auto k : key_list) values += k + ";"; values.pop_back(); dFile << "|" << values ; ChoiceParameter *cparam = dynamic_cast<ChoiceParameter*>(param.GetPointer()); default_value = std::to_string(cparam->GetValue()); } else if(type == ParameterType_OutputVectorData || type == ParameterType_OutputImage || type == ParameterType_OutputFilename) { //no need for default_value, optional and extra fields in dFile //if parameter is a destination type. qgis_type|name|description is enough. //so we simply set isDestination to true and skip to end to append a new line. isDestination = true; } else { std::cout << "ERROR: default_value is empty for '" << name << "' type='" << qgis_type << "'" << std::endl; return EXIT_FAILURE; } if (!isDestination) { std::string optional; if (param->GetMandatory()) { optional = param->HasValue() || type == ParameterType_StringList ? "True" : "False"; } else { optional = "False"; } dFile << "|" << default_value << "|" << optional; } dFile << std::endl; } if(hasRasterOutput) { dFile << "*QgsProcessingParameterEnum|outputpixeltype|Output pixel type|unit8;int;float;double|False|2|True" << std::endl; } dFile.close(); std::ofstream indexFile; indexFile.open (algs_txt, std::ios::out | std::ios::app ); indexFile << group << "|" << module << std::endl; indexFile.close(); std::cerr << "Updated " << algs_txt << std::endl; return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/***************************************************************************/ /** ** @file ** @brief interface to Tipper triangulator */ /***************************************************************************/ #include <stdlib.h> #include "TipperTriangulator.h" /**************************************************************************\ ** ** tMesh::MakeMeshFromScratchTipper( infile ) ** ** as tMesh::MakeMeshFromScratch but uses Tipper's triangulation ** algorithm. ** ** Created: 07/2002, Arnaud Desitter ** Calls: ** Parameters: ** Modified: ** \**************************************************************************/ template< class tSubNode > void tMesh< tSubNode >:: MakeMeshFromScratchTipper( tInputFile &infile ) { //cout << "In MGFS, calling node constr w/ infile\n"; seed = infile.ReadItem( seed, "SEED" ); // Parameters defined in Input File ParamMMFS_t Param(infile); // Generate points { tPtrList< tSubNode > bndList; MakePointBoundary(Param, infile, bndList); MakePointInterior(Param, infile, false); nnodes = nodeList.getSize(); } // call triangulator based on Tipper's method BuildDelaunayMeshTipper(); cout<<"MakeMeshFromScratchTipper done.\n"; } /************************************************************************** ** ** tMesh::MakeMeshFromPointsTipper( infile ) ** ** Similar to tMesh::MakeMeshFromPoints but uses Tipper's triangulation ** algorithm. ** ** Created: 07/2002, Arnaud Desitter, Greg Tucker, Oxford ** Modified: 08/2002, MIT ** **************************************************************************/ template< class tSubNode > void tMesh< tSubNode >:: MakeMeshFromPointsTipper( tInputFile &infile ){ { int numpts; // no. of points in mesh char pointFilenm[80]; // name of file containing (x,y,z,b) data ifstream pointfile; // the file (stream) itself //Read Points infile.ReadItem( pointFilenm, "POINTFILENAME" ); pointfile.open( pointFilenm ); if( !pointfile.good() ){ cerr << "\nPoint file name: '" << pointFilenm << endl; ReportFatalError( "I can't find a file by this name." ); } cout<<"\nReading in '"<<pointFilenm<<"' points file..."<<endl; pointfile >> numpts; if( !pointfile.good() ) { cerr << "\nPoint file name: '" << pointFilenm << "'\n";; ReportFatalError( "I can't find a file by this name." ); } //Read point file, make Nodelist for( int i=0; i<numpts; i++ ){ double x, y, z; int bnd; if( pointfile.eof() ) { cout << "\nReached end-of-file while reading points.\n" ; ReportFatalError("Invalid point file."); } pointfile >> x >> y >> z >> bnd; if( pointfile.fail() ) { cerr << "\nPoint file name: '" << pointFilenm << "' - point " << i << endl; ReportFatalError( "I can't read the point above." ); } tSubNode tempnode( infile ); // temporary node used to create node list tempnode.set3DCoords( x, y, z); tempnode.setBoundaryFlag( bnd ); tempnode.setID( i ); if( bnd<0 || bnd>3 ){ ReportFatalError("Invalid boundary code."); } switch(bnd){ case kNonBoundary: nodeList.insertAtActiveBack( tempnode ); break; case kOpenBoundary: nodeList.insertAtBoundFront( tempnode ); break; default: nodeList.insertAtBack( tempnode ); break; } } pointfile.close(); } nnodes = nodeList.getSize(); // call triangulator based on Tipper's method BuildDelaunayMeshTipper(); cout<<"MakeMeshFromPointsTipper done.\n"; } /**************************************************************************\ ** ** tMesh::BuildDelaunayMeshTipper() ** ** once nodeList is set up, build a Delaunay triangulation using Tipper's ** algorithm. ** ** Created: 07/2002, Arnaud Desitter ** Calls: ** Parameters: ** Modified: ** \**************************************************************************/ // edge numbering translation static inline int e_t2c(int ei, bool o){ // Tipper to child return o? 2*ei : 2*ei+1; } static inline int e_t2c(const oriented_edge &oe){ return e_t2c(oe.e(), oe.o()); } template< class tSubNode > void tMesh< tSubNode >:: BuildDelaunayMeshTipper() { point *p = new point[nnodes]; // for Tipper triangulator { tMeshListIter< tSubNode > nodIter(nodeList); tSubNode* cn; int inode = 0; for( cn=nodIter.FirstP(); !(nodIter.AtEnd()); cn=nodIter.NextP()){ p[inode] = point(cn->getX(), cn->getY(), cn->getID()); ++inode; } if (0) { // DEBUG for (int i=0; i<nnodes; ++i){ cout << i << " x=" << p[i].x() << " y=" << p[i].y() << endl; } } } // call mesh generator based on Tipper's method cout << "Computing triangulation..." << flush; int nedgesl; int nelem; edge* edges(0); elem* elems(0); tt_sort_triangulate(nnodes, p, &nedgesl, &edges, &nelem, &elems); cout << "done.\n"; if (0) { // DEBUG cout << "After sort_triangulate:\n"; for( int iedge=0; iedge < nedgesl; ++iedge) { cout << "edge " << 2*iedge << " from=" << p[edges[iedge].from].id() << " (" << p[edges[iedge].from].x() << "," << p[edges[iedge].from].y() << ")" << " to=" << p[edges[iedge].to].id() << " (" << p[edges[iedge].to].x() << "," << p[edges[iedge].to].y() << ")" << endl; } } // set sizes this->nedges = 2*nedgesl; this->ntri = nelem; { const tIdArray< tSubNode > NodeTable(nodeList); // for fast lookup per ID // Create and initialize the edge list by creating two temporary edges // (which are complementary, ie share the same endpoints) and then // iteratively assigning values to the pair and inserting them onto the // back of the edgeList cout << "Creating edge list..." << flush; { for( int iedge = 0; iedge < nedgesl; ++iedge ) { tSubNode *nodPtr1 = NodeTable[p[edges[iedge].from].id()]; tSubNode *nodPtr2 = NodeTable[p[edges[iedge].to].id()]; // Assign values: ID, origin and destination pointers, // "flowallowed" status tEdge tempedge1( e_t2c(iedge,true) , nodPtr1, nodPtr2), tempedge2( e_t2c(iedge,false), nodPtr2, nodPtr1); // insert edge pair onto the list --- active // part of list if flow is allowed, inactive if not if (0) //DEBUG cout << "Setting edges " << tempedge1.getID() << " and " << tempedge2.getID() << (tempedge1.FlowAllowed() ? " as OPEN" : " as no-flux") << endl; if ( tempedge1.FlowAllowed() ) { edgeList.insertAtActiveBack( tempedge1 ); tEdge *e1 = edgeList.getLastActive()->getDataPtrNC(); edgeList.insertAtActiveBack( tempedge2 ); tEdge *e2 = edgeList.getLastActive()->getDataPtrNC(); e1->setComplementEdge(e2); e2->setComplementEdge(e1); } else { edgeList.insertAtBack( tempedge1 ); tEdge *e1 = edgeList.getLast()->getDataPtrNC(); edgeList.insertAtBack( tempedge2 ); tEdge *e2 = edgeList.getLast()->getDataPtrNC(); e1->setComplementEdge(e2); e2->setComplementEdge(e1); } } } const tIdArray< tEdge > EdgeTable(edgeList); // for fast lookup per ID cout << "done.\n"; if (0) { //DEBUG cout << "JUST ADDED EDGES:\n"; tMeshListIter< tEdge > ei( edgeList ); for( tEdge *ce=ei.FirstP(); !(ei.AtEnd()); ce=ei.NextP() ){ ce->TellCoords(); cout << ce->FlowAllowed() << endl; } } // set up the lists of edges (spokes) connected to each node cout << "Setting up edg pointer..." << flush; { // connectivity point - sorted point tArray< int > p2sp(nnodes); for(int inodes=0;inodes!=nnodes;++inodes){ p2sp[p[inodes].id()] = inodes; } oriented_edge *oedge; tt_build_spoke(nnodes, nedgesl, edges, &oedge); tMeshListIter< tSubNode > nodIter(nodeList); tSubNode * cn; for( cn=nodIter.FirstP(); !(nodIter.AtEnd()); cn=nodIter.NextP()){ tEdge *edgPtr = EdgeTable[ e_t2c(oedge[p2sp[cn->getID()]]) ]; cn->setEdg( edgPtr ); } delete [] oedge; } cout << "done.\n"; // Assign ccwedg connectivity (that is, tell each edge about its neighbor // immediately counterclockwise). Likewise for cwedg connectivity. cout << "Setting up CCW and CW edges..." << flush; { for( int iedge=0; iedge<nedgesl; ++iedge){ { const oriented_edge e1(iedge,true); tEdge *curedg = EdgeTable[ e_t2c(e1) ]; const oriented_edge ccw_from = e1.ccw_edge_around_from(edges); tEdge *ccwedg = EdgeTable[ e_t2c(ccw_from) ]; curedg->setCCWEdg( ccwedg ); ccwedg->setCWEdg( curedg ); } { const oriented_edge e2(iedge,false); tEdge *curedg = EdgeTable[ e_t2c(e2) ]; const oriented_edge ccw_to = e2.ccw_edge_around_from(edges); tEdge *ccwedg = EdgeTable[ e_t2c(ccw_to) ]; curedg->setCCWEdg( ccwedg ); ccwedg->setCWEdg( curedg ); } } } cout << "done.\n"; cout << "Setting up triangle connectivity..." << flush; { int ielem; for ( ielem=0; ielem<nelem; ++ielem ) { if (0) // DEBUG cout << "TRI " << ielem << endl << flush; if (0) { // DEBUG cout << "p0=" << p[elems[ielem].p1].id() << " " << "(" << p[elems[ielem].p1].x() << "," << p[elems[ielem].p1].y() << "), " << "p1=" << p[elems[ielem].p2].id() << " " << "(" << p[elems[ielem].p2].x() << "," << p[elems[ielem].p2].y() << "), " << "p2=" << p[elems[ielem].p3].id() << " " << "(" << p[elems[ielem].p3].x() << "," << p[elems[ielem].p3].y() << "), " << "e0=" << elems[ielem].e1 << " " << "e1=" << elems[ielem].e2 << " " << "e2=" << elems[ielem].e3 << endl; } tTriangle newtri( ielem, NodeTable[p[elems[ielem].p1].id()], NodeTable[p[elems[ielem].p2].id()], NodeTable[p[elems[ielem].p3].id()], EdgeTable[e_t2c(elems[ielem].e1, elems[ielem].eo1)], EdgeTable[e_t2c(elems[ielem].e2, elems[ielem].eo2)], EdgeTable[e_t2c(elems[ielem].e3, elems[ielem].eo3)] ); triList.insertAtBack( newtri ); } } } // deallocation of some Tipper triangulator data structures delete [] edges; edges = 0; delete [] p; p = 0; { const tIdArray< tTriangle > TriTable(triList); // for fast lookup per ID int ielem; for( ielem=0; ielem<nelem; ++ielem ) { tTriangle *ct = TriTable[ ielem ]; ct->setTPtr( 0, elems[ielem].t1>=0 ? TriTable[ elems[ielem].t1 ] : 0 ); ct->setTPtr( 1, elems[ielem].t2>=0 ? TriTable[ elems[ielem].t2 ] : 0 ); ct->setTPtr( 2, elems[ielem].t3>=0 ? TriTable[ elems[ielem].t3 ] : 0 ); } } cout << "done.\n"; // deallocation of remaining Tipper triangulator data structures delete [] elems; // assertions assert( edgeList.getSize() == 2*nedgesl ); assert( triList.getSize() == nelem ); CheckMeshConsistency(); //remove CMC call from UM UpdateMesh(); //calls CheckMeshConsistency() TODO: once bug-free, } <commit_msg>(Arnaud) BuildDelaunayMeshTipper: set miNextXXID<commit_after>/***************************************************************************/ /** ** @file ** @brief interface to Tipper triangulator */ /***************************************************************************/ #include <stdlib.h> #include "TipperTriangulator.h" /**************************************************************************\ ** ** tMesh::MakeMeshFromScratchTipper( infile ) ** ** as tMesh::MakeMeshFromScratch but uses Tipper's triangulation ** algorithm. ** ** Created: 07/2002, Arnaud Desitter ** Calls: ** Parameters: ** Modified: ** \**************************************************************************/ template< class tSubNode > void tMesh< tSubNode >:: MakeMeshFromScratchTipper( tInputFile &infile ) { //cout << "In MGFS, calling node constr w/ infile\n"; seed = infile.ReadItem( seed, "SEED" ); // Parameters defined in Input File ParamMMFS_t Param(infile); // Generate points { tPtrList< tSubNode > bndList; MakePointBoundary(Param, infile, bndList); MakePointInterior(Param, infile, false); nnodes = nodeList.getSize(); } // call triangulator based on Tipper's method BuildDelaunayMeshTipper(); cout<<"MakeMeshFromScratchTipper done.\n"; } /************************************************************************** ** ** tMesh::MakeMeshFromPointsTipper( infile ) ** ** Similar to tMesh::MakeMeshFromPoints but uses Tipper's triangulation ** algorithm. ** ** Created: 07/2002, Arnaud Desitter, Greg Tucker, Oxford ** Modified: 08/2002, MIT ** **************************************************************************/ template< class tSubNode > void tMesh< tSubNode >:: MakeMeshFromPointsTipper( tInputFile &infile ){ { int numpts; // no. of points in mesh char pointFilenm[80]; // name of file containing (x,y,z,b) data ifstream pointfile; // the file (stream) itself //Read Points infile.ReadItem( pointFilenm, "POINTFILENAME" ); pointfile.open( pointFilenm ); if( !pointfile.good() ){ cerr << "\nPoint file name: '" << pointFilenm << endl; ReportFatalError( "I can't find a file by this name." ); } cout<<"\nReading in '"<<pointFilenm<<"' points file..."<<endl; pointfile >> numpts; if( !pointfile.good() ) { cerr << "\nPoint file name: '" << pointFilenm << "'\n";; ReportFatalError( "I can't find a file by this name." ); } //Read point file, make Nodelist for( int i=0; i<numpts; i++ ){ double x, y, z; int bnd; if( pointfile.eof() ) { cout << "\nReached end-of-file while reading points.\n" ; ReportFatalError("Invalid point file."); } pointfile >> x >> y >> z >> bnd; if( pointfile.fail() ) { cerr << "\nPoint file name: '" << pointFilenm << "' - point " << i << endl; ReportFatalError( "I can't read the point above." ); } tSubNode tempnode( infile ); // temporary node used to create node list tempnode.set3DCoords( x, y, z); tempnode.setBoundaryFlag( bnd ); tempnode.setID( i ); if( bnd<0 || bnd>3 ){ ReportFatalError("Invalid boundary code."); } switch(bnd){ case kNonBoundary: nodeList.insertAtActiveBack( tempnode ); break; case kOpenBoundary: nodeList.insertAtBoundFront( tempnode ); break; default: nodeList.insertAtBack( tempnode ); break; } } pointfile.close(); } nnodes = nodeList.getSize(); // call triangulator based on Tipper's method BuildDelaunayMeshTipper(); cout<<"MakeMeshFromPointsTipper done.\n"; } /**************************************************************************\ ** ** tMesh::BuildDelaunayMeshTipper() ** ** once nodeList is set up, build a Delaunay triangulation using Tipper's ** algorithm. ** ** Created: 07/2002, Arnaud Desitter ** Calls: ** Parameters: ** Modified: ** \**************************************************************************/ // edge numbering translation static inline int e_t2c(int ei, bool o){ // Tipper to child return o? 2*ei : 2*ei+1; } static inline int e_t2c(const oriented_edge &oe){ return e_t2c(oe.e(), oe.o()); } template< class tSubNode > void tMesh< tSubNode >:: BuildDelaunayMeshTipper() { point *p = new point[nnodes]; // for Tipper triangulator { tMeshListIter< tSubNode > nodIter(nodeList); tSubNode* cn; int inode = 0; for( cn=nodIter.FirstP(); !(nodIter.AtEnd()); cn=nodIter.NextP()){ p[inode] = point(cn->getX(), cn->getY(), cn->getID()); ++inode; } if (0) { // DEBUG for (int i=0; i<nnodes; ++i){ cout << i << " x=" << p[i].x() << " y=" << p[i].y() << endl; } } } // call mesh generator based on Tipper's method cout << "Computing triangulation..." << flush; int nedgesl; int nelem; edge* edges(0); elem* elems(0); tt_sort_triangulate(nnodes, p, &nedgesl, &edges, &nelem, &elems); cout << "done.\n"; if (0) { // DEBUG cout << "After sort_triangulate:\n"; for( int iedge=0; iedge < nedgesl; ++iedge) { cout << "edge " << 2*iedge << " from=" << p[edges[iedge].from].id() << " (" << p[edges[iedge].from].x() << "," << p[edges[iedge].from].y() << ")" << " to=" << p[edges[iedge].to].id() << " (" << p[edges[iedge].to].x() << "," << p[edges[iedge].to].y() << ")" << endl; } } // set sizes this->nedges = 2*nedgesl; this->ntri = nelem; { const tIdArray< tSubNode > NodeTable(nodeList); // for fast lookup per ID // Create and initialize the edge list by creating two temporary edges // (which are complementary, ie share the same endpoints) and then // iteratively assigning values to the pair and inserting them onto the // back of the edgeList cout << "Creating edge list..." << flush; { for( int iedge = 0; iedge < nedgesl; ++iedge ) { tSubNode *nodPtr1 = NodeTable[p[edges[iedge].from].id()]; tSubNode *nodPtr2 = NodeTable[p[edges[iedge].to].id()]; // Assign values: ID, origin and destination pointers, // "flowallowed" status tEdge tempedge1( e_t2c(iedge,true) , nodPtr1, nodPtr2), tempedge2( e_t2c(iedge,false), nodPtr2, nodPtr1); // insert edge pair onto the list --- active // part of list if flow is allowed, inactive if not if (0) //DEBUG cout << "Setting edges " << tempedge1.getID() << " and " << tempedge2.getID() << (tempedge1.FlowAllowed() ? " as OPEN" : " as no-flux") << endl; if ( tempedge1.FlowAllowed() ) { edgeList.insertAtActiveBack( tempedge1 ); tEdge *e1 = edgeList.getLastActive()->getDataPtrNC(); edgeList.insertAtActiveBack( tempedge2 ); tEdge *e2 = edgeList.getLastActive()->getDataPtrNC(); e1->setComplementEdge(e2); e2->setComplementEdge(e1); } else { edgeList.insertAtBack( tempedge1 ); tEdge *e1 = edgeList.getLast()->getDataPtrNC(); edgeList.insertAtBack( tempedge2 ); tEdge *e2 = edgeList.getLast()->getDataPtrNC(); e1->setComplementEdge(e2); e2->setComplementEdge(e1); } } } const tIdArray< tEdge > EdgeTable(edgeList); // for fast lookup per ID cout << "done.\n"; if (0) { //DEBUG cout << "JUST ADDED EDGES:\n"; tMeshListIter< tEdge > ei( edgeList ); for( tEdge *ce=ei.FirstP(); !(ei.AtEnd()); ce=ei.NextP() ){ ce->TellCoords(); cout << ce->FlowAllowed() << endl; } } // set up the lists of edges (spokes) connected to each node cout << "Setting up edg pointer..." << flush; { // connectivity point - sorted point tArray< int > p2sp(nnodes); for(int inodes=0;inodes!=nnodes;++inodes){ p2sp[p[inodes].id()] = inodes; } oriented_edge *oedge; tt_build_spoke(nnodes, nedgesl, edges, &oedge); tMeshListIter< tSubNode > nodIter(nodeList); tSubNode * cn; for( cn=nodIter.FirstP(); !(nodIter.AtEnd()); cn=nodIter.NextP()){ tEdge *edgPtr = EdgeTable[ e_t2c(oedge[p2sp[cn->getID()]]) ]; cn->setEdg( edgPtr ); } delete [] oedge; } cout << "done.\n"; // Assign ccwedg connectivity (that is, tell each edge about its neighbor // immediately counterclockwise). Likewise for cwedg connectivity. cout << "Setting up CCW and CW edges..." << flush; { for( int iedge=0; iedge<nedgesl; ++iedge){ { const oriented_edge e1(iedge,true); tEdge *curedg = EdgeTable[ e_t2c(e1) ]; const oriented_edge ccw_from = e1.ccw_edge_around_from(edges); tEdge *ccwedg = EdgeTable[ e_t2c(ccw_from) ]; curedg->setCCWEdg( ccwedg ); ccwedg->setCWEdg( curedg ); } { const oriented_edge e2(iedge,false); tEdge *curedg = EdgeTable[ e_t2c(e2) ]; const oriented_edge ccw_to = e2.ccw_edge_around_from(edges); tEdge *ccwedg = EdgeTable[ e_t2c(ccw_to) ]; curedg->setCCWEdg( ccwedg ); ccwedg->setCWEdg( curedg ); } } } cout << "done.\n"; cout << "Setting up triangle connectivity..." << flush; { int ielem; for ( ielem=0; ielem<nelem; ++ielem ) { if (0) // DEBUG cout << "TRI " << ielem << endl << flush; if (0) { // DEBUG cout << "p0=" << p[elems[ielem].p1].id() << " " << "(" << p[elems[ielem].p1].x() << "," << p[elems[ielem].p1].y() << "), " << "p1=" << p[elems[ielem].p2].id() << " " << "(" << p[elems[ielem].p2].x() << "," << p[elems[ielem].p2].y() << "), " << "p2=" << p[elems[ielem].p3].id() << " " << "(" << p[elems[ielem].p3].x() << "," << p[elems[ielem].p3].y() << "), " << "e0=" << elems[ielem].e1 << " " << "e1=" << elems[ielem].e2 << " " << "e2=" << elems[ielem].e3 << endl; } tTriangle newtri( ielem, NodeTable[p[elems[ielem].p1].id()], NodeTable[p[elems[ielem].p2].id()], NodeTable[p[elems[ielem].p3].id()], EdgeTable[e_t2c(elems[ielem].e1, elems[ielem].eo1)], EdgeTable[e_t2c(elems[ielem].e2, elems[ielem].eo2)], EdgeTable[e_t2c(elems[ielem].e3, elems[ielem].eo3)] ); triList.insertAtBack( newtri ); } } } // deallocation of some Tipper triangulator data structures delete [] edges; edges = 0; delete [] p; p = 0; { const tIdArray< tTriangle > TriTable(triList); // for fast lookup per ID int ielem; for( ielem=0; ielem<nelem; ++ielem ) { tTriangle *ct = TriTable[ ielem ]; ct->setTPtr( 0, elems[ielem].t1>=0 ? TriTable[ elems[ielem].t1 ] : 0 ); ct->setTPtr( 1, elems[ielem].t2>=0 ? TriTable[ elems[ielem].t2 ] : 0 ); ct->setTPtr( 2, elems[ielem].t3>=0 ? TriTable[ elems[ielem].t3 ] : 0 ); } } cout << "done.\n"; // deallocation of remaining Tipper triangulator data structures delete [] elems; // set Maximum IDs miNextNodeID = nodeList.getSize(); miNextEdgID = edgeList.getSize(); miNextTriID = triList.getSize(); // assertions assert( edgeList.getSize() == 2*nedgesl ); assert( triList.getSize() == nelem ); CheckMeshConsistency(); //remove CMC call from UM UpdateMesh(); //calls CheckMeshConsistency() TODO: once bug-free, } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: accessiblecontexthelper.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: fs $ $Date: 2002-04-26 07:25:50 $ * * 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 EXPRESS 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 COMPHELPER_ACCESSIBLE_CONTEXT_HELPER_HXX #include <comphelper/accessiblecontexthelper.hxx> #endif #ifndef _OSL_DIAGNOSE_H_ #include <osl/diagnose.h> #endif #ifndef _CPPUHELPER_WEAKREF_HXX_ #include <cppuhelper/weakref.hxx> #endif #ifndef _SV_SVAPP_HXX #include <vcl/svapp.hxx> #endif #ifndef _VOS_MUTEX_HXX_ #include <vos/mutex.hxx> #endif #ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLEEVENTID_HPP_ #include <drafts/com/sun/star/accessibility/AccessibleEventId.hpp> #endif #ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLESTATETYPE_HPP_ #include <drafts/com/sun/star/accessibility/AccessibleStateType.hpp> #endif //......................................................................... namespace comphelper { //......................................................................... using namespace ::com::sun::star::uno; using namespace ::com::sun::star::lang; using namespace ::drafts::com::sun::star::accessibility; //===================================================================== //= OContextHelper_Impl //===================================================================== /** implementation class for OAccessibleContextHelper. No own thread safety! */ class OContextHelper_Impl { private: OAccessibleContextHelper* m_pAntiImpl; // the owning instance ::cppu::OInterfaceContainerHelper* m_pEventListeners; WeakReference< XAccessible > m_aCreator; // the XAccessible which created our XAccessibleContext public: ::cppu::OInterfaceContainerHelper* getListenerContainer( sal_Bool _bCreate = sal_True ); // not const - will create if necessary inline Reference< XAccessible > getCreator( ) const { return m_aCreator; } inline void setCreator( const Reference< XAccessible >& _rAcc ); public: OContextHelper_Impl( OAccessibleContextHelper* _pAntiImpl ) :m_pAntiImpl( _pAntiImpl ) ,m_pEventListeners( NULL ) { } }; //--------------------------------------------------------------------- inline void OContextHelper_Impl::setCreator( const Reference< XAccessible >& _rAcc ) { m_aCreator = _rAcc; } //--------------------------------------------------------------------- ::cppu::OInterfaceContainerHelper* OContextHelper_Impl::getListenerContainer( sal_Bool _bCreate ) { if ( !m_pEventListeners && _bCreate ) m_pEventListeners = new ::cppu::OInterfaceContainerHelper( m_pAntiImpl->GetMutex( OAccessibleContextHelper::OAccessControl() ) ); return m_pEventListeners; } //===================================================================== //= OAccessibleContextHelper //===================================================================== //--------------------------------------------------------------------- OAccessibleContextHelper::OAccessibleContextHelper( ) :OAccessibleContextHelper_Base( GetMutex() ) ,m_pImpl( NULL ) { m_pImpl = new OContextHelper_Impl( this ); } //--------------------------------------------------------------------- OAccessibleContextHelper::~OAccessibleContextHelper( ) { ensureDisposed(); delete m_pImpl; m_pImpl = NULL; } //--------------------------------------------------------------------- void SAL_CALL OAccessibleContextHelper::disposing() { // notify our listeners that we're going to be defunc NotifyAccessibleEvent( AccessibleEventId::ACCESSIBLE_STATE_EVENT, Any(), makeAny( AccessibleStateType::DEFUNC ) ); ::osl::ClearableMutexGuard aGuard( GetMutex() ); ::cppu::OInterfaceContainerHelper* pListeners = m_pImpl->getListenerContainer( sal_False ); if ( pListeners ) { EventObject aDisposee( *this ); aGuard.clear(); pListeners->disposeAndClear( aDisposee ); } } //--------------------------------------------------------------------- void SAL_CALL OAccessibleContextHelper::addEventListener( const Reference< XAccessibleEventListener >& _rxListener ) throw (RuntimeException) { OContextEntryGuard( this ); if ( _rxListener.is() ) m_pImpl->getListenerContainer()->addInterface( _rxListener ); } //--------------------------------------------------------------------- void SAL_CALL OAccessibleContextHelper::removeEventListener( const Reference< XAccessibleEventListener >& _rxListener ) throw (RuntimeException) { OContextEntryGuard( this ); if ( _rxListener.is() ) m_pImpl->getListenerContainer()->removeInterface( _rxListener ); } //--------------------------------------------------------------------- void SAL_CALL OAccessibleContextHelper::NotifyAccessibleEvent( const sal_Int16 _nEventId, const Any& _rOldValue, const Any& _rNewValue ) { // copy our current listeners ::cppu::OInterfaceContainerHelper* pListeners = m_pImpl->getListenerContainer( sal_False ); Sequence< Reference< XInterface > > aListeners; if ( pListeners ) aListeners = pListeners->getElements(); if ( aListeners.getLength() ) { AccessibleEventObject aEvent; aEvent.Source = *this; aEvent.EventId = _nEventId; aEvent.OldValue = _rOldValue; aEvent.NewValue = _rNewValue; const Reference< XInterface >* pLoop = aListeners.getConstArray(); const Reference< XInterface >* pLoopEnd = pLoop + aListeners.getLength(); while ( pLoop != pLoopEnd ) { try { while ( pLoop != pLoopEnd ) { XAccessibleEventListener* pListener = static_cast< XAccessibleEventListener* > ( pLoop->get() ); // note that this cast is valid: // We added the interface to our listener container, and at this time it was an // XAccessibleEventListener. As we did not query for XInterface, but instead used // the XInterface which is the base of XAccessibleEventListener, we can now safely // cast. if ( pListener ) pListener->notifyEvent( aEvent ); ++pLoop; } } catch( const Exception& e ) { e; // make compiler happy // skip this listener and continue with the next one ++pLoop; } } } } //--------------------------------------------------------------------- sal_Bool OAccessibleContextHelper::isAlive() const { return !GetBroadcastHelper().bDisposed && !GetBroadcastHelper().bInDispose; } //--------------------------------------------------------------------- void OAccessibleContextHelper::ensureAlive() const SAL_THROW( ( DisposedException ) ) { if( !isAlive() ) throw DisposedException(); } //--------------------------------------------------------------------- void OAccessibleContextHelper::ensureDisposed( ) { if ( !GetBroadcastHelper().bDisposed ) { OSL_ENSURE( 0 == m_refCount, "OAccessibleContextHelper::ensureDisposed: this method _has_ to be called from without your dtor only!" ); acquire(); dispose(); } } //--------------------------------------------------------------------- void OAccessibleContextHelper::lateInit( const Reference< XAccessible >& _rxAccessible ) { m_pImpl->setCreator( _rxAccessible ); } //--------------------------------------------------------------------- sal_Int32 SAL_CALL OAccessibleContextHelper::getAccessibleIndexInParent( ) throw (RuntimeException) { OContextEntryGuard aGuard( this ); // -1 for child not found/no parent (according to specification) sal_Int32 nRet = -1; try { Reference< XAccessibleContext > xParentContext( implGetParentContext() ); // iterate over parent's children and search for this object if ( xParentContext.is() ) { // our own XAccessible for comparing with the children of our parent Reference< XAccessible > xCreator( m_pImpl->getCreator() ); OSL_ENSURE( xCreator.is(), "OAccessibleContextHelper::getAccessibleIndexInParent: invalid creator!" ); // two ideas why this could be NULL: // * nobody called our late ctor (init), so we never had a creator at all -> bad // * the creator is already dead. In this case, we should have been disposed, and // never survived the above OContextEntryGuard. // in all other situations the creator should be non-NULL if ( xCreator.is() ) { sal_Int32 nChildCount = xParentContext->getAccessibleChildCount(); for ( sal_Int32 nChild = 0; ( nChild < nChildCount ) && ( -1 == nRet ); ++nChild ) { Reference< XAccessible > xChild( xParentContext->getAccessibleChild( nChild ) ); if ( xChild.get() == xCreator.get() ) nRet = nChild; } } } } catch( const Exception& ) { OSL_ENSURE( sal_False, "OAccessibleContextHelper::getAccessibleIndexInParent: caught an exception!" ); } return nRet; } //--------------------------------------------------------------------- Locale SAL_CALL OAccessibleContextHelper::getLocale( ) throw (IllegalAccessibleComponentStateException, RuntimeException) { // simply ask the parent Reference< XAccessible > xParent = getAccessibleParent(); Reference< XAccessibleContext > xParentContext; if ( xParent.is() ) xParentContext = xParent->getAccessibleContext(); if ( !xParentContext.is() ) throw IllegalAccessibleComponentStateException( ::rtl::OUString(), *this ); return xParentContext->getLocale(); } //--------------------------------------------------------------------- Reference< XAccessibleContext > OAccessibleContextHelper::implGetParentContext() SAL_THROW( ( RuntimeException ) ) { Reference< XAccessible > xParent = getAccessibleParent(); Reference< XAccessibleContext > xParentContext; if ( xParent.is() ) xParentContext = xParent->getAccessibleContext(); return xParentContext; } //......................................................................... } // namespace comphelper //......................................................................... /************************************************************************* * history: * $Log: not supported by cvs2svn $ * Revision 1.2 2002/04/26 05:52:18 fs * #98750# use correct broadcasthelper (in the WeagAggComponentImpl* base) * * Revision 1.1 2002/04/23 11:10:30 fs * initial checkin - helper for implementing an XAccessibleContext * * * Revision 1.0 17.04.2002 16:06:46 fs ************************************************************************/ <commit_msg>#98750# +getAccessibleCreator / use the creator (XAccessible) as event source<commit_after>/************************************************************************* * * $RCSfile: accessiblecontexthelper.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: fs $ $Date: 2002-04-26 14:24:28 $ * * 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 EXPRESS 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 COMPHELPER_ACCESSIBLE_CONTEXT_HELPER_HXX #include <comphelper/accessiblecontexthelper.hxx> #endif #ifndef _OSL_DIAGNOSE_H_ #include <osl/diagnose.h> #endif #ifndef _CPPUHELPER_WEAKREF_HXX_ #include <cppuhelper/weakref.hxx> #endif #ifndef _SV_SVAPP_HXX #include <vcl/svapp.hxx> #endif #ifndef _VOS_MUTEX_HXX_ #include <vos/mutex.hxx> #endif #ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLEEVENTID_HPP_ #include <drafts/com/sun/star/accessibility/AccessibleEventId.hpp> #endif #ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLESTATETYPE_HPP_ #include <drafts/com/sun/star/accessibility/AccessibleStateType.hpp> #endif //......................................................................... namespace comphelper { //......................................................................... using namespace ::com::sun::star::uno; using namespace ::com::sun::star::lang; using namespace ::drafts::com::sun::star::accessibility; //===================================================================== //= OContextHelper_Impl //===================================================================== /** implementation class for OAccessibleContextHelper. No own thread safety! */ class OContextHelper_Impl { private: OAccessibleContextHelper* m_pAntiImpl; // the owning instance ::cppu::OInterfaceContainerHelper* m_pEventListeners; WeakReference< XAccessible > m_aCreator; // the XAccessible which created our XAccessibleContext public: ::cppu::OInterfaceContainerHelper* getListenerContainer( sal_Bool _bCreate = sal_True ); // not const - will create if necessary inline Reference< XAccessible > getCreator( ) const { return m_aCreator; } inline void setCreator( const Reference< XAccessible >& _rAcc ); public: OContextHelper_Impl( OAccessibleContextHelper* _pAntiImpl ) :m_pAntiImpl( _pAntiImpl ) ,m_pEventListeners( NULL ) { } }; //--------------------------------------------------------------------- inline void OContextHelper_Impl::setCreator( const Reference< XAccessible >& _rAcc ) { m_aCreator = _rAcc; } //--------------------------------------------------------------------- ::cppu::OInterfaceContainerHelper* OContextHelper_Impl::getListenerContainer( sal_Bool _bCreate ) { if ( !m_pEventListeners && _bCreate ) m_pEventListeners = new ::cppu::OInterfaceContainerHelper( m_pAntiImpl->GetMutex( OAccessibleContextHelper::OAccessControl() ) ); return m_pEventListeners; } //===================================================================== //= OAccessibleContextHelper //===================================================================== //--------------------------------------------------------------------- OAccessibleContextHelper::OAccessibleContextHelper( ) :OAccessibleContextHelper_Base( GetMutex() ) ,m_pImpl( NULL ) { m_pImpl = new OContextHelper_Impl( this ); } //--------------------------------------------------------------------- OAccessibleContextHelper::~OAccessibleContextHelper( ) { ensureDisposed(); delete m_pImpl; m_pImpl = NULL; } //--------------------------------------------------------------------- void SAL_CALL OAccessibleContextHelper::disposing() { // notify our listeners that we're going to be defunc NotifyAccessibleEvent( AccessibleEventId::ACCESSIBLE_STATE_EVENT, Any(), makeAny( AccessibleStateType::DEFUNC ) ); ::osl::ClearableMutexGuard aGuard( GetMutex() ); ::cppu::OInterfaceContainerHelper* pListeners = m_pImpl->getListenerContainer( sal_False ); if ( pListeners ) { EventObject aDisposee( *this ); aGuard.clear(); pListeners->disposeAndClear( aDisposee ); } } //--------------------------------------------------------------------- void SAL_CALL OAccessibleContextHelper::addEventListener( const Reference< XAccessibleEventListener >& _rxListener ) throw (RuntimeException) { OContextEntryGuard( this ); if ( _rxListener.is() ) m_pImpl->getListenerContainer()->addInterface( _rxListener ); } //--------------------------------------------------------------------- void SAL_CALL OAccessibleContextHelper::removeEventListener( const Reference< XAccessibleEventListener >& _rxListener ) throw (RuntimeException) { OContextEntryGuard( this ); if ( _rxListener.is() ) m_pImpl->getListenerContainer()->removeInterface( _rxListener ); } //--------------------------------------------------------------------- void SAL_CALL OAccessibleContextHelper::NotifyAccessibleEvent( const sal_Int16 _nEventId, const Any& _rOldValue, const Any& _rNewValue ) { // copy our current listeners ::cppu::OInterfaceContainerHelper* pListeners = m_pImpl->getListenerContainer( sal_False ); Sequence< Reference< XInterface > > aListeners; if ( pListeners ) aListeners = pListeners->getElements(); if ( aListeners.getLength() ) { AccessibleEventObject aEvent; aEvent.Source = m_pImpl->getCreator(); OSL_ENSURE( aEvent.Source.is(), "OAccessibleContextHelper::NotifyAccessibleEvent: invalid creator!" ); aEvent.EventId = _nEventId; aEvent.OldValue = _rOldValue; aEvent.NewValue = _rNewValue; const Reference< XInterface >* pLoop = aListeners.getConstArray(); const Reference< XInterface >* pLoopEnd = pLoop + aListeners.getLength(); while ( pLoop != pLoopEnd ) { try { while ( pLoop != pLoopEnd ) { XAccessibleEventListener* pListener = static_cast< XAccessibleEventListener* > ( pLoop->get() ); // note that this cast is valid: // We added the interface to our listener container, and at this time it was an // XAccessibleEventListener. As we did not query for XInterface, but instead used // the XInterface which is the base of XAccessibleEventListener, we can now safely // cast. if ( pListener ) pListener->notifyEvent( aEvent ); ++pLoop; } } catch( const Exception& e ) { e; // make compiler happy // skip this listener and continue with the next one ++pLoop; } } } } //--------------------------------------------------------------------- sal_Bool OAccessibleContextHelper::isAlive() const { return !GetBroadcastHelper().bDisposed && !GetBroadcastHelper().bInDispose; } //--------------------------------------------------------------------- void OAccessibleContextHelper::ensureAlive() const SAL_THROW( ( DisposedException ) ) { if( !isAlive() ) throw DisposedException(); } //--------------------------------------------------------------------- void OAccessibleContextHelper::ensureDisposed( ) { if ( !GetBroadcastHelper().bDisposed ) { OSL_ENSURE( 0 == m_refCount, "OAccessibleContextHelper::ensureDisposed: this method _has_ to be called from without your dtor only!" ); acquire(); dispose(); } } //--------------------------------------------------------------------- void OAccessibleContextHelper::lateInit( const Reference< XAccessible >& _rxAccessible ) { m_pImpl->setCreator( _rxAccessible ); } //--------------------------------------------------------------------- Reference< XAccessible > OAccessibleContextHelper::getAccessibleCreator( ) const { return m_pImpl->getCreator(); } //--------------------------------------------------------------------- sal_Int32 SAL_CALL OAccessibleContextHelper::getAccessibleIndexInParent( ) throw (RuntimeException) { OContextEntryGuard aGuard( this ); // -1 for child not found/no parent (according to specification) sal_Int32 nRet = -1; try { Reference< XAccessibleContext > xParentContext( implGetParentContext() ); // iterate over parent's children and search for this object if ( xParentContext.is() ) { // our own XAccessible for comparing with the children of our parent Reference< XAccessible > xCreator( m_pImpl->getCreator() ); OSL_ENSURE( xCreator.is(), "OAccessibleContextHelper::getAccessibleIndexInParent: invalid creator!" ); // two ideas why this could be NULL: // * nobody called our late ctor (init), so we never had a creator at all -> bad // * the creator is already dead. In this case, we should have been disposed, and // never survived the above OContextEntryGuard. // in all other situations the creator should be non-NULL if ( xCreator.is() ) { sal_Int32 nChildCount = xParentContext->getAccessibleChildCount(); for ( sal_Int32 nChild = 0; ( nChild < nChildCount ) && ( -1 == nRet ); ++nChild ) { Reference< XAccessible > xChild( xParentContext->getAccessibleChild( nChild ) ); if ( xChild.get() == xCreator.get() ) nRet = nChild; } } } } catch( const Exception& ) { OSL_ENSURE( sal_False, "OAccessibleContextHelper::getAccessibleIndexInParent: caught an exception!" ); } return nRet; } //--------------------------------------------------------------------- Locale SAL_CALL OAccessibleContextHelper::getLocale( ) throw (IllegalAccessibleComponentStateException, RuntimeException) { // simply ask the parent Reference< XAccessible > xParent = getAccessibleParent(); Reference< XAccessibleContext > xParentContext; if ( xParent.is() ) xParentContext = xParent->getAccessibleContext(); if ( !xParentContext.is() ) throw IllegalAccessibleComponentStateException( ::rtl::OUString(), *this ); return xParentContext->getLocale(); } //--------------------------------------------------------------------- Reference< XAccessibleContext > OAccessibleContextHelper::implGetParentContext() SAL_THROW( ( RuntimeException ) ) { Reference< XAccessible > xParent = getAccessibleParent(); Reference< XAccessibleContext > xParentContext; if ( xParent.is() ) xParentContext = xParent->getAccessibleContext(); return xParentContext; } //......................................................................... } // namespace comphelper //......................................................................... /************************************************************************* * history: * $Log: not supported by cvs2svn $ * Revision 1.3 2002/04/26 07:25:50 fs * #98750# corrected NotifyAccessibleEvent * * Revision 1.2 2002/04/26 05:52:18 fs * #98750# use correct broadcasthelper (in the WeagAggComponentImpl* base) * * Revision 1.1 2002/04/23 11:10:30 fs * initial checkin - helper for implementing an XAccessibleContext * * * Revision 1.0 17.04.2002 16:06:46 fs ************************************************************************/ <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: DriverManager.cxx,v $ * * $Revision: 1.10 $ * * last change: $Author: hr $ $Date: 2006-06-20 01:34:15 $ * * 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 _CONNECTIVITY_JAVA_SQL_DRIVERMANAGER_HXX_ #include "java/sql/DriverManager.hxx" #endif #ifndef _CONNECTIVITY_JAVA_TOOLS_HXX_ #include "java/tools.hxx" #endif using namespace connectivity; //************************************************************** //************ Class: java.sql.DriverManager //************************************************************** jclass java_sql_DriverManager::theClass = 0; java_sql_DriverManager::~java_sql_DriverManager() {} jclass java_sql_DriverManager::getMyClass() { // die Klasse muss nur einmal geholt werden, daher statisch if( !theClass ){ SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment geloescht worden!"); if( !t.pEnv ) return (jclass)0; jclass tempClass = t.pEnv->FindClass("java/sql/DriverManager"); OSL_ENSURE(tempClass,"Java : FindClass nicht erfolgreich!"); jclass globClass = (jclass)t.pEnv->NewGlobalRef( tempClass ); t.pEnv->DeleteLocalRef( tempClass ); saveClassRef( globClass ); } return theClass; } void java_sql_DriverManager::saveClassRef( jclass pClass ) { if( pClass==0 ) return; // der uebergebe Klassen-Handle ist schon global, daher einfach speichern theClass = pClass; } jobject java_sql_DriverManager::getDriver(const ::rtl::OUString &url) { jobject out(0); SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment geloescht worden!"); if( t.pEnv ) { jvalue args[1]; // Parameter konvertieren args[0].l = convertwchar_tToJavaString(t.pEnv,url); // temporaere Variable initialisieren static const char * cSignature = "(Ljava/lang/String;)Ljava/sql/Driver;"; static const char * cMethodName = "getDriver"; // Java-Call absetzen static jmethodID mID = t.pEnv->GetStaticMethodID( getMyClass(), cMethodName, cSignature );OSL_ENSURE(mID,"Unknown method id!"); if( mID ) { out = t.pEnv->CallStaticObjectMethod( getMyClass(), mID, args[0].l ); // und aufraeumen } //mID t.pEnv->DeleteLocalRef((jstring)args[0].l); return t.pEnv->NewGlobalRef( out ); } //t.pEnv return out; } void java_sql_DriverManager::setLoginTimeout(sal_Int32 _par0) { SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment geloescht worden!"); if( t.pEnv ) { // temporaere Variable initialisieren static const char * cSignature = "(I)V"; static const char * cMethodName = "setLoginTimeout"; // Java-Call absetzen static jmethodID mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );OSL_ENSURE(mID,"Unknown method id!"); if( mID ) t.pEnv->CallStaticVoidMethod(getMyClass(), mID, _par0); ThrowSQLException(t.pEnv,0); } //t.pEnv // ACHTUNG: der Aufrufer wird Eigentuemer des zurueckgelieferten Zeigers !!! } <commit_msg>INTEGRATION: CWS pchfix02 (1.10.60); FILE MERGED 2006/09/01 17:22:19 kaib 1.10.60.1: #i68856# Added header markers and pch files<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: DriverManager.cxx,v $ * * $Revision: 1.11 $ * * last change: $Author: obo $ $Date: 2006-09-17 02:46:14 $ * * 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_connectivity.hxx" #ifndef _CONNECTIVITY_JAVA_SQL_DRIVERMANAGER_HXX_ #include "java/sql/DriverManager.hxx" #endif #ifndef _CONNECTIVITY_JAVA_TOOLS_HXX_ #include "java/tools.hxx" #endif using namespace connectivity; //************************************************************** //************ Class: java.sql.DriverManager //************************************************************** jclass java_sql_DriverManager::theClass = 0; java_sql_DriverManager::~java_sql_DriverManager() {} jclass java_sql_DriverManager::getMyClass() { // die Klasse muss nur einmal geholt werden, daher statisch if( !theClass ){ SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment geloescht worden!"); if( !t.pEnv ) return (jclass)0; jclass tempClass = t.pEnv->FindClass("java/sql/DriverManager"); OSL_ENSURE(tempClass,"Java : FindClass nicht erfolgreich!"); jclass globClass = (jclass)t.pEnv->NewGlobalRef( tempClass ); t.pEnv->DeleteLocalRef( tempClass ); saveClassRef( globClass ); } return theClass; } void java_sql_DriverManager::saveClassRef( jclass pClass ) { if( pClass==0 ) return; // der uebergebe Klassen-Handle ist schon global, daher einfach speichern theClass = pClass; } jobject java_sql_DriverManager::getDriver(const ::rtl::OUString &url) { jobject out(0); SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment geloescht worden!"); if( t.pEnv ) { jvalue args[1]; // Parameter konvertieren args[0].l = convertwchar_tToJavaString(t.pEnv,url); // temporaere Variable initialisieren static const char * cSignature = "(Ljava/lang/String;)Ljava/sql/Driver;"; static const char * cMethodName = "getDriver"; // Java-Call absetzen static jmethodID mID = t.pEnv->GetStaticMethodID( getMyClass(), cMethodName, cSignature );OSL_ENSURE(mID,"Unknown method id!"); if( mID ) { out = t.pEnv->CallStaticObjectMethod( getMyClass(), mID, args[0].l ); // und aufraeumen } //mID t.pEnv->DeleteLocalRef((jstring)args[0].l); return t.pEnv->NewGlobalRef( out ); } //t.pEnv return out; } void java_sql_DriverManager::setLoginTimeout(sal_Int32 _par0) { SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment geloescht worden!"); if( t.pEnv ) { // temporaere Variable initialisieren static const char * cSignature = "(I)V"; static const char * cMethodName = "setLoginTimeout"; // Java-Call absetzen static jmethodID mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );OSL_ENSURE(mID,"Unknown method id!"); if( mID ) t.pEnv->CallStaticVoidMethod(getMyClass(), mID, _par0); ThrowSQLException(t.pEnv,0); } //t.pEnv // ACHTUNG: der Aufrufer wird Eigentuemer des zurueckgelieferten Zeigers !!! } <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you 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 . */ #include "MacabColumns.hxx" #include "MacabTable.hxx" #include "MacabTables.hxx" #include "MacabCatalog.hxx" #include "connectivity/sdbcx/VColumn.hxx" using namespace connectivity::macab; using namespace connectivity::sdbcx; using namespace connectivity; using namespace ::comphelper; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::sdbc; using namespace ::com::sun::star::container; using namespace ::com::sun::star::lang; // ------------------------------------------------------------------------- sdbcx::ObjectType MacabColumns::createObject(const ::rtl::OUString& _rName) { Reference< XResultSet > xResult = m_pTable->getConnection()->getMetaData()->getColumns( Any(), m_pTable->getSchema(), m_pTable->getTableName(), _rName); sdbcx::ObjectType xRet = NULL; if (xResult.is()) { Reference< XRow > xRow(xResult,UNO_QUERY); while (xResult->next()) { if (xRow->getString(4) == _rName) { OColumn* pRet = new OColumn( _rName, xRow->getString(6), xRow->getString(13), xRow->getString(12), xRow->getInt(11), xRow->getInt(7), xRow->getInt(9), xRow->getInt(5), sal_False, sal_False, sal_False, sal_True); xRet = pRet; break; } } } return xRet; } // ------------------------------------------------------------------------- void MacabColumns::impl_refresh() throw(RuntimeException) { m_pTable->refreshColumns(); } // ------------------------------------------------------------------------- MacabColumns::MacabColumns( MacabTable* _pTable, ::osl::Mutex& _rMutex, const TStringVector &_rVector) : sdbcx::OCollection(*_pTable, sal_True, _rMutex, _rVector), m_pTable(_pTable) { } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>connectivity: port macab driver to new OColumn, too<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you 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 . */ #include "MacabColumns.hxx" #include "MacabTable.hxx" #include "MacabTables.hxx" #include "MacabCatalog.hxx" #include "connectivity/sdbcx/VColumn.hxx" using namespace connectivity::macab; using namespace connectivity::sdbcx; using namespace connectivity; using namespace ::comphelper; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::sdbc; using namespace ::com::sun::star::container; using namespace ::com::sun::star::lang; // ------------------------------------------------------------------------- sdbcx::ObjectType MacabColumns::createObject(const ::rtl::OUString& _rName) { const Any aCatalog; const ::rtl::OUString sCatalogName; const ::rtl::OUString sSchemaName(m_pTable->getSchema()); const ::rtl::OUString sTableName(m_pTable->getTableName()); Reference< XResultSet > xResult = m_pTable->getConnection()->getMetaData()->getColumns( aCatalog, sSchemaName, sTableName, _rName); sdbcx::ObjectType xRet = NULL; if (xResult.is()) { Reference< XRow > xRow(xResult,UNO_QUERY); while (xResult->next()) { if (xRow->getString(4) == _rName) { OColumn* pRet = new OColumn( _rName, xRow->getString(6), xRow->getString(13), xRow->getString(12), xRow->getInt(11), xRow->getInt(7), xRow->getInt(9), xRow->getInt(5), sal_False, sal_False, sal_False, sal_True, sCatalogName, sSchemaName, sTableName); xRet = pRet; break; } } } return xRet; } // ------------------------------------------------------------------------- void MacabColumns::impl_refresh() throw(RuntimeException) { m_pTable->refreshColumns(); } // ------------------------------------------------------------------------- MacabColumns::MacabColumns( MacabTable* _pTable, ::osl::Mutex& _rMutex, const TStringVector &_rVector) : sdbcx::OCollection(*_pTable, sal_True, _rMutex, _rVector), m_pTable(_pTable) { } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: CDatabaseMetaData.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: rt $ $Date: 2005-09-08 06:59:19 $ * * 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 _CONNECTIVITY_CALC_DATABASEMETADATA_HXX_ #define _CONNECTIVITY_CALC_DATABASEMETADATA_HXX_ #ifndef _CONNECTIVITY_FILE_ODATABASEMETADATA_HXX_ #include "file/FDatabaseMetaData.hxx" #endif namespace connectivity { namespace calc { //************************************************************** //************ Class: java.sql.DatabaseMetaDataDate //************************************************************** class OCalcDatabaseMetaData : public file::ODatabaseMetaData { public: OCalcDatabaseMetaData(file::OConnection* _pCon); ~OCalcDatabaseMetaData(); virtual ::rtl::OUString SAL_CALL getURL( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet > SAL_CALL getColumns( const ::com::sun::star::uno::Any& catalog, const ::rtl::OUString& schemaPattern, const ::rtl::OUString& tableNamePattern, const ::rtl::OUString& columnNamePattern ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet > SAL_CALL getColumnPrivileges( const ::com::sun::star::uno::Any& catalog, const ::rtl::OUString& schema, const ::rtl::OUString& table, const ::rtl::OUString& columnNamePattern ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet > SAL_CALL getBestRowIdentifier( const ::com::sun::star::uno::Any& catalog, const ::rtl::OUString& schema, const ::rtl::OUString& table, sal_Int32 scope, sal_Bool nullable ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet > SAL_CALL getVersionColumns( const ::com::sun::star::uno::Any& catalog, const ::rtl::OUString& schema, const ::rtl::OUString& table ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet > SAL_CALL getPrimaryKeys( const ::com::sun::star::uno::Any& catalog, const ::rtl::OUString& schema, const ::rtl::OUString& table ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet > SAL_CALL getImportedKeys( const ::com::sun::star::uno::Any& catalog, const ::rtl::OUString& schema, const ::rtl::OUString& table ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet > SAL_CALL getExportedKeys( const ::com::sun::star::uno::Any& catalog, const ::rtl::OUString& schema, const ::rtl::OUString& table ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet > SAL_CALL getCrossReference( const ::com::sun::star::uno::Any& primaryCatalog, const ::rtl::OUString& primarySchema, const ::rtl::OUString& primaryTable, const ::com::sun::star::uno::Any& foreignCatalog, const ::rtl::OUString& foreignSchema, const ::rtl::OUString& foreignTable ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet > SAL_CALL getTypeInfo( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet > SAL_CALL getIndexInfo( const ::com::sun::star::uno::Any& catalog, const ::rtl::OUString& schema, const ::rtl::OUString& table, sal_Bool unique, sal_Bool approximate ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual sal_Int32 SAL_CALL getMaxBinaryLiteralLength( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual sal_Int32 SAL_CALL getMaxCharLiteralLength( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual sal_Int32 SAL_CALL getMaxColumnNameLength( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual sal_Int32 SAL_CALL getMaxColumnsInIndex( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual sal_Int32 SAL_CALL getMaxColumnsInTable( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet > SAL_CALL getTables( const ::com::sun::star::uno::Any& catalog, const ::rtl::OUString& schemaPattern, const ::rtl::OUString& tableNamePattern, const ::com::sun::star::uno::Sequence< ::rtl::OUString >& types ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); }; } } #endif // _CONNECTIVITY_CALC_DATABASEMETADATA_HXX_ <commit_msg>INTEGRATION: CWS dba24d (1.2.310); FILE MERGED 2007/11/21 12:39:24 oj 1.2.310.1: #i68854# impl TypeSettingInfo for Oracle and some clean up<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: CDatabaseMetaData.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2008-01-30 08:00: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 _CONNECTIVITY_CALC_DATABASEMETADATA_HXX_ #define _CONNECTIVITY_CALC_DATABASEMETADATA_HXX_ #ifndef _CONNECTIVITY_FILE_ODATABASEMETADATA_HXX_ #include "file/FDatabaseMetaData.hxx" #endif namespace connectivity { namespace calc { //************************************************************** //************ Class: java.sql.DatabaseMetaDataDate //************************************************************** class OCalcDatabaseMetaData : public file::ODatabaseMetaData { virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet > impl_getTypeInfo_throw(); virtual ::rtl::OUString SAL_CALL getURL( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet > SAL_CALL getColumns( const ::com::sun::star::uno::Any& catalog, const ::rtl::OUString& schemaPattern, const ::rtl::OUString& tableNamePattern, const ::rtl::OUString& columnNamePattern ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual sal_Int32 SAL_CALL getMaxBinaryLiteralLength( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual sal_Int32 SAL_CALL getMaxCharLiteralLength( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual sal_Int32 SAL_CALL getMaxColumnNameLength( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual sal_Int32 SAL_CALL getMaxColumnsInIndex( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual sal_Int32 SAL_CALL getMaxColumnsInTable( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet > SAL_CALL getTables( const ::com::sun::star::uno::Any& catalog, const ::rtl::OUString& schemaPattern, const ::rtl::OUString& tableNamePattern, const ::com::sun::star::uno::Sequence< ::rtl::OUString >& types ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); protected: virtual ~OCalcDatabaseMetaData(); public: OCalcDatabaseMetaData(file::OConnection* _pCon); }; } } #endif // _CONNECTIVITY_CALC_DATABASEMETADATA_HXX_ <|endoftext|>
<commit_before>#include <chrono> #include <list> #include <vector> #include <random> #include <iostream> #include<conio.h> using namespace std; class Timer { public: Timer() : beg_(clock_::now()) {} void reset() { beg_ = clock_::now(); } double elapsed() const { return std::chrono::duration_cast<ms_> (clock_::now() - beg_).count(); } private: typedef std::chrono::high_resolution_clock clock_; typedef std::chrono::duration<double, std::milli> ms_; std::chrono::time_point<clock_> beg_; }; struct EpicStruct { #define EpicStruct_SIZE 4 char m_memory[EpicStruct_SIZE]; EpicStruct() { } explicit EpicStruct(size_t val) { memset(m_memory, val % 127, sizeof(m_memory)); } void print() { for( int i = 0; i < EpicStruct_SIZE; ++i) printf("%d", m_memory[i]); } }; // !!!!!!!!!!!!!!! This is a bad implementation of a vector. !!!!!!!!!!!!!!!!!!!!!!! // !!!!!!!!!!!!!!! No, really it is a bad one. !!!!!!!!!!!!!!!!!!!!!!! //Provided just as an example so people get a general idea of what's under the hood. // Use this anywhere else besides 'demo' purposes and you deserve whatever bugs you get. template<class T> class MyVector { public: typedef T* iterator; MyVector() { m_AllocatedSize = 2; m_Size = 0; m_Data = new T[m_AllocatedSize]; } ~MyVector() { delete[] m_Data; } void push_back(T element) { //One element is guaranteed to be available for end() // + 1 for the new one // + 1 for the end() reserved space. if ((m_Size + 2) >= m_AllocatedSize) { //Grow by half ( this is what microsoft SDL vector does. I know because I checked the code ). // Don't trust me for it, go check. size_t newSize = m_AllocatedSize + m_AllocatedSize / 2; T* m_NewData = new T[newSize]; memcpy(m_NewData, m_Data, m_Size*sizeof(T)); delete[] m_Data; m_AllocatedSize = newSize; m_Data = m_NewData; } m_Data[m_Size++] = element; } iterator begin() { return m_Data; } iterator end() { return m_Data + m_Size; } //Taken from here: // // void rotate(iterator first, iterator n_first, iterator last) { iterator next = n_first; while(first != n_first) { swap(*first, *next); first++; next++; if(next == last) next = n_first; else if (first == n_first) n_first = next; } } //#define STL_WAY #define MY_WAY iterator insert(iterator& it, T value) { #ifdef STL_WAY // This is how STL does it, using rotate, but not using temporary variables that hold ELEMENTS. // Uncomment the define above in order to enable this behaviour. size_t off = it - m_Data; push_back(value); it = m_Data+off; rotate(it, end() - 1, end()); #elif defined(MY_WAY) // Faster insert // Consumes more memory in theory due to extra temporary variables that hold ELEMENTS(tmp and tmp2) size_t off = it - m_Data; push_back(value); iterator new_location = m_Data+off; it = new_location; T tmp = *(end() - 1); while(new_location != end()) { std::swap(tmp, *new_location); new_location++; } #else //memmove way size_t off = it - m_Data; push_back(value); iterator new_location = m_Data+off; it = new_location; memmove(it+1, it, (m_Size-off)*sizeof(T)); (*it)=value; #endif return it; } size_t size() { return m_Size; } private: size_t m_Size; size_t m_AllocatedSize; T* m_Data; }; template<class T> double test_container(size_t count) { T container; T::iterator it; srand(42); Timer tmr; container.push_back(EpicStruct(0)); for (size_t i = 0; i < count; ++i) { size_t pos = rand() % container.size(); it = container.begin(); for (size_t p = 0; p < pos; ++p) { volatile char temp = (*it).m_memory[0]; //Touch each element from 0 to pos by reading it in a temp. This won't get optimized away due to volatile it++; } container.insert(it, EpicStruct(i)); } double t = tmr.elapsed(); #if _DEBUG //If you want you can also print or save to file the struct. Just to check that they are the same in the end. for(it = container.begin(); it != container.end(); ++it) (*it).print(); printf("\n"); #endif return t; } int main() { size_t count = 99999; double t = test_container<vector<EpicStruct>>(count); printf("Elapsed time vector: %.2f ms\n", t); t = test_container<list<EpicStruct>>(count); printf("Elapsed time list: %.2f ms\n", t); t = test_container<MyVector<EpicStruct>>(count); printf("Elapsed time MyVector: %.2f ms\n", t); _getch(); return 0; } <commit_msg>Update list_vs_vector.cpp<commit_after>#include <chrono> #include <list> #include <vector> #include <random> #include <iostream> #include<conio.h> using namespace std; class Timer { public: Timer() : beg_(clock_::now()) {} void reset() { beg_ = clock_::now(); } double elapsed() const { return std::chrono::duration_cast<ms_> (clock_::now() - beg_).count(); } private: typedef std::chrono::high_resolution_clock clock_; typedef std::chrono::duration<double, std::milli> ms_; std::chrono::time_point<clock_> beg_; }; struct EpicStruct { #define EpicStruct_SIZE 4 char m_memory[EpicStruct_SIZE]; EpicStruct() { } explicit EpicStruct(size_t val) { memset(m_memory, val % 127, sizeof(m_memory)); } void print() { for( int i = 0; i < EpicStruct_SIZE; ++i) printf("%d", m_memory[i]); } }; // !!!!!!!!!!!!!!! This is a bad implementation of a vector. !!!!!!!!!!!!!!!!!!!!!!! // !!!!!!!!!!!!!!! No, really it is a bad one. !!!!!!!!!!!!!!!!!!!!!!! //Provided just as an example so people get a general idea of what's under the hood. // Use this anywhere else besides 'demo' purposes and you deserve whatever bugs you get. template<class T> class MyVector { public: typedef T* iterator; MyVector() { m_AllocatedSize = 2; m_Size = 0; m_Data = new T[m_AllocatedSize]; } ~MyVector() { delete[] m_Data; } void push_back(T element) { //One element is guaranteed to be available for end() // + 1 for the new one // + 1 for the end() reserved space. if ((m_Size + 2) >= m_AllocatedSize) { //Grow by half ( this is what microsoft SDL vector does. I know because I checked the code ). // Don't trust me for it, go check. size_t newSize = m_AllocatedSize + m_AllocatedSize / 2; T* m_NewData = new T[newSize]; memcpy(m_NewData, m_Data, m_Size*sizeof(T)); delete[] m_Data; m_AllocatedSize = newSize; m_Data = m_NewData; } m_Data[m_Size++] = element; } iterator begin() { return m_Data; } iterator end() { return m_Data + m_Size; } //Taken from here: // // void rotate(iterator first, iterator n_first, iterator last) { iterator next = n_first; while(first != n_first) { swap(*first, *next); first++; next++; if(next == last) next = n_first; else if (first == n_first) n_first = next; } } //#define STL_WAY #define MY_WAY iterator insert(iterator& it, T value) { #ifdef STL_WAY // This is how STL does it, using rotate, but not using temporary variables that hold ELEMENTS. // Uncomment the define above in order to enable this behaviour. size_t off = it - m_Data; push_back(value); it = m_Data+off; rotate(it, end() - 1, end()); #elif defined(MY_WAY) // Faster insert // Consumes more memory in theory due to extra temporary variables that hold ELEMENTS(tmp and tmp2) size_t off = it - m_Data; push_back(value); iterator new_location = m_Data+off; it = new_location; T tmp = *(end() - 1); while(new_location != end()) { std::swap(tmp, *new_location); new_location++; } #else //memmove way size_t off = it - m_Data; push_back(value); iterator new_location = m_Data+off; it = new_location; memmove(it+1, it, (m_Size-off)*sizeof(T)); (*it)=value; #endif return it; } size_t size() { return m_Size; } private: size_t m_Size; size_t m_AllocatedSize; T* m_Data; }; template<class T> void insert(T& container,typename T::iterator it, EpicStruct value) { container.insert(it, value); } #define IMPROVE_STL_VECTOR #ifdef IMPROVE_STL_VECTOR template<> void insert(vector<EpicStruct>& container, vector<EpicStruct>::iterator it, EpicStruct value) { size_t offset = it-container.begin(); container.push_back(value); it = container.begin() + offset; while(it != container.end()) { std::swap(value, *it); it++; } } #endif template<class T> double test_container(size_t count) { T container; T::iterator it; srand(42); Timer tmr; container.push_back(EpicStruct(0)); for (size_t i = 0; i < count; ++i) { size_t pos = rand() % container.size(); it = container.begin(); for (size_t p = 0; p < pos; ++p) { volatile char temp = (*it).m_memory[0]; //Touch each element from 0 to pos by reading it in a temp. This won't get optimized away due to volatile it++; } //container.insert(it, EpicStruct(i)); insert(container, it, EpicStruct(i)); } double t = tmr.elapsed(); #if _DEBUG //If you want you can also print or save to file the struct. Just to check that they are the same in the end. for(it = container.begin(); it != container.end(); ++it) (*it).print(); printf("\n"); #endif return t; } int main() { size_t count = 99999; double t = test_container<vector<EpicStruct>>(count); printf("Elapsed time vector: %.2f ms\n", t); t = test_container<list<EpicStruct>>(count); printf("Elapsed time list: %.2f ms\n", t); t = test_container<MyVector<EpicStruct>>(count); printf("Elapsed time MyVector: %.2f ms\n", t); _getch(); return 0; } <|endoftext|>
<commit_before>// This sets some hard-coded ACLs in the given drive #include <stdio.h> #include "kinetic/kinetic.h" using kinetic::KineticConnectionFactory; using kinetic::Status; using kinetic::KineticRecord; using kinetic::ACL; using kinetic::Domain; using std::list; using std::make_shared; using std::unique_ptr; int main(int argc, char* argv[]) { if (argc != 3) { printf("%s: <host> <port>\n", argv[0]); return 1; } const char* host = argv[1]; int port = atoi(argv[2]); kinetic::ConnectionOptions options; options.host = host; options.port = port; options.user_id = 1; options.hmac_key = "asdfasdf"; kinetic::KineticConnectionFactory kinetic_connection_factory = kinetic::NewKineticConnectionFactory(); unique_ptr<kinetic::ConnectionHandle> connection; if (!kinetic_connection_factory.NewConnection(options, 5, connection).ok()) { printf("Unable to connect\n"); return 1; } Domain domain1 = {.offset = 0, .value = "", .roles = {kinetic::GETLOG}}; std::list<Domain> acl1_domains = { domain1, }; ACL acl1; acl1.client_id = 1000; acl1.hmac_key = "foobarbaz"; acl1.domains = acl1_domains; Domain domain2 = {.offset = 0, .value = "", .roles = { kinetic::READ, kinetic::WRITE, kinetic::DELETE, kinetic::RANGE, kinetic::SETUP, kinetic::P2POP, kinetic::GETLOG, kinetic::SECURITY}, }; std::list<Domain> acl2_domains = { domain2 }; ACL acl2; acl2.client_id = 1; acl2.hmac_key = "asdfasdf"; acl2.domains = acl2_domains; auto acls = make_shared<list<ACL>>(); acls->push_back(acl2); acls->push_back(acl1); printf("Setting ACLs..."); if (connection->blocking().SetACLs(acls).ok()) { printf("Success!\n"); return 0; } else { printf("Error\n"); return 1; } } <commit_msg>Updated set_acls<commit_after>// This sets some hard-coded ACLs in the given drive #include <stdio.h> #include "kinetic/kinetic.h" using kinetic::KineticConnectionFactory; using kinetic::Status; using kinetic::KineticRecord; using kinetic::ACL; using kinetic::Domain; using std::list; using std::make_shared; using std::unique_ptr; int example_main(unique_ptr<kinetic::ConnectionHandle> connection, int argc, char* argv[]) { Domain domain1 = {.offset = 0, .value = "", .roles = {kinetic::GETLOG}}; std::list<Domain> acl1_domains = { domain1, }; ACL acl1; acl1.client_id = 1000; acl1.hmac_key = "foobarbaz"; acl1.domains = acl1_domains; Domain domain2 = {.offset = 0, .value = "", .roles = { kinetic::READ, kinetic::WRITE, kinetic::DELETE, kinetic::RANGE, kinetic::SETUP, kinetic::P2POP, kinetic::GETLOG, kinetic::SECURITY}, }; std::list<Domain> acl2_domains = { domain2 }; ACL acl2; acl2.client_id = 1; acl2.hmac_key = "asdfasdf"; acl2.domains = acl2_domains; auto acls = make_shared<list<ACL>>(); acls->push_back(acl2); acls->push_back(acl1); printf("Setting ACLs..."); if (connection->blocking().SetACLs(acls).ok()) { printf("Success!\n"); return 0; } else { printf("Error\n"); return 1; } } <|endoftext|>
<commit_before>static void error ( int error , const char * description ) { fputs(description,stderr); } static void resize ( GLFWwindow * window , int width , int height ) { glViewport(0,0,width,height); updateProjection(PROJECTION); } static void keyboard ( GLFWwindow * window , int key , int scancode , int action , int mods ) { switch (key) { default: return; // http://www.glfw.org/docs/latest/group__keys.html // http://www.glfw.org/docs/latest/group__mods.html case GLFW_KEY_A: if (mods == GLFW_MOD_CONTROL) switch (action) { // toggle axis case GLFW_PRESS: axis = not axis; break; case GLFW_RELEASE: moveL = false; break; default: break; } else switch (action) { // strafe left case GLFW_PRESS: case GLFW_REPEAT: moveL = true; break; case GLFW_RELEASE: moveL = false; break; default: break; } break; case GLFW_KEY_C: // toggle culling if (mods == GLFW_MOD_CONTROL and action == GLFW_PRESS) { cull = not cull; if (cull) glEnable(GL_CULL_FACE); else glDisable(GL_CULL_FACE); } break; case GLFW_KEY_D: // strafe right switch (action) { case GLFW_PRESS: case GLFW_REPEAT: moveR = true; break; case GLFW_RELEASE: moveR = false; break; default: break; } break; case GLFW_KEY_G: // toggle grid if (mods == GLFW_MOD_CONTROL and action == GLFW_PRESS) grid = not grid; break; case GLFW_KEY_H: // help if (action == GLFW_PRESS) { putchar('\n'); puts("Navigation"); puts("arrows look around"); puts("scroll zoom"); puts("a,d,s,w move camera"); puts("keypad move selection"); putchar('\n'); puts("Selections"); puts("0 light source"); puts("1 skeleton"); puts("2 colorcube"); puts("3 sierpinski tetrahedron"); putchar('\n'); puts("Controls"); puts("ctrl-scroll adjust FOV"); puts("ctrl-# toggle selection"); puts("ctrl-a toggle axis"); puts("ctrl-c toggle culling"); puts("ctrl-g toggle grid"); puts("ctrl-h help"); puts("ctrl-p animate selection"); puts("ctrl-q quit"); puts("ctrl-w toggle wireframe"); } break; case GLFW_KEY_P: if (mods == GLFW_MOD_CONTROL and action == GLFW_PRESS) skeletonPlay = not skeletonPlay; break; case GLFW_KEY_Q: // quit if (mods == GLFW_MOD_CONTROL and action == GLFW_PRESS) glfwSetWindowShouldClose(window,GL_TRUE); break; case GLFW_KEY_S: switch (action) { // move backward case GLFW_PRESS: case GLFW_REPEAT: moveB = true; break; case GLFW_RELEASE: moveB = false; break; default: break; } break; case GLFW_KEY_W: if (mods == GLFW_MOD_CONTROL) switch (action) { // toggle wireframe case GLFW_PRESS: wire = not wire; if (wire) glPolygonMode(GL_FRONT_AND_BACK,GL_LINE); else glPolygonMode(GL_FRONT_AND_BACK,GL_FILL); break; case GLFW_RELEASE: moveF = false; break; default: break; } else switch (action) { // move forward case GLFW_PRESS: case GLFW_REPEAT: moveF = true; break; case GLFW_RELEASE: moveF = false; break; default: break; } break; case GLFW_KEY_PAGE_UP: // ascend switch (action) { case GLFW_PRESS: case GLFW_REPEAT: moveU = true; break; case GLFW_RELEASE: moveU = false; break; default: break; } break; case GLFW_KEY_PAGE_DOWN: // descend switch (action) { case GLFW_PRESS: case GLFW_REPEAT: moveD = true; break; case GLFW_RELEASE: moveD = false; break; default: break; } break; case GLFW_KEY_HOME: // orbit CW switch (action) { case GLFW_PRESS: case GLFW_REPEAT: orbitCW = true; break; case GLFW_RELEASE: orbitCW = false; break; default: break; } break; case GLFW_KEY_END: // orbit CCW switch (action) { case GLFW_PRESS: case GLFW_REPEAT: orbitCCW = true; break; case GLFW_RELEASE: orbitCCW = false; break; default: break; } break; case GLFW_KEY_LEFT: // look left switch (action) { case GLFW_PRESS: case GLFW_REPEAT: lookL = true; break; case GLFW_RELEASE: lookL = false; break; default: break; } break; case GLFW_KEY_RIGHT: // look right switch (action) { case GLFW_PRESS: case GLFW_REPEAT: lookR = true; break; case GLFW_RELEASE: lookR = false; break; default: break; } break; case GLFW_KEY_DOWN: // look down switch (action) { case GLFW_PRESS: case GLFW_REPEAT: lookD = true; break; case GLFW_RELEASE: lookD = false; break; default: break; } break; case GLFW_KEY_UP: // look up switch (action) { case GLFW_PRESS: case GLFW_REPEAT: lookU = true; break; case GLFW_RELEASE: lookU = false; break; default: break; } break; case GLFW_KEY_0: if (mods == GLFW_MOD_CONTROL) { if (action == GLFW_PRESS) toggleLight(); } else selection = 0; break; case GLFW_KEY_1: if (mods == GLFW_MOD_CONTROL) { if (action == GLFW_PRESS) skeleton = not skeleton; } else selection = 1; break; case GLFW_KEY_2: if (mods == GLFW_MOD_CONTROL) { if (action == GLFW_PRESS) colorcube = not colorcube; } else selection = 2; break; case GLFW_KEY_3: if (mods == GLFW_MOD_CONTROL) { if (action == GLFW_PRESS) sierpinski = not sierpinski; } else selection = 3; break; case GLFW_KEY_SPACE: pEye = glm::translate(glm::mat4(),glm::vec3(5,6,5))*pSelection[selection]; pFocus = pSelection[selection]; break; case GLFW_KEY_KP_2: // move back switch (action) { case GLFW_PRESS: case GLFW_REPEAT: selectionMoveB[selection] = true; break; case GLFW_RELEASE: selectionMoveB[selection] = false; break; default: return; } break; case GLFW_KEY_KP_4: // move left switch (action) { case GLFW_PRESS: case GLFW_REPEAT: selectionMoveL[selection] = true; break; case GLFW_RELEASE: selectionMoveL[selection] = false; break; default: return; } break; case GLFW_KEY_KP_6: // move right switch (action) { case GLFW_PRESS: case GLFW_REPEAT: selectionMoveR[selection] = true; break; case GLFW_RELEASE: selectionMoveR[selection] = false; break; default: return; } break; case GLFW_KEY_KP_8: // move forth switch (action) { case GLFW_PRESS: case GLFW_REPEAT: selectionMoveF[selection] = true; break; case GLFW_RELEASE: selectionMoveF[selection] = false; break; default: return; } break; case GLFW_KEY_KP_SUBTRACT: // move down switch (action) { case GLFW_PRESS: case GLFW_REPEAT: selectionMoveD[selection] = true; break; case GLFW_RELEASE: selectionMoveD[selection] = false; break; default: return; } break; case GLFW_KEY_KP_ADD: // move up switch (action) { case GLFW_PRESS: case GLFW_REPEAT: selectionMoveU[selection] = true; break; case GLFW_RELEASE: selectionMoveU[selection] = false; break; default: return; } break; } } static void click ( GLFWwindow * window , int button , int action , int mods ) { switch (button) { default: return; // http://www.glfw.org/docs/latest/group__buttons.html // http://www.glfw.org/docs/latest/group__mods.html case GLFW_MOUSE_BUTTON_LEFT: case GLFW_MOUSE_BUTTON_MIDDLE: case GLFW_MOUSE_BUTTON_RIGHT: break; } } static void hover ( GLFWwindow * window , double xpos , double ypos ) { vCursor = glm::vec3(xpos,ypos,1)-pCursor; pCursor = glm::vec3(xpos,ypos,1); } static void scroll ( GLFWwindow * window , double xoffset , double yoffset ) { if (glfwGetKey(window,GLFW_KEY_LEFT_CONTROL) == GLFW_PRESS or glfwGetKey(window,GLFW_KEY_RIGHT_CONTROL) == GLFW_PRESS) { const GLfloat s = rad(1.0); if (yoffset > 0) lens -= s; else if (yoffset < 0) lens += s; } else { const GLfloat s = 0.05; if (yoffset > 0) zoom += s; else if (yoffset < 0) zoom -= s; } } <commit_msg>Document PgUp and PgDn controls<commit_after>static void error ( int error , const char * description ) { fputs(description,stderr); } static void resize ( GLFWwindow * window , int width , int height ) { glViewport(0,0,width,height); updateProjection(PROJECTION); } static void keyboard ( GLFWwindow * window , int key , int scancode , int action , int mods ) { switch (key) { default: return; // http://www.glfw.org/docs/latest/group__keys.html // http://www.glfw.org/docs/latest/group__mods.html case GLFW_KEY_A: if (mods == GLFW_MOD_CONTROL) switch (action) { // toggle axis case GLFW_PRESS: axis = not axis; break; case GLFW_RELEASE: moveL = false; break; default: break; } else switch (action) { // strafe left case GLFW_PRESS: case GLFW_REPEAT: moveL = true; break; case GLFW_RELEASE: moveL = false; break; default: break; } break; case GLFW_KEY_C: // toggle culling if (mods == GLFW_MOD_CONTROL and action == GLFW_PRESS) { cull = not cull; if (cull) glEnable(GL_CULL_FACE); else glDisable(GL_CULL_FACE); } break; case GLFW_KEY_D: // strafe right switch (action) { case GLFW_PRESS: case GLFW_REPEAT: moveR = true; break; case GLFW_RELEASE: moveR = false; break; default: break; } break; case GLFW_KEY_G: // toggle grid if (mods == GLFW_MOD_CONTROL and action == GLFW_PRESS) grid = not grid; break; case GLFW_KEY_H: // help if (action == GLFW_PRESS) { putchar('\n'); puts("Navigation"); puts("arrows look around"); puts("scroll zoom"); puts("a,d,s,w,PgUp,PgDn move camera"); puts("keypad move selection"); putchar('\n'); puts("Selections"); puts("0 light source"); puts("1 skeleton"); puts("2 colorcube"); puts("3 sierpinski tetrahedron"); putchar('\n'); puts("Controls"); puts("ctrl-scroll adjust FOV"); puts("ctrl-# toggle selection"); puts("ctrl-a toggle axis"); puts("ctrl-c toggle culling"); puts("ctrl-g toggle grid"); puts("ctrl-h help"); puts("ctrl-p animate selection"); puts("ctrl-q quit"); puts("ctrl-w toggle wireframe"); } break; case GLFW_KEY_P: if (mods == GLFW_MOD_CONTROL and action == GLFW_PRESS) skeletonPlay = not skeletonPlay; break; case GLFW_KEY_Q: // quit if (mods == GLFW_MOD_CONTROL and action == GLFW_PRESS) glfwSetWindowShouldClose(window,GL_TRUE); break; case GLFW_KEY_S: switch (action) { // move backward case GLFW_PRESS: case GLFW_REPEAT: moveB = true; break; case GLFW_RELEASE: moveB = false; break; default: break; } break; case GLFW_KEY_W: if (mods == GLFW_MOD_CONTROL) switch (action) { // toggle wireframe case GLFW_PRESS: wire = not wire; if (wire) glPolygonMode(GL_FRONT_AND_BACK,GL_LINE); else glPolygonMode(GL_FRONT_AND_BACK,GL_FILL); break; case GLFW_RELEASE: moveF = false; break; default: break; } else switch (action) { // move forward case GLFW_PRESS: case GLFW_REPEAT: moveF = true; break; case GLFW_RELEASE: moveF = false; break; default: break; } break; case GLFW_KEY_PAGE_UP: // ascend switch (action) { case GLFW_PRESS: case GLFW_REPEAT: moveU = true; break; case GLFW_RELEASE: moveU = false; break; default: break; } break; case GLFW_KEY_PAGE_DOWN: // descend switch (action) { case GLFW_PRESS: case GLFW_REPEAT: moveD = true; break; case GLFW_RELEASE: moveD = false; break; default: break; } break; case GLFW_KEY_HOME: // orbit CW switch (action) { case GLFW_PRESS: case GLFW_REPEAT: orbitCW = true; break; case GLFW_RELEASE: orbitCW = false; break; default: break; } break; case GLFW_KEY_END: // orbit CCW switch (action) { case GLFW_PRESS: case GLFW_REPEAT: orbitCCW = true; break; case GLFW_RELEASE: orbitCCW = false; break; default: break; } break; case GLFW_KEY_LEFT: // look left switch (action) { case GLFW_PRESS: case GLFW_REPEAT: lookL = true; break; case GLFW_RELEASE: lookL = false; break; default: break; } break; case GLFW_KEY_RIGHT: // look right switch (action) { case GLFW_PRESS: case GLFW_REPEAT: lookR = true; break; case GLFW_RELEASE: lookR = false; break; default: break; } break; case GLFW_KEY_DOWN: // look down switch (action) { case GLFW_PRESS: case GLFW_REPEAT: lookD = true; break; case GLFW_RELEASE: lookD = false; break; default: break; } break; case GLFW_KEY_UP: // look up switch (action) { case GLFW_PRESS: case GLFW_REPEAT: lookU = true; break; case GLFW_RELEASE: lookU = false; break; default: break; } break; case GLFW_KEY_0: if (mods == GLFW_MOD_CONTROL) { if (action == GLFW_PRESS) toggleLight(); } else selection = 0; break; case GLFW_KEY_1: if (mods == GLFW_MOD_CONTROL) { if (action == GLFW_PRESS) skeleton = not skeleton; } else selection = 1; break; case GLFW_KEY_2: if (mods == GLFW_MOD_CONTROL) { if (action == GLFW_PRESS) colorcube = not colorcube; } else selection = 2; break; case GLFW_KEY_3: if (mods == GLFW_MOD_CONTROL) { if (action == GLFW_PRESS) sierpinski = not sierpinski; } else selection = 3; break; case GLFW_KEY_SPACE: pEye = glm::translate(glm::mat4(),glm::vec3(5,6,5))*pSelection[selection]; pFocus = pSelection[selection]; break; case GLFW_KEY_KP_2: // move back switch (action) { case GLFW_PRESS: case GLFW_REPEAT: selectionMoveB[selection] = true; break; case GLFW_RELEASE: selectionMoveB[selection] = false; break; default: return; } break; case GLFW_KEY_KP_4: // move left switch (action) { case GLFW_PRESS: case GLFW_REPEAT: selectionMoveL[selection] = true; break; case GLFW_RELEASE: selectionMoveL[selection] = false; break; default: return; } break; case GLFW_KEY_KP_6: // move right switch (action) { case GLFW_PRESS: case GLFW_REPEAT: selectionMoveR[selection] = true; break; case GLFW_RELEASE: selectionMoveR[selection] = false; break; default: return; } break; case GLFW_KEY_KP_8: // move forth switch (action) { case GLFW_PRESS: case GLFW_REPEAT: selectionMoveF[selection] = true; break; case GLFW_RELEASE: selectionMoveF[selection] = false; break; default: return; } break; case GLFW_KEY_KP_SUBTRACT: // move down switch (action) { case GLFW_PRESS: case GLFW_REPEAT: selectionMoveD[selection] = true; break; case GLFW_RELEASE: selectionMoveD[selection] = false; break; default: return; } break; case GLFW_KEY_KP_ADD: // move up switch (action) { case GLFW_PRESS: case GLFW_REPEAT: selectionMoveU[selection] = true; break; case GLFW_RELEASE: selectionMoveU[selection] = false; break; default: return; } break; } } static void click ( GLFWwindow * window , int button , int action , int mods ) { switch (button) { default: return; // http://www.glfw.org/docs/latest/group__buttons.html // http://www.glfw.org/docs/latest/group__mods.html case GLFW_MOUSE_BUTTON_LEFT: case GLFW_MOUSE_BUTTON_MIDDLE: case GLFW_MOUSE_BUTTON_RIGHT: break; } } static void hover ( GLFWwindow * window , double xpos , double ypos ) { vCursor = glm::vec3(xpos,ypos,1)-pCursor; pCursor = glm::vec3(xpos,ypos,1); } static void scroll ( GLFWwindow * window , double xoffset , double yoffset ) { if (glfwGetKey(window,GLFW_KEY_LEFT_CONTROL) == GLFW_PRESS or glfwGetKey(window,GLFW_KEY_RIGHT_CONTROL) == GLFW_PRESS) { const GLfloat s = rad(1.0); if (yoffset > 0) lens -= s; else if (yoffset < 0) lens += s; } else { const GLfloat s = 0.05; if (yoffset > 0) zoom += s; else if (yoffset < 0) zoom -= s; } } <|endoftext|>
<commit_before>/////////////////////////////////////////////////////////////////////////////////////////////////// // OpenGL Mathematics Copyright (c) 2005 - 2012 G-Truc Creation (www.g-truc.net) /////////////////////////////////////////////////////////////////////////////////////////////////// // Created : 2011-01-15 // Updated : 2011-01-15 // Licence : This source is under MIT licence // File : test/core/func_matrix.cpp /////////////////////////////////////////////////////////////////////////////////////////////////// #include <glm/glm.hpp> int test_matrixCompMult() { int Error(0); { glm::mat2 m(0, 1, 2, 3); glm::mat2 n = glm::matrixCompMult(m, m); Error += n == glm::mat2(0, 1, 4, 9) ? 0 : 1; } { glm::mat2x3 m(0, 1, 2, 3, 4, 5); glm::mat2x3 n = glm::matrixCompMult(m, m); Error += n == glm::mat2x3(0, 1, 4, 9, 16, 25) ? 0 : 1; } { glm::mat2x4 m(0, 1, 2, 3, 4, 5, 6, 7); glm::mat2x4 n = glm::matrixCompMult(m, m); Error += n == glm::mat2x4(0, 1, 4, 9, 16, 25, 36, 49) ? 0 : 1; } { glm::mat3 m(0, 1, 2, 3, 4, 5, 6, 7, 8); glm::mat3 n = glm::matrixCompMult(m, m); Error += n == glm::mat3(0, 1, 4, 9, 16, 25, 36, 49, 64) ? 0 : 1; } { glm::mat3x2 m(0, 1, 2, 3, 4, 5); glm::mat3x2 n = glm::matrixCompMult(m, m); Error += n == glm::mat3x2(0, 1, 4, 9, 16, 25) ? 0 : 1; } { glm::mat3x4 m(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11); glm::mat3x4 n = glm::matrixCompMult(m, m); Error += n == glm::mat3x4(0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121) ? 0 : 1; } { glm::mat4 m(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15); glm::mat4 n = glm::matrixCompMult(m, m); Error += n == glm::mat4(0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225) ? 0 : 1; } { glm::mat4x2 m(0, 1, 2, 3, 4, 5, 6, 7); glm::mat4x2 n = glm::matrixCompMult(m, m); Error += n == glm::mat4x2(0, 1, 4, 9, 16, 25, 36, 49) ? 0 : 1; } { glm::mat4x3 m(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11); glm::mat4x3 n = glm::matrixCompMult(m, m); Error += n == glm::mat4x3(0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121) ? 0 : 1; } return Error; } int test_outerProduct() { return 0; } int test_transpose() { return 0; } int test_determinant() { return 0; } int test_inverse() { int Failed(0); glm::mat4x4 A4x4( glm::vec4(1, 0, 1, 0), glm::vec4(0, 1, 0, 0), glm::vec4(0, 0, 1, 0), glm::vec4(0, 0, 0, 1)); glm::mat4x4 B4x4 = glm::inverse(A4x4); glm::mat4x4 I4x4 = A4x4 * B4x4; Failed += I4x4 == glm::mat4x4(1) ? 0 : 1; glm::mat3x3 A3x3( glm::vec3(1, 0, 1), glm::vec3(0, 1, 0), glm::vec3(0, 0, 1)); glm::mat3x3 B3x3 = glm::inverse(A3x3); glm::mat3x3 I3x3 = A3x3 * B3x3; Failed += I3x3 == glm::mat3x3(1) ? 0 : 1; glm::mat2x2 A2x2( glm::vec2(1, 1), glm::vec2(0, 1)); glm::mat2x2 B2x2 = glm::inverse(A2x2); glm::mat2x2 I2x2 = A2x2 * B2x2; Failed += I2x2 == glm::mat2x2(1) ? 0 : 1; return Failed; } int main() { int Failed = 0; Failed += test_matrixCompMult(); Failed += test_outerProduct(); Failed += test_transpose(); Failed += test_determinant(); Failed += test_inverse(); return Failed; } <commit_msg>Added transpose test<commit_after>/////////////////////////////////////////////////////////////////////////////////////////////////// // OpenGL Mathematics Copyright (c) 2005 - 2012 G-Truc Creation (www.g-truc.net) /////////////////////////////////////////////////////////////////////////////////////////////////// // Created : 2011-01-15 // Updated : 2012-05-02 // Licence : This source is under MIT licence // File : test/core/func_matrix.cpp /////////////////////////////////////////////////////////////////////////////////////////////////// #include <glm/glm.hpp> int test_matrixCompMult() { int Error(0); { glm::mat2 m(0, 1, 2, 3); glm::mat2 n = glm::matrixCompMult(m, m); Error += n == glm::mat2(0, 1, 4, 9) ? 0 : 1; } { glm::mat2x3 m(0, 1, 2, 3, 4, 5); glm::mat2x3 n = glm::matrixCompMult(m, m); Error += n == glm::mat2x3(0, 1, 4, 9, 16, 25) ? 0 : 1; } { glm::mat2x4 m(0, 1, 2, 3, 4, 5, 6, 7); glm::mat2x4 n = glm::matrixCompMult(m, m); Error += n == glm::mat2x4(0, 1, 4, 9, 16, 25, 36, 49) ? 0 : 1; } { glm::mat3 m(0, 1, 2, 3, 4, 5, 6, 7, 8); glm::mat3 n = glm::matrixCompMult(m, m); Error += n == glm::mat3(0, 1, 4, 9, 16, 25, 36, 49, 64) ? 0 : 1; } { glm::mat3x2 m(0, 1, 2, 3, 4, 5); glm::mat3x2 n = glm::matrixCompMult(m, m); Error += n == glm::mat3x2(0, 1, 4, 9, 16, 25) ? 0 : 1; } { glm::mat3x4 m(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11); glm::mat3x4 n = glm::matrixCompMult(m, m); Error += n == glm::mat3x4(0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121) ? 0 : 1; } { glm::mat4 m(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15); glm::mat4 n = glm::matrixCompMult(m, m); Error += n == glm::mat4(0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225) ? 0 : 1; } { glm::mat4x2 m(0, 1, 2, 3, 4, 5, 6, 7); glm::mat4x2 n = glm::matrixCompMult(m, m); Error += n == glm::mat4x2(0, 1, 4, 9, 16, 25, 36, 49) ? 0 : 1; } { glm::mat4x3 m(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11); glm::mat4x3 n = glm::matrixCompMult(m, m); Error += n == glm::mat4x3(0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121) ? 0 : 1; } return Error; } int test_outerProduct() { return 0; } int test_transpose() { int Error(0); { glm::mat2 m(0, 1, 2, 3); glm::mat2 t = glm::transpose(m); Error += t == glm::mat2(0, 2, 1, 3) ? 0 : 1; } { glm::mat2x3 m(0, 1, 2, 3, 4, 5); glm::mat3x2 t = glm::transpose(m); Error += t == glm::mat3x2(0, 3, 1, 4, 2, 5) ? 0 : 1; } { glm::mat2x4 m(0, 1, 2, 3, 4, 5, 6, 7); glm::mat4x2 t = glm::transpose(m); Error += t == glm::mat4x2(0, 4, 1, 5, 2, 6, 3, 7) ? 0 : 1; } { glm::mat3 m(0, 1, 2, 3, 4, 5, 6, 7, 8); glm::mat3 t = glm::transpose(m); Error += t == glm::mat3(0, 3, 6, 1, 4, 7, 2, 5, 8) ? 0 : 1; } { glm::mat3x2 m(0, 1, 2, 3, 4, 5); glm::mat2x3 t = glm::transpose(m); Error += t == glm::mat2x3(0, 3, 1, 4, 2, 5) ? 0 : 1; } { glm::mat3x4 m(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11); glm::mat4x3 t = glm::transpose(m); Error += t == glm::mat4x3(0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11) ? 0 : 1; } { glm::mat4 m(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15); glm::mat4 t = glm::transpose(m); Error += t == glm::mat4(0, 4, 8, 12, 1, 5, 9, 13, 2, 6, 10, 14, 3, 7, 11, 15) ? 0 : 1; } { glm::mat4x2 m(0, 1, 2, 3, 4, 5, 6, 7); glm::mat2x4 t = glm::transpose(m); Error += t == glm::mat2x4(0, 4, 1, 5, 2, 6, 3, 7) ? 0 : 1; } { glm::mat4x3 m(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11); glm::mat3x4 t = glm::transpose(m); Error += t == glm::mat3x4(0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11) ? 0 : 1; } return Error; } int test_determinant() { return 0; } int test_inverse() { int Failed(0); glm::mat4x4 A4x4( glm::vec4(1, 0, 1, 0), glm::vec4(0, 1, 0, 0), glm::vec4(0, 0, 1, 0), glm::vec4(0, 0, 0, 1)); glm::mat4x4 B4x4 = glm::inverse(A4x4); glm::mat4x4 I4x4 = A4x4 * B4x4; Failed += I4x4 == glm::mat4x4(1) ? 0 : 1; glm::mat3x3 A3x3( glm::vec3(1, 0, 1), glm::vec3(0, 1, 0), glm::vec3(0, 0, 1)); glm::mat3x3 B3x3 = glm::inverse(A3x3); glm::mat3x3 I3x3 = A3x3 * B3x3; Failed += I3x3 == glm::mat3x3(1) ? 0 : 1; glm::mat2x2 A2x2( glm::vec2(1, 1), glm::vec2(0, 1)); glm::mat2x2 B2x2 = glm::inverse(A2x2); glm::mat2x2 I2x2 = A2x2 * B2x2; Failed += I2x2 == glm::mat2x2(1) ? 0 : 1; return Failed; } int main() { int Failed = 0; Failed += test_matrixCompMult(); Failed += test_outerProduct(); Failed += test_transpose(); Failed += test_determinant(); Failed += test_inverse(); return Failed; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: PreviewRenderer.cxx,v $ * * $Revision: 1.7 $ * * last change: $Author: kz $ $Date: 2006-04-26 20:53:47 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #include "PreviewRenderer.hxx" #include "DrawDocShell.hxx" #include "drawdoc.hxx" #include "drawview.hxx" #include "sdpage.hxx" #include "ViewShell.hxx" #include <vcl/virdev.hxx> #include <svx/svdpagv.hxx> #include <svx/svdoutl.hxx> #include <svx/eeitem.hxx> #include <svx/editstat.hxx> #include <tools/link.hxx> namespace sd { const int PreviewRenderer::snSubstitutionTextSize = 11; const int PreviewRenderer::snFrameWidth = 1; PreviewRenderer::PreviewRenderer (OutputDevice* pTemplate) : mpPreviewDevice (new VirtualDevice()), mpView(NULL), mpDocShellOfView(NULL), mnWidthOfView(0), maFrameColor (svtools::ColorConfig().GetColorValue( svtools::DOCBOUNDARIES).nColor) { // Create a virtual device when not already present and // initialize it. mpPreviewDevice->SetDrawMode (DRAWMODE_DEFAULT); if (pTemplate != NULL) { mpPreviewDevice->SetDigitLanguage (pTemplate->GetDigitLanguage()); mpPreviewDevice->SetBackground(pTemplate->GetBackground()); } else mpPreviewDevice->SetBackground(Wallpaper(COL_WHITE)); } PreviewRenderer::~PreviewRenderer (void) { if (mpDocShellOfView != NULL) EndListening (*mpDocShellOfView); } Image PreviewRenderer::RenderPage ( const SdPage* pPage, int nWidth, const String& rSubstitutionText) { if (pPage != NULL) { Size aPageModelSize (pPage->GetSize()); double nAspectRatio ( double(aPageModelSize.Width()) / double(aPageModelSize.Height())); int nHeight = (int)((nWidth - 2*snFrameWidth) / nAspectRatio + 2*snFrameWidth + 0.5); return RenderPage (pPage, Size(nWidth,nHeight), rSubstitutionText); } else return Image(); } Image PreviewRenderer::RenderPage ( const SdPage* pPage, Size aPixelSize, const String& rSubstitutionText) { Image aPreview; if (pPage != NULL) { try { if (Initialize (pPage, aPixelSize)) { PaintPage (pPage); PaintSubstitutionText (rSubstitutionText); PaintFrame(); Size aSize (mpPreviewDevice->GetOutputSizePixel()); aPreview = mpPreviewDevice->GetBitmap ( mpPreviewDevice->PixelToLogic(Point(0,0)), mpPreviewDevice->PixelToLogic(aSize)); Cleanup(); } } catch (const com::sun::star::uno::Exception&) { OSL_TRACE("PreviewRenderer::RenderPage: caught exception"); } } return aPreview; } Image PreviewRenderer::RenderSubstitution ( const Size& rPreviewPixelSize, const String& rSubstitutionText) { Image aPreview; try { // Set size. mpPreviewDevice->SetOutputSizePixel(rPreviewPixelSize); // Adjust contrast mode. bool bUseContrast = Application::GetSettings().GetStyleSettings(). GetHighContrastMode(); mpPreviewDevice->SetDrawMode (bUseContrast ? ViewShell::OUTPUT_DRAWMODE_CONTRAST : ViewShell::OUTPUT_DRAWMODE_COLOR); // Set a map mode makes a typical substitution text completely // visible. MapMode aMapMode (mpPreviewDevice->GetMapMode()); aMapMode.SetMapUnit(MAP_100TH_MM); double nFinalScale (25.0 * rPreviewPixelSize.Width() / 28000.0); aMapMode.SetScaleX(nFinalScale); aMapMode.SetScaleY(nFinalScale); aMapMode.SetOrigin(mpPreviewDevice->PixelToLogic( Point(snFrameWidth,snFrameWidth),aMapMode)); mpPreviewDevice->SetMapMode (aMapMode); // Clear the background. Rectangle aPaintRectangle ( Point(0,0), mpPreviewDevice->GetOutputSizePixel()); mpPreviewDevice->EnableMapMode(FALSE); mpPreviewDevice->SetLineColor(); svtools::ColorConfig aColorConfig; mpPreviewDevice->SetFillColor(aColorConfig.GetColorValue(svtools::DOCCOLOR).nColor); mpPreviewDevice->DrawRect (aPaintRectangle); mpPreviewDevice->EnableMapMode(TRUE); // Paint substitution text and a frame around it. PaintSubstitutionText (rSubstitutionText); PaintFrame(); Size aSize (mpPreviewDevice->GetOutputSizePixel()); aPreview = mpPreviewDevice->GetBitmap ( mpPreviewDevice->PixelToLogic(Point(0,0)), mpPreviewDevice->PixelToLogic(aSize)); } catch (const com::sun::star::uno::Exception&) { OSL_TRACE("PreviewRenderer::RenderPage: caught exception"); } return aPreview; } bool PreviewRenderer::Initialize ( const SdPage* pPage, const Size& rPixelSize) { bool bSuccess = false; do { if (pPage == NULL) break; SdrModel* pModel = pPage->GetModel(); if (pModel == NULL) break; SetupOutputSize (pPage, rPixelSize); SdDrawDocument* pDocument = static_cast<SdDrawDocument*>(pPage->GetModel()); DrawDocShell* pDocShell = pDocument->GetDocSh(); // Create view ProvideView (pDocShell); if (mpView.get() == NULL) break; // Adjust contrast mode. bool bUseContrast = Application::GetSettings().GetStyleSettings(). GetHighContrastMode(); mpPreviewDevice->SetDrawMode (bUseContrast ? ViewShell::OUTPUT_DRAWMODE_CONTRAST : ViewShell::OUTPUT_DRAWMODE_COLOR); // Tell the view to show the given page. SdPage* pNonConstPage = const_cast<SdPage*>(pPage); if (pPage->IsMasterPage()) mpView->ShowMasterPagePgNum(pPage->GetPageNum(), Point(0, 0)); else mpView->ShowPage (pNonConstPage, Point(0,0)); // Make sure that a page view exists. SdrPageView* pPageView = mpView->GetPageView (pPage); if (pPageView == NULL) break; // Set background color of page view and outliner. svtools::ColorConfig aColorConfig; pPageView->SetApplicationBackgroundColor( pPage->GetBackgroundColor(pPageView)); SdrOutliner& rOutliner (pDocument->GetDrawOutliner(NULL)); rOutliner.SetBackgroundColor(pPage->GetBackgroundColor(pPageView)); rOutliner.SetDefaultLanguage(pDocument->GetLanguage(EE_CHAR_LANGUAGE)); mpView->SetApplicationBackgroundColor( Color(aColorConfig.GetColorValue(svtools::APPBACKGROUND).nColor)); bSuccess = true; } while (false); return bSuccess; } void PreviewRenderer::Cleanup (void) { mpView->HideAllPages(); } void PreviewRenderer::PaintPage (const SdPage* pPage) { // Paint the page. Rectangle aPaintRectangle (Point(0,0), pPage->GetSize()); Region aRegion (aPaintRectangle); // Turn off online spelling and redlining. SdrOutliner* pOutliner = NULL; ULONG nOriginalControlWord = 0; if (mpDocShellOfView!=NULL && mpDocShellOfView->GetDoc()!=NULL) { pOutliner = &mpDocShellOfView->GetDoc()->GetDrawOutliner(); nOriginalControlWord = pOutliner->GetControlWord(); pOutliner->SetControlWord( (nOriginalControlWord & ~EE_CNTRL_ONLINESPELLING) | EE_CNTRL_NOREDLINES); } try { mpView->CompleteRedraw (mpPreviewDevice.get(), aRegion); } catch (const ::com::sun::star::uno::Exception&) { OSL_TRACE("PreviewRenderer::PaintPage: caught exception"); } // Restore the previous online spelling and redlining states. if (pOutliner != NULL) pOutliner->SetControlWord(nOriginalControlWord); } void PreviewRenderer::PaintSubstitutionText (const String& rSubstitutionText) { if (rSubstitutionText.Len() > 0) { // Set the font size. const Font& rOriginalFont (mpPreviewDevice->GetFont()); Font aFont (mpPreviewDevice->GetSettings().GetStyleSettings().GetAppFont()); sal_Int32 nHeight (mpPreviewDevice->PixelToLogic(Size(0,snSubstitutionTextSize)).Height()); aFont.SetHeight(nHeight); mpPreviewDevice->SetFont (aFont); // Paint the substitution text. Rectangle aTextBox ( Point(0,0), mpPreviewDevice->PixelToLogic( mpPreviewDevice->GetOutputSizePixel())); USHORT nTextStyle = TEXT_DRAW_CENTER | TEXT_DRAW_VCENTER | TEXT_DRAW_MULTILINE | TEXT_DRAW_WORDBREAK; mpPreviewDevice->DrawText (aTextBox, rSubstitutionText, nTextStyle); // Restore the font. mpPreviewDevice->SetFont (rOriginalFont); } } void PreviewRenderer::PaintFrame (void) { // Paint a frame arround the preview. Rectangle aPaintRectangle ( Point(0,0), mpPreviewDevice->GetOutputSizePixel()); mpPreviewDevice->EnableMapMode (FALSE); mpPreviewDevice->SetLineColor (maFrameColor); mpPreviewDevice->SetFillColor (); mpPreviewDevice->DrawRect (aPaintRectangle); mpPreviewDevice->EnableMapMode (TRUE); } void PreviewRenderer::SetupOutputSize ( const SdPage* pPage, const Size& rFramePixelSize) { // First set the map mode to some arbitrary scale that is numerically // stable. MapMode aMapMode (mpPreviewDevice->GetMapMode()); aMapMode.SetMapUnit(MAP_100TH_MM); double nInitialScale = 1; aMapMode.SetScaleX (Fraction(nInitialScale)); aMapMode.SetScaleY (Fraction(nInitialScale)); aMapMode.SetOrigin (Point(0,0)); // Adapt it to the desired width. Size aPageModelSize (pPage->GetSize()); /* double nAspectRatio ( double(aPageModelSize.Width()) / double(aPageModelSize.Height())); Size aFramePixelSize (nWidth, (int)((nWidth-2) / nAspectRatio + 2 + 0.5)); */ Size aOutputSize = mpPreviewDevice->LogicToPixel( pPage->GetSize(), aMapMode); double nFinalScale (nInitialScale * (rFramePixelSize.Width()-snFrameWidth) / aOutputSize.Width()); aMapMode.SetScaleX (nFinalScale); aMapMode.SetScaleY (nFinalScale); aMapMode.SetOrigin (mpPreviewDevice->PixelToLogic( Point(snFrameWidth,snFrameWidth),aMapMode)); mpPreviewDevice->SetMapMode (aMapMode); mpPreviewDevice->SetOutputSizePixel(rFramePixelSize); } void PreviewRenderer::ProvideView (DrawDocShell* pDocShell) { if (pDocShell != mpDocShellOfView) { // Destroy the view that is connected to the current doc shell. mpView.reset (NULL); // Switch our attention, i.e. listening for DYING events, to // the new doc shell. if (mpDocShellOfView != NULL) EndListening (*mpDocShellOfView); mpDocShellOfView = pDocShell; if (mpDocShellOfView != NULL) StartListening (*mpDocShellOfView); } if (mpView.get() == NULL) { mpView.reset (new DrawView (pDocShell, mpPreviewDevice.get(), NULL)); } mpView->SetBordVisible(FALSE); mpView->SetPageBorderVisible(FALSE); mpView->SetPageVisible(TRUE); } Image PreviewRenderer::ScaleBitmap ( const BitmapEx& rBitmapEx, int nWidth) { Image aPreview; do { // Adjust contrast mode. bool bUseContrast = Application::GetSettings().GetStyleSettings(). GetHighContrastMode(); mpPreviewDevice->SetDrawMode (bUseContrast ? ViewShell::OUTPUT_DRAWMODE_CONTRAST : ViewShell::OUTPUT_DRAWMODE_COLOR); // Set output size. Size aSize (rBitmapEx.GetSizePixel()); if (aSize.Width() <= 0) break; Size aFrameSize ( nWidth, (long)((nWidth*1.0 * aSize.Height()) / aSize.Width() + 0.5)); Size aPreviewSize (aFrameSize.Width()-2,aFrameSize.Height()-2); MapMode aMapMode (mpPreviewDevice->GetMapMode()); aMapMode.SetMapUnit(MAP_PIXEL); aMapMode.SetOrigin (Point()); aMapMode.SetScaleX (1.0); aMapMode.SetScaleY (1.0); mpPreviewDevice->SetMapMode (aMapMode); mpPreviewDevice->SetOutputSize (aFrameSize); // Paint a frame arround the preview. mpPreviewDevice->SetLineColor (maFrameColor); mpPreviewDevice->SetFillColor (); mpPreviewDevice->DrawRect (Rectangle(Point(0,0), aFrameSize)); // Paint the bitmap scaled to the desired width. BitmapEx aScaledBitmap (rBitmapEx.GetBitmap()); aScaledBitmap.Scale (aPreviewSize, BMP_SCALE_INTERPOLATE); mpPreviewDevice->DrawBitmap ( Point(1,1), aPreviewSize, aScaledBitmap.GetBitmap()); // Get the resulting bitmap. aPreview = mpPreviewDevice->GetBitmap (Point(0,0), aFrameSize); } while (false); return aPreview; } void PreviewRenderer::SFX_NOTIFY(SfxBroadcaster& rBC, const TypeId& rBCType, const SfxHint& rHint, const TypeId& rHintType) { if (rHint.IsA(TYPE(SfxSimpleHint)) && mpDocShellOfView != NULL) { const SfxSimpleHint* pSimpleHint = PTR_CAST(SfxSimpleHint, &rHint); if (pSimpleHint != NULL && pSimpleHint->GetId() == SFX_HINT_DYING) { // The doc shell is dying. Our view uses its item pool and // has to be destroyed as well. The next call to // ProvideView will create a new one (for another // doc shell, of course.) mpView.reset (NULL); mpDocShellOfView = NULL; } } } } // end of namespace ::sd <commit_msg>INTEGRATION: CWS impress92 (1.6.186); FILE MERGED 2006/04/26 13:17:35 af 1.6.186.1: #i63668# Using the correct style settings.<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: PreviewRenderer.cxx,v $ * * $Revision: 1.8 $ * * last change: $Author: rt $ $Date: 2006-05-05 10:07:17 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #include "PreviewRenderer.hxx" #include "DrawDocShell.hxx" #include "drawdoc.hxx" #include "drawview.hxx" #include "sdpage.hxx" #include "ViewShell.hxx" #include <vcl/virdev.hxx> #include <svx/svdpagv.hxx> #include <svx/svdoutl.hxx> #include <svx/eeitem.hxx> #include <svx/editstat.hxx> #include <tools/link.hxx> namespace sd { const int PreviewRenderer::snSubstitutionTextSize = 11; const int PreviewRenderer::snFrameWidth = 1; PreviewRenderer::PreviewRenderer (OutputDevice* pTemplate) : mpPreviewDevice (new VirtualDevice()), mpView(NULL), mpDocShellOfView(NULL), mnWidthOfView(0), maFrameColor (svtools::ColorConfig().GetColorValue( svtools::DOCBOUNDARIES).nColor) { if (pTemplate != NULL) { mpPreviewDevice->SetDigitLanguage (pTemplate->GetDigitLanguage()); mpPreviewDevice->SetBackground(pTemplate->GetBackground()); } else mpPreviewDevice->SetBackground(Wallpaper(COL_WHITE)); } PreviewRenderer::~PreviewRenderer (void) { if (mpDocShellOfView != NULL) EndListening (*mpDocShellOfView); } Image PreviewRenderer::RenderPage ( const SdPage* pPage, int nWidth, const String& rSubstitutionText) { if (pPage != NULL) { Size aPageModelSize (pPage->GetSize()); double nAspectRatio ( double(aPageModelSize.Width()) / double(aPageModelSize.Height())); int nHeight = (int)((nWidth - 2*snFrameWidth) / nAspectRatio + 2*snFrameWidth + 0.5); return RenderPage (pPage, Size(nWidth,nHeight), rSubstitutionText); } else return Image(); } Image PreviewRenderer::RenderPage ( const SdPage* pPage, Size aPixelSize, const String& rSubstitutionText) { Image aPreview; if (pPage != NULL) { try { if (Initialize (pPage, aPixelSize)) { PaintPage (pPage); PaintSubstitutionText (rSubstitutionText); PaintFrame(); Size aSize (mpPreviewDevice->GetOutputSizePixel()); aPreview = mpPreviewDevice->GetBitmap ( mpPreviewDevice->PixelToLogic(Point(0,0)), mpPreviewDevice->PixelToLogic(aSize)); Cleanup(); } } catch (const com::sun::star::uno::Exception&) { OSL_TRACE("PreviewRenderer::RenderPage: caught exception"); } } return aPreview; } Image PreviewRenderer::RenderSubstitution ( const Size& rPreviewPixelSize, const String& rSubstitutionText) { Image aPreview; try { // Set size. mpPreviewDevice->SetOutputSizePixel(rPreviewPixelSize); // Adjust contrast mode. bool bUseContrast = Application::GetSettings().GetStyleSettings(). GetHighContrastMode(); mpPreviewDevice->SetDrawMode (bUseContrast ? ViewShell::OUTPUT_DRAWMODE_CONTRAST : ViewShell::OUTPUT_DRAWMODE_COLOR); // Set a map mode makes a typical substitution text completely // visible. MapMode aMapMode (mpPreviewDevice->GetMapMode()); aMapMode.SetMapUnit(MAP_100TH_MM); double nFinalScale (25.0 * rPreviewPixelSize.Width() / 28000.0); aMapMode.SetScaleX(nFinalScale); aMapMode.SetScaleY(nFinalScale); aMapMode.SetOrigin(mpPreviewDevice->PixelToLogic( Point(snFrameWidth,snFrameWidth),aMapMode)); mpPreviewDevice->SetMapMode (aMapMode); // Clear the background. Rectangle aPaintRectangle ( Point(0,0), mpPreviewDevice->GetOutputSizePixel()); mpPreviewDevice->EnableMapMode(FALSE); mpPreviewDevice->SetLineColor(); svtools::ColorConfig aColorConfig; mpPreviewDevice->SetFillColor(aColorConfig.GetColorValue(svtools::DOCCOLOR).nColor); mpPreviewDevice->DrawRect (aPaintRectangle); mpPreviewDevice->EnableMapMode(TRUE); // Paint substitution text and a frame around it. PaintSubstitutionText (rSubstitutionText); PaintFrame(); Size aSize (mpPreviewDevice->GetOutputSizePixel()); aPreview = mpPreviewDevice->GetBitmap ( mpPreviewDevice->PixelToLogic(Point(0,0)), mpPreviewDevice->PixelToLogic(aSize)); } catch (const com::sun::star::uno::Exception&) { OSL_TRACE("PreviewRenderer::RenderPage: caught exception"); } return aPreview; } bool PreviewRenderer::Initialize ( const SdPage* pPage, const Size& rPixelSize) { bool bSuccess = false; do { if (pPage == NULL) break; SdrModel* pModel = pPage->GetModel(); if (pModel == NULL) break; SetupOutputSize (pPage, rPixelSize); SdDrawDocument* pDocument = static_cast<SdDrawDocument*>(pPage->GetModel()); DrawDocShell* pDocShell = pDocument->GetDocSh(); // Create view ProvideView (pDocShell); if (mpView.get() == NULL) break; // Adjust contrast mode. bool bUseContrast = Application::GetSettings().GetStyleSettings(). GetHighContrastMode(); mpPreviewDevice->SetDrawMode (bUseContrast ? ViewShell::OUTPUT_DRAWMODE_CONTRAST : ViewShell::OUTPUT_DRAWMODE_COLOR); mpPreviewDevice->SetSettings(Application::GetSettings()); // Tell the view to show the given page. SdPage* pNonConstPage = const_cast<SdPage*>(pPage); if (pPage->IsMasterPage()) mpView->ShowMasterPagePgNum(pPage->GetPageNum(), Point(0, 0)); else mpView->ShowPage (pNonConstPage, Point(0,0)); // Make sure that a page view exists. SdrPageView* pPageView = mpView->GetPageView (pPage); if (pPageView == NULL) break; // Set background color of page view and outliner. svtools::ColorConfig aColorConfig; pPageView->SetApplicationBackgroundColor( pPage->GetBackgroundColor(pPageView)); SdrOutliner& rOutliner (pDocument->GetDrawOutliner(NULL)); rOutliner.SetBackgroundColor(pPage->GetBackgroundColor(pPageView)); rOutliner.SetDefaultLanguage(pDocument->GetLanguage(EE_CHAR_LANGUAGE)); mpView->SetApplicationBackgroundColor( Color(aColorConfig.GetColorValue(svtools::APPBACKGROUND).nColor)); bSuccess = true; } while (false); return bSuccess; } void PreviewRenderer::Cleanup (void) { mpView->HideAllPages(); } void PreviewRenderer::PaintPage (const SdPage* pPage) { // Paint the page. Rectangle aPaintRectangle (Point(0,0), pPage->GetSize()); Region aRegion (aPaintRectangle); // Turn off online spelling and redlining. SdrOutliner* pOutliner = NULL; ULONG nOriginalControlWord = 0; if (mpDocShellOfView!=NULL && mpDocShellOfView->GetDoc()!=NULL) { pOutliner = &mpDocShellOfView->GetDoc()->GetDrawOutliner(); nOriginalControlWord = pOutliner->GetControlWord(); pOutliner->SetControlWord( (nOriginalControlWord & ~EE_CNTRL_ONLINESPELLING) | EE_CNTRL_NOREDLINES); } try { mpView->CompleteRedraw (mpPreviewDevice.get(), aRegion); } catch (const ::com::sun::star::uno::Exception&) { OSL_TRACE("PreviewRenderer::PaintPage: caught exception"); } // Restore the previous online spelling and redlining states. if (pOutliner != NULL) pOutliner->SetControlWord(nOriginalControlWord); } void PreviewRenderer::PaintSubstitutionText (const String& rSubstitutionText) { if (rSubstitutionText.Len() > 0) { // Set the font size. const Font& rOriginalFont (mpPreviewDevice->GetFont()); Font aFont (mpPreviewDevice->GetSettings().GetStyleSettings().GetAppFont()); sal_Int32 nHeight (mpPreviewDevice->PixelToLogic(Size(0,snSubstitutionTextSize)).Height()); aFont.SetHeight(nHeight); mpPreviewDevice->SetFont (aFont); // Paint the substitution text. Rectangle aTextBox ( Point(0,0), mpPreviewDevice->PixelToLogic( mpPreviewDevice->GetOutputSizePixel())); USHORT nTextStyle = TEXT_DRAW_CENTER | TEXT_DRAW_VCENTER | TEXT_DRAW_MULTILINE | TEXT_DRAW_WORDBREAK; mpPreviewDevice->DrawText (aTextBox, rSubstitutionText, nTextStyle); // Restore the font. mpPreviewDevice->SetFont (rOriginalFont); } } void PreviewRenderer::PaintFrame (void) { // Paint a frame arround the preview. Rectangle aPaintRectangle ( Point(0,0), mpPreviewDevice->GetOutputSizePixel()); mpPreviewDevice->EnableMapMode (FALSE); mpPreviewDevice->SetLineColor (maFrameColor); mpPreviewDevice->SetFillColor (); mpPreviewDevice->DrawRect (aPaintRectangle); mpPreviewDevice->EnableMapMode (TRUE); } void PreviewRenderer::SetupOutputSize ( const SdPage* pPage, const Size& rFramePixelSize) { // First set the map mode to some arbitrary scale that is numerically // stable. MapMode aMapMode (mpPreviewDevice->GetMapMode()); aMapMode.SetMapUnit(MAP_100TH_MM); double nInitialScale = 1; aMapMode.SetScaleX (Fraction(nInitialScale)); aMapMode.SetScaleY (Fraction(nInitialScale)); aMapMode.SetOrigin (Point(0,0)); // Adapt it to the desired width. Size aPageModelSize (pPage->GetSize()); /* double nAspectRatio ( double(aPageModelSize.Width()) / double(aPageModelSize.Height())); Size aFramePixelSize (nWidth, (int)((nWidth-2) / nAspectRatio + 2 + 0.5)); */ Size aOutputSize = mpPreviewDevice->LogicToPixel( pPage->GetSize(), aMapMode); double nFinalScale (nInitialScale * (rFramePixelSize.Width()-snFrameWidth) / aOutputSize.Width()); aMapMode.SetScaleX (nFinalScale); aMapMode.SetScaleY (nFinalScale); aMapMode.SetOrigin (mpPreviewDevice->PixelToLogic( Point(snFrameWidth,snFrameWidth),aMapMode)); mpPreviewDevice->SetMapMode (aMapMode); mpPreviewDevice->SetOutputSizePixel(rFramePixelSize); } void PreviewRenderer::ProvideView (DrawDocShell* pDocShell) { if (pDocShell != mpDocShellOfView) { // Destroy the view that is connected to the current doc shell. mpView.reset (NULL); // Switch our attention, i.e. listening for DYING events, to // the new doc shell. if (mpDocShellOfView != NULL) EndListening (*mpDocShellOfView); mpDocShellOfView = pDocShell; if (mpDocShellOfView != NULL) StartListening (*mpDocShellOfView); } if (mpView.get() == NULL) { mpView.reset (new DrawView (pDocShell, mpPreviewDevice.get(), NULL)); } mpView->SetBordVisible(FALSE); mpView->SetPageBorderVisible(FALSE); mpView->SetPageVisible(TRUE); } Image PreviewRenderer::ScaleBitmap ( const BitmapEx& rBitmapEx, int nWidth) { Image aPreview; do { // Adjust contrast mode. bool bUseContrast = Application::GetSettings().GetStyleSettings(). GetHighContrastMode(); mpPreviewDevice->SetDrawMode (bUseContrast ? ViewShell::OUTPUT_DRAWMODE_CONTRAST : ViewShell::OUTPUT_DRAWMODE_COLOR); // Set output size. Size aSize (rBitmapEx.GetSizePixel()); if (aSize.Width() <= 0) break; Size aFrameSize ( nWidth, (long)((nWidth*1.0 * aSize.Height()) / aSize.Width() + 0.5)); Size aPreviewSize (aFrameSize.Width()-2,aFrameSize.Height()-2); MapMode aMapMode (mpPreviewDevice->GetMapMode()); aMapMode.SetMapUnit(MAP_PIXEL); aMapMode.SetOrigin (Point()); aMapMode.SetScaleX (1.0); aMapMode.SetScaleY (1.0); mpPreviewDevice->SetMapMode (aMapMode); mpPreviewDevice->SetOutputSize (aFrameSize); // Paint a frame arround the preview. mpPreviewDevice->SetLineColor (maFrameColor); mpPreviewDevice->SetFillColor (); mpPreviewDevice->DrawRect (Rectangle(Point(0,0), aFrameSize)); // Paint the bitmap scaled to the desired width. BitmapEx aScaledBitmap (rBitmapEx.GetBitmap()); aScaledBitmap.Scale (aPreviewSize, BMP_SCALE_INTERPOLATE); mpPreviewDevice->DrawBitmap ( Point(1,1), aPreviewSize, aScaledBitmap.GetBitmap()); // Get the resulting bitmap. aPreview = mpPreviewDevice->GetBitmap (Point(0,0), aFrameSize); } while (false); return aPreview; } void PreviewRenderer::SFX_NOTIFY(SfxBroadcaster& rBC, const TypeId& rBCType, const SfxHint& rHint, const TypeId& rHintType) { if (rHint.IsA(TYPE(SfxSimpleHint)) && mpDocShellOfView != NULL) { const SfxSimpleHint* pSimpleHint = PTR_CAST(SfxSimpleHint, &rHint); if (pSimpleHint != NULL && pSimpleHint->GetId() == SFX_HINT_DYING) { // The doc shell is dying. Our view uses its item pool and // has to be destroyed as well. The next call to // ProvideView will create a new one (for another // doc shell, of course.) mpView.reset (NULL); mpDocShellOfView = NULL; } } } } // end of namespace ::sd <|endoftext|>
<commit_before>/*! \file urbi/usyncclient.hh **************************************************************************** * * Definition of the URBI interface class * * Copyright (C) 2004, 2006, 2007, 2008, 2009 Jean-Christophe Baillie. * All rights reserved. * * 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. **********************************************************************/ #ifndef URBI_USYNCCLIENT_HH # define URBI_USYNCCLIENT_HH # include <libport/fwd.hh> # include <libport/lockable.hh> # include <libport/semaphore.hh> # include <libport/utime.hh> # include <libport/pthread.h> # include <urbi/uclient.hh> namespace urbi { /*! Format in which image requested with syncGetSound are transmitted*/ enum UTransmitFormat { /// Transmit images compressed in JPEG. URBI_TRANSMIT_JPEG, /// Transmit raw YCbCr images. URBI_TRANSMIT_YCbCr }; /// UClient linux implementation with support for synchronous extra /// functions. /*! This class provides extra functions to synchronously request values. These functions can safely be called frow within a callback function. All callback will be called in a separate thread created in the constructor. If you want to call these callbacks in a different thread, call @stopCallbackThread, then regularly call @processEvents. Each call will call callbacks for all pending messages in the current thread. */ class URBI_SDK_API USyncClient: public UClient { public: /** Create a new connection to an Urbi Server. * * \param host The host to connect to. * \param port the port number to connect to, defaults to URBI_PORT. * \param buflen Size of reception buffer, defaults to URBI_BUFLEN. * \param server If true, listen for an incoming connection from an * urbi server instead of connecting. * \param startCallbackThread Create a thread didacated to the processing * of incoming messages. If false, it is the responsibility of the user * to regularly call processEvents(). */ USyncClient(const std::string& host, unsigned port = URBI_PORT, size_t buflen = URBI_BUFLEN, bool server = false, bool startCallbackThread = true, unsigned semListenInc = 2u); ~USyncClient(); protected: /** Synchronously ask the server for the value of an expression. * \param expression the Urbi expression to evaluate. * It must be a single expression and must not start with a tag. * \param mtag tag to use, or 0 to generate one. * \param mmod modifier to use on the tag, or 0 for none. * \return the resulting message, or 0 in case of error. */ UMessage* syncGet_(const char* expression, const char* mtag, const char* mmod, va_list& arg); public: /// Synchronously evaluate an Urbi expression. The expression must /// not start with a tag or channel. UMessage *syncGet(const char* expression, ...); /// Synchronously evaluate an Urbi expression, specifying the tag /// and modifiers to prepend to it. UMessage *syncGetTag(const char* expression, const char* mtag, const char* mmod, ...); /// Send given buffer without copying it. int syncSend(const void * buffer, size_t length); /// Get an image in a synchronous way. Returns 1 on success, 0 on failure. int syncGetImage(const char* cameraDevice, void* buffer, size_t& buffersize, int format, int transmitFormat, size_t& width, size_t& height); /// Get the value of any device in a synchronous way. Returns 1 on /// success, 0 on failure. int syncGetValue(const char* valName, UValue& val); int syncGetValue(const char* tag, const char* valName, UValue& val); /// Get the value of device.val in a synchronous way. Returns 1 on /// success, 0 on failure. int syncGetDevice(const char* device, double &val); /// Execute an URBI command, return the resulting double /// value. Returns 1 on success, 0 on failure. int syncGetResult(const char* command, double &val); /// Get the normalized value of a device in a synchronous /// way. Returns 1 on success, 0 on failure. int syncGetNormalizedDevice(const char* device, double &val); /// Get a field of a device in a synchronous way. Returns 1 on /// success, 0 on failure. int syncGetDevice(const char* device, const char* field, double &val); /// Get sound for duration milliseconds in buffer. int syncGetSound(const char* device, int duration, USound &sound); /// Wait until a message with specified tag is received. Returned /// message must be deleted. UMessage* waitForTag(const std::string& tag); /// Overriding UAbstractclient implementation virtual void notifyCallbacks(const UMessage &msg); /** * Check message queue for pending messages, notify callbacks synchronously. * @param timeout If different -1 process events for at most @a timeout * microseconds. This is useful if you don't want * processEvents() to take to much time if there are many * many pending messages. * @return true if at least one message was processed, false otherwise. * Callbacks functions are called synchronously in the caller thread. */ bool processEvents(const libport::utime_t timeout = -1); /** * Stop the callback processing thread. * The user is responsible for calling processEvents() regularily * once this function has been called. */ void stopCallbackThread(); void callbackThread(); /** * Block until kernel version is available, or an error occurrs. * @param hasProcessingThread true if a processing thread is running, false * if processEvents must be called while waiting. */ void waitForKernelVersion(bool hasProcessingThread); protected: int joinCallbackThread_(); // Incremented at each queue push, decremented on pop. libport::Semaphore sem_; // Semaphore to delay execution of callback thread until ctor finishes. libport::Semaphore callbackSem_; std::list<UMessage*> queue; libport::Lockable queueLock_; UMessage* msg; libport::Semaphore syncLock_; std::string syncTag; bool stopCallbackThread_; pthread_t cbThread; // Used to block until the callback thread is realy stopped. libport::Semaphore stopCallbackSem_; }; } // namespace urbi #endif // ! URBI_USYNCCLIENT_HH <commit_msg>Comment changes.<commit_after>/*! \file urbi/usyncclient.hh **************************************************************************** * * Definition of the URBI interface class * * Copyright (C) 2004, 2006, 2007, 2008, 2009 Jean-Christophe Baillie. * All rights reserved. * * 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. **********************************************************************/ #ifndef URBI_USYNCCLIENT_HH # define URBI_USYNCCLIENT_HH # include <libport/fwd.hh> # include <libport/lockable.hh> # include <libport/semaphore.hh> # include <libport/utime.hh> # include <libport/pthread.h> # include <urbi/uclient.hh> namespace urbi { /*! Format in which image requested with syncGetSound are transmitted*/ enum UTransmitFormat { /// Transmit images compressed in JPEG. URBI_TRANSMIT_JPEG, /// Transmit raw YCbCr images. URBI_TRANSMIT_YCbCr }; /// UClient linux implementation with support for synchronous extra /// functions. /*! This class provides extra functions to synchronously request values. These functions can safely be called frow within a callback function. All callback will be called in a separate thread created in the constructor. If you want to call these callbacks in a different thread, call @stopCallbackThread, then regularly call @processEvents. Each call will call callbacks for all pending messages in the current thread. */ class URBI_SDK_API USyncClient: public UClient { public: /** Create a new connection to an Urbi Server. * * \param host The host to connect to. * \param port the port number to connect to, defaults to URBI_PORT. * \param buflen Size of reception buffer, defaults to URBI_BUFLEN. * \param server If true, listen for an incoming connection from an * urbi server instead of connecting. * \param startCallbackThread Create a thread didacated to the processing * of incoming messages. If false, it is the responsibility of the user * to regularly call processEvents(). */ USyncClient(const std::string& host, unsigned port = URBI_PORT, size_t buflen = URBI_BUFLEN, bool server = false, bool startCallbackThread = true, unsigned semListenInc = 2u); ~USyncClient(); protected: /** Synchronously ask the server for the value of an expression. * \param expression the Urbi expression to evaluate. * It must be a single expression and must not start with a tag. * \param mtag tag to use, or 0 to generate one. * \param mmod modifier to use on the tag, or 0 for none. * \return the resulting message, or 0 in case of error. */ UMessage* syncGet_(const char* expression, const char* mtag, const char* mmod, va_list& arg); public: /// Synchronously evaluate an Urbi expression. The expression must /// not start with a tag or channel. UMessage *syncGet(const char* expression, ...); /// Synchronously evaluate an Urbi expression, specifying the tag /// and modifiers to prepend to it. UMessage *syncGetTag(const char* expression, const char* mtag, const char* mmod, ...); /// Send given buffer without copying it. int syncSend(const void * buffer, size_t length); /// Get an image in a synchronous way. /// \return 1 on success, 0 on failure. int syncGetImage(const char* cameraDevice, void* buffer, size_t& buffersize, int format, int transmitFormat, size_t& width, size_t& height); /// Get the value of any device in a synchronous way. /// \return 1 on success, 0 on failure. int syncGetValue(const char* valName, UValue& val); int syncGetValue(const char* tag, const char* valName, UValue& val); /// Get the value of device.val in a synchronous way. /// \return 1 on success, 0 on failure. int syncGetDevice(const char* device, double &val); /// Execute an URBI command, return the resulting double /// value. /// \return 1 on success, 0 on failure. int syncGetResult(const char* command, double &val); /// Get the normalized value of a device in a synchronous /// way. /// \return 1 on success, 0 on failure. int syncGetNormalizedDevice(const char* device, double &val); /// Get a field of a device in a synchronous way. /// \return 1 on success, 0 on failure. int syncGetDevice(const char* device, const char* field, double &val); /// Get sound for duration milliseconds in buffer. int syncGetSound(const char* device, int duration, USound &sound); /// Wait until a message with specified tag is received. Returned /// message must be deleted. UMessage* waitForTag(const std::string& tag); /// Overriding UAbstractclient implementation virtual void notifyCallbacks(const UMessage &msg); /** * Check message queue for pending messages, notify callbacks synchronously. * @param timeout If different -1 process events for at most @a timeout * microseconds. This is useful if you don't want * processEvents() to take to much time if there are many * many pending messages. * @return true if at least one message was processed, false otherwise. * Callbacks functions are called synchronously in the caller thread. */ bool processEvents(const libport::utime_t timeout = -1); /** * Stop the callback processing thread. * The user is responsible for calling processEvents() regularily * once this function has been called. */ void stopCallbackThread(); void callbackThread(); /** * Block until kernel version is available, or an error occurrs. * @param hasProcessingThread true if a processing thread is running, false * if processEvents must be called while waiting. */ void waitForKernelVersion(bool hasProcessingThread); protected: int joinCallbackThread_(); // Incremented at each queue push, decremented on pop. libport::Semaphore sem_; // Semaphore to delay execution of callback thread until ctor finishes. libport::Semaphore callbackSem_; std::list<UMessage*> queue; libport::Lockable queueLock_; /// When locked waiting for a specific tag, notifyCallbacks will /// store the received message here, and waitForTag will get it /// there. UMessage* msg; libport::Semaphore syncLock_; std::string syncTag; bool stopCallbackThread_; pthread_t cbThread; // Used to block until the callback thread is realy stopped. libport::Semaphore stopCallbackSem_; }; } // namespace urbi #endif // ! URBI_USYNCCLIENT_HH <|endoftext|>
<commit_before>AliJetReader *CreateJetReader(Char_t *jr); // Common config AliJetFinder *CreateJetFinder(Char_t *jf,Float_t radius = -1); AliAnalysisTaskJets *AddTaskJets(Char_t *jr, Char_t *jf,Float_t radius = -1); // for the new AF AliAnalysisTaskJets *AddTaskJets(Char_t *jr, Char_t *jf, Float_t radius) { // Creates a jet finder task, configures it and adds it to the analysis manager. // Get the pointer to the existing analysis manager via the static access method. //============================================================================== AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { ::Error("AddTaskJets", "No analysis manager to connect to."); return NULL; } // Check the analysis type using the event handlers connected to the analysis manager. //============================================================================== if (!mgr->GetInputEventHandler()) { ::Error("AddTaskJets", "This task requires an input event handler"); return NULL; } // Create the task and configure it. //=========================================================================== AliAnalysisTaskJets *jetana; AliJetReader *er = CreateJetReader(jr); // Define jet header and jet finder AliJetFinder *jetFinder = CreateJetFinder(jf,radius); if (jetFinder){ if (er) jetFinder->SetJetReader(er); } char *cRadius = ""; if(radius>0)cRadius = Form("%02d",(int)(radius*10)); jetana = new AliAnalysisTaskJets(Form("JetAnalysis%s%s%s",jr,jf,cRadius)); TString type = mgr->GetInputEventHandler()->GetDataType(); if (type == "AOD") jetana->SetNonStdBranch(Form("jets%s",jf)); AliAnalysisDataContainer *cout_jet = mgr->CreateContainer(Form("jethist%s%s%s",jr,jf,cRadius), TList::Class(), AliAnalysisManager::kOutputContainer, Form("jethist%s_%s%s.root",jr,jf,cRadius)); // Connect jet finder to task. jetana->SetJetFinder(jetFinder); jetana->SetConfigFile(""); jetana->SetDebugLevel(0); mgr->AddTask(jetana); // Create ONLY the output containers for the data produced by the task. // Get and connect other common input/output containers via the manager as below //============================================================================== mgr->ConnectInput (jetana, 0, mgr->GetCommonInputContainer()); // AOD output slot will be used in a different way in future mgr->ConnectOutput (jetana, 0, mgr->GetCommonOutputContainer()); mgr->ConnectOutput (jetana, 1, cout_jet); return jetana; } AliJetFinder *CreateJetFinder(Char_t *jf,Float_t radius){ AliJetFinder *jetFinder = 0; switch (jf) { case "CDF": AliCdfJetHeader *jh = new AliCdfJetHeader(); jh->SetRadius(0.7); jetFinder = new AliCdfJetFinder(); jetFinder->SetOutputFile("jets.root"); if (jh) jetFinder->SetJetHeader(jh); break; case "DA": AliDAJetHeader *jh=new AliDAJetHeader(); jh->SetComment("DA jet code with default parameters"); jh->SelectJets(kTRUE); jh->SetNclust(10); jetFinder = new AliDAJetFinder(); if (jh) jetFinder->SetJetHeader(jh); break; case "FASTJET": AliFastJetHeaderV1 *jh = new AliFastJetHeaderV1(); jh->SetRparam(0.4); // setup parameters if(radius>0)jh->SetRparam(radius); jh->SetAlgorithm(2); // antikt from fastjet/JetDefinition.hh jetFinder = new AliFastJetFinder(); if (jh) jetFinder->SetJetHeader(jh); break; case "UA1": AliUA1JetHeaderV1 *jh=new AliUA1JetHeaderV1(); jh->SetComment("UA1 jet code with default parameters"); jh->BackgMode(0); jh->SetRadius(0.4); if(radius>0)jh->SetRadius(radius); jh->SetEtSeed(4.); jh->SetLegoNbinPhi(432); jh->SetLegoNbinEta(274); jh->SetLegoEtaMin(-2); jh->SetLegoEtaMax(+2); jh->SetMinJetEt(10.); jh->SetJetEtaMax(1.5); jh->SetJetEtaMin(-1.5); jetFinder = new AliUA1JetFinderV1(); if (jh) jetFinder->SetJetHeader(jh); break; case "UA1MC": AliUA1JetHeaderV1 *jh=new AliUA1JetHeaderV1(); jh->SetComment("UA1 jet code with default MC parameters"); jh->BackgMode(0); jh->SetRadius(1.0); if(radius>0)jh->SetRadius(radius); jh->SetEtSeed(4.); jh->SetLegoNbinPhi(432); jh->SetLegoNbinEta(274); jh->SetLegoEtaMin(-2); jh->SetLegoEtaMax(+2); jh->SetMinJetEt(10.); jh->SetJetEtaMax(1.5); jh->SetJetEtaMin(-1.5); jetFinder = new AliUA1JetFinderV1(); if (jh) jetFinder->SetJetHeader(jh); break; default: Printf("\n >>>>>>> AddTaskJets Error Wrong jet finder selected\n"); break; } return jetFinder; } AliJetReader *CreateJetReader(Char_t *jr){ AliJetReader *er = 0; switch (jr) { case "MC": AliJetKineReaderHeader *jrh = new AliJetKineReaderHeader(); jrh->SetComment("MC full Kinematics"); jrh->SetFastSimTPC(kFALSE); jrh->SetFastSimEMCAL(kFALSE); jrh->SetPtCut(0.); jrh->SetFiducialEta(-2.1,2.1); // to take all MC particles default is 0 .9 // Define reader and set its header er = new AliJetKineReader(); er->SetReaderHeader(jrh); break; case "MC2": AliJetKineReaderHeader *jrh = new AliJetKineReaderHeader(); jrh->SetComment("MC full Kinematics spearate config charged only"); jrh->SetFastSimTPC(kFALSE); jrh->SetFastSimEMCAL(kFALSE); jrh->SetChargedOnly(kTRUE); jrh->SetPtCut(0.); jrh->SetFiducialEta(-2.1,2.1); // to take all MC particles default is 0 .9 // Define reader and set its header er = new AliJetKineReader(); er->SetReaderHeader(jrh); break; case "ESD": AliJetESDReaderHeader *jrh = new AliJetESDReaderHeader(); jrh->SetComment("Testing"); jrh->SetFirstEvent(0); jrh->SetLastEvent(1000); jrh->SetPtCut(0.); jrh->SetReadSignalOnly(kFALSE); // Define reader and set its header er = new AliJetESDReader(); er->SetReaderHeader(jrh); break; case "AOD": AliJetAODReaderHeader *jrh = new AliJetAODReaderHeader(); jrh->SetComment("AOD Reader"); jrh->SetPtCut(0.); jrh->SetTestFilterMask(1<<0); // Define reader and set its header er = new AliJetAODReader(); er->SetReaderHeader(jrh); break; case "AODMC": AliJetAODReaderHeader *jrh = new AliJetAODReaderHeader(); jrh->SetComment("AOD MC Reader"); jrh->SetPtCut(0.); jrh->SetFiducialEta(-2.1,2.1); // to take all MC particles default is 0.9 jrh->SetReadAODMC(1);// 1 all primary MC , 2 all primary charged // Define reader and set its header er = new AliJetAODReader(); er->SetReaderHeader(jrh); break; case "AODMC2": AliJetAODReaderHeader *jrh = new AliJetAODReaderHeader(); jrh->SetComment("AOD MC Reader"); jrh->SetPtCut(0.); jrh->SetFiducialEta(-2.1,2.1); // to take all MC particles default is 0.9 jrh->SetReadAODMC(2);// 1 all primary MC , 2 all primary charged // Define reader and set its header er = new AliJetAODReader(); er->SetReaderHeader(jrh); break; default: ::Error("AddTaskJets", "Wrong jet reader selected\n"); return 0; } return er; } <commit_msg>add check on aod otput event handler<commit_after>AliJetReader *CreateJetReader(Char_t *jr); // Common config AliJetFinder *CreateJetFinder(Char_t *jf,Float_t radius = -1); AliAnalysisTaskJets *AddTaskJets(Char_t *jr, Char_t *jf,Float_t radius = -1); // for the new AF AliAnalysisTaskJets *AddTaskJets(Char_t *jr, Char_t *jf, Float_t radius) { // Creates a jet finder task, configures it and adds it to the analysis manager. // Get the pointer to the existing analysis manager via the static access method. //============================================================================== AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { ::Error("AddTaskJets", "No analysis manager to connect to."); return NULL; } // Check the analysis type using the event handlers connected to the analysis manager. //============================================================================== if (!mgr->GetInputEventHandler()) { ::Error("AddTaskJets", "This task requires an input event handler"); return NULL; } AliAODHandler *aodh = (AliAODHandler*)mgr->GetOutputEventHandler(); if (!aodh) { ::Error("AddTaskJets", "This task needs an output event handler"); return NULL; } // Create the task and configure it. //=========================================================================== AliAnalysisTaskJets *jetana; AliJetReader *er = CreateJetReader(jr); // Define jet header and jet finder AliJetFinder *jetFinder = CreateJetFinder(jf,radius); if (jetFinder){ if (er) jetFinder->SetJetReader(er); } char *cRadius = ""; if(radius>0)cRadius = Form("%02d",(int)(radius*10)); jetana = new AliAnalysisTaskJets(Form("JetAnalysis%s%s%s",jr,jf,cRadius)); TString type = mgr->GetInputEventHandler()->GetDataType(); if (type == "AOD") jetana->SetNonStdBranch(Form("jets%s",jf)); AliAnalysisDataContainer *cout_jet = mgr->CreateContainer(Form("jethist%s%s%s",jr,jf,cRadius), TList::Class(), AliAnalysisManager::kOutputContainer, Form("jethist%s_%s%s.root",jr,jf,cRadius)); // Connect jet finder to task. jetana->SetJetFinder(jetFinder); jetana->SetConfigFile(""); jetana->SetDebugLevel(0); mgr->AddTask(jetana); // Create ONLY the output containers for the data produced by the task. // Get and connect other common input/output containers via the manager as below //============================================================================== mgr->ConnectInput (jetana, 0, mgr->GetCommonInputContainer()); // AOD output slot will be used in a different way in future mgr->ConnectOutput (jetana, 0, mgr->GetCommonOutputContainer()); mgr->ConnectOutput (jetana, 1, cout_jet); return jetana; } AliJetFinder *CreateJetFinder(Char_t *jf,Float_t radius){ AliJetFinder *jetFinder = 0; switch (jf) { case "CDF": AliCdfJetHeader *jh = new AliCdfJetHeader(); jh->SetRadius(0.7); jetFinder = new AliCdfJetFinder(); jetFinder->SetOutputFile("jets.root"); if (jh) jetFinder->SetJetHeader(jh); break; case "DA": AliDAJetHeader *jh=new AliDAJetHeader(); jh->SetComment("DA jet code with default parameters"); jh->SelectJets(kTRUE); jh->SetNclust(10); jetFinder = new AliDAJetFinder(); if (jh) jetFinder->SetJetHeader(jh); break; case "FASTJET": AliFastJetHeaderV1 *jh = new AliFastJetHeaderV1(); jh->SetRparam(0.4); // setup parameters if(radius>0)jh->SetRparam(radius); jh->SetAlgorithm(2); // antikt from fastjet/JetDefinition.hh jetFinder = new AliFastJetFinder(); if (jh) jetFinder->SetJetHeader(jh); break; case "UA1": AliUA1JetHeaderV1 *jh=new AliUA1JetHeaderV1(); jh->SetComment("UA1 jet code with default parameters"); jh->BackgMode(0); jh->SetRadius(0.4); if(radius>0)jh->SetRadius(radius); jh->SetEtSeed(4.); jh->SetLegoNbinPhi(432); jh->SetLegoNbinEta(274); jh->SetLegoEtaMin(-2); jh->SetLegoEtaMax(+2); jh->SetMinJetEt(10.); jh->SetJetEtaMax(1.5); jh->SetJetEtaMin(-1.5); jetFinder = new AliUA1JetFinderV1(); if (jh) jetFinder->SetJetHeader(jh); break; case "UA1MC": AliUA1JetHeaderV1 *jh=new AliUA1JetHeaderV1(); jh->SetComment("UA1 jet code with default MC parameters"); jh->BackgMode(0); jh->SetRadius(1.0); if(radius>0)jh->SetRadius(radius); jh->SetEtSeed(4.); jh->SetLegoNbinPhi(432); jh->SetLegoNbinEta(274); jh->SetLegoEtaMin(-2); jh->SetLegoEtaMax(+2); jh->SetMinJetEt(10.); jh->SetJetEtaMax(1.5); jh->SetJetEtaMin(-1.5); jetFinder = new AliUA1JetFinderV1(); if (jh) jetFinder->SetJetHeader(jh); break; default: Printf("\n >>>>>>> AddTaskJets Error Wrong jet finder selected\n"); break; } return jetFinder; } AliJetReader *CreateJetReader(Char_t *jr){ AliJetReader *er = 0; switch (jr) { case "MC": AliJetKineReaderHeader *jrh = new AliJetKineReaderHeader(); jrh->SetComment("MC full Kinematics"); jrh->SetFastSimTPC(kFALSE); jrh->SetFastSimEMCAL(kFALSE); jrh->SetPtCut(0.); jrh->SetFiducialEta(-2.1,2.1); // to take all MC particles default is 0 .9 // Define reader and set its header er = new AliJetKineReader(); er->SetReaderHeader(jrh); break; case "MC2": AliJetKineReaderHeader *jrh = new AliJetKineReaderHeader(); jrh->SetComment("MC full Kinematics spearate config charged only"); jrh->SetFastSimTPC(kFALSE); jrh->SetFastSimEMCAL(kFALSE); jrh->SetChargedOnly(kTRUE); jrh->SetPtCut(0.); jrh->SetFiducialEta(-2.1,2.1); // to take all MC particles default is 0 .9 // Define reader and set its header er = new AliJetKineReader(); er->SetReaderHeader(jrh); break; case "ESD": AliJetESDReaderHeader *jrh = new AliJetESDReaderHeader(); jrh->SetComment("Testing"); jrh->SetFirstEvent(0); jrh->SetLastEvent(1000); jrh->SetPtCut(0.); jrh->SetReadSignalOnly(kFALSE); // Define reader and set its header er = new AliJetESDReader(); er->SetReaderHeader(jrh); break; case "AOD": AliJetAODReaderHeader *jrh = new AliJetAODReaderHeader(); jrh->SetComment("AOD Reader"); jrh->SetPtCut(0.); jrh->SetTestFilterMask(1<<0); // Define reader and set its header er = new AliJetAODReader(); er->SetReaderHeader(jrh); break; case "AODMC": AliJetAODReaderHeader *jrh = new AliJetAODReaderHeader(); jrh->SetComment("AOD MC Reader"); jrh->SetPtCut(0.); jrh->SetFiducialEta(-2.1,2.1); // to take all MC particles default is 0.9 jrh->SetReadAODMC(1);// 1 all primary MC , 2 all primary charged // Define reader and set its header er = new AliJetAODReader(); er->SetReaderHeader(jrh); break; case "AODMC2": AliJetAODReaderHeader *jrh = new AliJetAODReaderHeader(); jrh->SetComment("AOD MC Reader"); jrh->SetPtCut(0.); jrh->SetFiducialEta(-2.1,2.1); // to take all MC particles default is 0.9 jrh->SetReadAODMC(2);// 1 all primary MC , 2 all primary charged // Define reader and set its header er = new AliJetAODReader(); er->SetReaderHeader(jrh); break; default: ::Error("AddTaskJets", "Wrong jet reader selected\n"); return 0; } return er; } <|endoftext|>
<commit_before>#include <map> #include <cmath> #include <algorithm> #include <fstream> #include <ctime> #include <memory> #include "ChatBot.h" struct userinfo { int smiles; int lastReply; }; vector<wstring> request; vector<shared_ptr<vector<wstring> > > reply; vector<vector<long long> > tf; vector<pair<long long, long long> > fixedstem; vector<pair<long long, long long> > replaced; vector<pair<long long, bool> > blacklist; vector<double> tfnorm; map<long long, int> df; map<int, userinfo> users; set<long long> names; //wofstream misslog; //wofstream alllog; inline double tfidf(long long &word) { return df.count(word) ? log((double)tf.size() / df[word]) : 0.; } inline double sqr(double x) { return x * x; } double norm(vector<long long> &arr) { double ans = 0; for(auto&& i: arr) { ans += sqr(tfidf(i)); } return sqrt(ans); } wstring RandReply(vector<wstring> &v) { return v.size() == 1 ? v[0] : v[rand() % v.size()]; } int randint(int a, int b) { return rand() % (b - a + 1) + a; } void SwapFirst(vector<wstring> &v, bool canStay) { if(v.size() > 1) { swap(v[0], v[randint(1 - canStay, v.size()-1)]); } } long long phnamec = phash(L"firstnamec"); wstring BestReply(wstring &line, int id, bool conf) { line += L' '; if(id >= 0 && users[id].lastReply && reply[abs(users[id].lastReply) - 1]->size() == 1 && line == L' ' + (*reply[abs(users[id].lastReply) - 1])[0] + L' ') { wcerr << line << L" - my reply\n"; return L""; } vector<long long> words = splitWords(line, fixedstem, replaced, names); if(conf) { replace(words.begin(), words.end(), phname, phnamec); } sort(words.begin(), words.end()); words.resize(unique(words.begin(), words.end()) - words.begin()); for(auto &i : blacklist) { if(i.second && id >= 0) continue; if(find(words.begin(), words.end(), i.first) != words.end()) { wcerr << line << L" - blacklisted\n"; return L"$blacklisted"; } } double mx = 0; int imx = 0; vector<long long> common; for(int i=0;i<(int)tf.size();i++) { common.clear(); set_intersection(words.begin(), words.end(), tf[i].begin(), tf[i].end(), back_inserter(common)); double ans = 0; for(auto&& word: common) { ans += sqr(tfidf(word)); } ans /= tfnorm[i]; if(ans > mx + 0.00000001) { mx = ans; imx = i; } } if(mx == 0) { wcerr << line << L" - no match\n"; while(line.length() && line[0] == L' ') { line = line.substr(1); } /* if(id >= 0 && words.size()) { misslog << line << endl; misslog.flush(); }*/ if(id >= 0 && users[id].smiles >= 2) { wcerr << "Too many smiles\n"; return L""; } users[id].smiles++; return L"$noans"; } wcerr << line << L" == " << request[imx] << L" (" << mx / norm(words) << L")"; if(reply[imx]->size() > 1) { wcerr << L", " << reply[imx]->size() << L" replies"; } wcerr << L'\n'; if(users[id].lastReply == imx + 1) { users[id].lastReply = -(imx + 1); } else if(id >= 0 && users[id].lastReply == -(imx + 1)) { wcerr << "Repeated\n"; return L""; } else { users[id].lastReply = imx + 1; } users[id].smiles = 0; wstring ans = (*reply[imx])[0]; SwapFirst(*reply[imx], 0); // alllog << line << L"\n==" << request[imx] << L'\n' << ans << endl; // alllog.flush(); return ans; } wstring Say(wstring &curline, int id, bool conf) { return BestReply(curline, id, conf); } vector<wstring> splitReply(const wstring &t) { vector<wstring> ans; wstring s; for(wchar_t i : t) { if(i == L'|') { if(s.length()) ans.push_back(s); s.clear(); } else { s.push_back(i); } } if(s.length()) ans.push_back(s); SwapFirst(ans, 1); return ans; } void AddReply(const wstring &req, const wstring &rep) { shared_ptr<vector<wstring> > v(new vector<wstring>()); *v = splitReply(rep); for(wstring& i : splitReply(req)) { reply.push_back(v); request.push_back(i); vector<long long> words = splitWords(i, fixedstem, replaced, names); sort(words.begin(), words.end()); words.resize(unique(words.begin(), words.end()) - words.begin()); for(auto& j: words) { df[j]++; } tf.push_back(words); } } wchar_t buf1[12000], buf2[12000]; const string file = "bot.txt"; const string filebl = "blacklist.txt"; const string filestem = "fixedstem.txt"; const string filenames = "names.txt"; void Load() { locale loc(""); //misslog.close(); //misslog.open("miss.log", ofstream::out | ofstream::app); //misslog.imbue(loc); //alllog.close(); //alllog.open("all.log", ofstream::out | ofstream::app); //alllog.imbue(loc); reply.clear(); request.clear(); tf.clear(); tfnorm.clear(); df.clear(); blacklist.clear(); fixedstem.clear(); names.clear(); srand(time(0)); wifstream fin(file); wifstream fstem(filestem); fstem.imbue(loc); while(fstem >> buf1) { fstem >> buf2; if(buf1[0] == '$') { replaced.push_back(make_pair(stem(buf1 + 1), stem(buf2))); } else { wstring s = buf1; for(auto &i : s) i = towupper(i); fixedstem.push_back(make_pair(phash(s), phash(buf2))); // wcerr << s << endl; } } fstem.close(); fin.imbue(loc); while(fin.getline(buf1, 10000)) { fin.getline(buf2, 10000); AddReply(buf1, buf2); //this should be done BEFORE filling names } df[phnamec] = 10000; for(auto&& i : tf) { tfnorm.push_back(norm(i)); } fin.close(); wifstream fbl(filebl); fbl.imbue(loc); while(fbl.getline(buf1, 10000)) { if(buf1[0] == '$') blacklist.push_back({stem(buf1 + 1), 1}); else blacklist.push_back({stem(buf1), 0}); } fbl.close(); wifstream fnm(filenames); fnm.imbue(loc); while(fnm.getline(buf1, 10000)) { for(int i=0;buf1[i];i++) { buf1[i] = towupper(buf1[i]); } names.insert(phash(buf1)); } fbl.close(); for(auto &i : users) { i.second.lastReply = 0; } } <commit_msg>Fixed double spaces in chat.exe console output<commit_after>#include <map> #include <cmath> #include <algorithm> #include <fstream> #include <ctime> #include <memory> #include "ChatBot.h" struct userinfo { int smiles; int lastReply; }; vector<wstring> request; vector<shared_ptr<vector<wstring> > > reply; vector<vector<long long> > tf; vector<pair<long long, long long> > fixedstem; vector<pair<long long, long long> > replaced; vector<pair<long long, bool> > blacklist; vector<double> tfnorm; map<long long, int> df; map<int, userinfo> users; set<long long> names; //wofstream misslog; //wofstream alllog; inline double tfidf(long long &word) { return df.count(word) ? log((double)tf.size() / df[word]) : 0.; } inline double sqr(double x) { return x * x; } double norm(vector<long long> &arr) { double ans = 0; for(auto&& i: arr) { ans += sqr(tfidf(i)); } return sqrt(ans); } wstring RandReply(vector<wstring> &v) { return v.size() == 1 ? v[0] : v[rand() % v.size()]; } int randint(int a, int b) { return rand() % (b - a + 1) + a; } void SwapFirst(vector<wstring> &v, bool canStay) { if(v.size() > 1) { swap(v[0], v[randint(1 - canStay, v.size()-1)]); } } long long phnamec = phash(L"firstnamec"); wstring BestReply(wstring &line, int id, bool conf) { line += L' '; if(id >= 0 && users[id].lastReply && reply[abs(users[id].lastReply) - 1]->size() == 1 && line == L' ' + (*reply[abs(users[id].lastReply) - 1])[0] + L' ') { wcerr << line << L"- my reply\n"; return L""; } vector<long long> words = splitWords(line, fixedstem, replaced, names); if(conf) { replace(words.begin(), words.end(), phname, phnamec); } sort(words.begin(), words.end()); words.resize(unique(words.begin(), words.end()) - words.begin()); for(auto &i : blacklist) { if(i.second && id >= 0) continue; if(find(words.begin(), words.end(), i.first) != words.end()) { wcerr << line << L"- blacklisted\n"; return L"$blacklisted"; } } double mx = 0; int imx = 0; vector<long long> common; for(int i=0;i<(int)tf.size();i++) { common.clear(); set_intersection(words.begin(), words.end(), tf[i].begin(), tf[i].end(), back_inserter(common)); double ans = 0; for(auto&& word: common) { ans += sqr(tfidf(word)); } ans /= tfnorm[i]; if(ans > mx + 0.00000001) { mx = ans; imx = i; } } if(mx == 0) { wcerr << line << L"- no match\n"; while(line.length() && line[0] == L' ') { line = line.substr(1); } /* if(id >= 0 && words.size()) { misslog << line << endl; misslog.flush(); }*/ if(id >= 0 && users[id].smiles >= 2) { wcerr << "Too many smiles\n"; return L""; } users[id].smiles++; return L"$noans"; } wcerr << line << L"== " << request[imx] << L" (" << mx / norm(words) << L")"; if(reply[imx]->size() > 1) { wcerr << L", " << reply[imx]->size() << L" replies"; } wcerr << L'\n'; if(users[id].lastReply == imx + 1) { users[id].lastReply = -(imx + 1); } else if(id >= 0 && users[id].lastReply == -(imx + 1)) { wcerr << "Repeated\n"; return L""; } else { users[id].lastReply = imx + 1; } users[id].smiles = 0; wstring ans = (*reply[imx])[0]; SwapFirst(*reply[imx], 0); // alllog << line << L"\n==" << request[imx] << L'\n' << ans << endl; // alllog.flush(); return ans; } wstring Say(wstring &curline, int id, bool conf) { return BestReply(curline, id, conf); } vector<wstring> splitReply(const wstring &t) { vector<wstring> ans; wstring s; for(wchar_t i : t) { if(i == L'|') { if(s.length()) ans.push_back(s); s.clear(); } else { s.push_back(i); } } if(s.length()) ans.push_back(s); SwapFirst(ans, 1); return ans; } void AddReply(const wstring &req, const wstring &rep) { shared_ptr<vector<wstring> > v(new vector<wstring>()); *v = splitReply(rep); for(wstring& i : splitReply(req)) { reply.push_back(v); request.push_back(i); vector<long long> words = splitWords(i, fixedstem, replaced, names); sort(words.begin(), words.end()); words.resize(unique(words.begin(), words.end()) - words.begin()); for(auto& j: words) { df[j]++; } tf.push_back(words); } } wchar_t buf1[12000], buf2[12000]; const string file = "bot.txt"; const string filebl = "blacklist.txt"; const string filestem = "fixedstem.txt"; const string filenames = "names.txt"; void Load() { locale loc(""); //misslog.close(); //misslog.open("miss.log", ofstream::out | ofstream::app); //misslog.imbue(loc); //alllog.close(); //alllog.open("all.log", ofstream::out | ofstream::app); //alllog.imbue(loc); reply.clear(); request.clear(); tf.clear(); tfnorm.clear(); df.clear(); blacklist.clear(); fixedstem.clear(); names.clear(); srand(time(0)); wifstream fin(file); wifstream fstem(filestem); fstem.imbue(loc); while(fstem >> buf1) { fstem >> buf2; if(buf1[0] == '$') { replaced.push_back(make_pair(stem(buf1 + 1), stem(buf2))); } else { wstring s = buf1; for(auto &i : s) i = towupper(i); fixedstem.push_back(make_pair(phash(s), phash(buf2))); // wcerr << s << endl; } } fstem.close(); fin.imbue(loc); while(fin.getline(buf1, 10000)) { fin.getline(buf2, 10000); AddReply(buf1, buf2); //this should be done BEFORE filling names } df[phnamec] = 10000; for(auto&& i : tf) { tfnorm.push_back(norm(i)); } fin.close(); wifstream fbl(filebl); fbl.imbue(loc); while(fbl.getline(buf1, 10000)) { if(buf1[0] == '$') blacklist.push_back({stem(buf1 + 1), 1}); else blacklist.push_back({stem(buf1), 0}); } fbl.close(); wifstream fnm(filenames); fnm.imbue(loc); while(fnm.getline(buf1, 10000)) { for(int i=0;buf1[i];i++) { buf1[i] = towupper(buf1[i]); } names.insert(phash(buf1)); } fbl.close(); for(auto &i : users) { i.second.lastReply = 0; } } <|endoftext|>
<commit_before>#include "stdafx.h" #include "Problem1.h" /* https://projecteuler.net/problem=1 Multiples of 3 and 5 Problem 1 If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. */ int Problem1::SumMultiplesOf3And5Below(int range) { int sum = 0; if (range > 0) { for (size_t i = 1; i < range; i++) { if (i % 3 == 0 || i % 5 == 0) { sum += i; } } } return sum; } long Problem1::SumBelow(long range) { return 0; } <commit_msg>green-commit - SumBelow_Input2_Returns1<commit_after>#include "stdafx.h" #include "Problem1.h" /* https://projecteuler.net/problem=1 Multiples of 3 and 5 Problem 1 If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. */ int Problem1::SumMultiplesOf3And5Below(int range) { int sum = 0; if (range > 0) { for (size_t i = 1; i < range; i++) { if (i % 3 == 0 || i % 5 == 0) { sum += i; } } } return sum; } long Problem1::SumBelow(long range) { if (range == 2) { return 1; } return 0; } <|endoftext|>
<commit_before>// // CRC.hpp // Clock Signal // // Created by Thomas Harte on 18/09/2016. // Copyright 2016 Thomas Harte. All rights reserved. // #ifndef CRC_hpp #define CRC_hpp #include <cstdint> #include <vector> namespace CRC { /*! Provides a class capable of generating a CRC from source data. */ template <typename T, T reset_value, T xor_output, bool reflect_input, bool reflect_output> class Generator { public: /*! Instantiates a CRC16 that will compute the CRC16 specified by the supplied @c polynomial and @c reset_value. */ Generator(T polynomial): value_(reset_value) { const T top_bit = T(~(T(~0) >> 1)); for(int c = 0; c < 256; c++) { T shift_value = static_cast<T>(c << multibyte_shift); for(int b = 0; b < 8; b++) { T exclusive_or = (shift_value&top_bit) ? polynomial : 0; shift_value = static_cast<T>(shift_value << 1) ^ exclusive_or; } xor_table[c] = shift_value; } } /// Resets the CRC to the reset value. void reset() { value_ = reset_value; } /// Updates the CRC to include @c byte. void add(uint8_t byte) { if(reflect_input) byte = reverse_byte(byte); value_ = static_cast<T>((value_ << 8) ^ xor_table[(value_ >> multibyte_shift) ^ byte]); } /// @returns The current value of the CRC. inline T get_value() const { T result = value_^xor_output; if(reflect_output) { T reflected_output = 0; for(std::size_t c = 0; c < sizeof(T); ++c) { reflected_output = T(reflected_output << 8) | T(reverse_byte(result & 0xff)); result >>= 8; } return reflected_output; } return result; } /// Sets the current value of the CRC. inline void set_value(T value) { value_ = value; } /*! A compound for: reset() [add all data from @c data] get_value() */ template <typename Collection> T compute_crc(const Collection &data) { return compute_crc(data.begin(), data.end()); } /*! A compound for: reset() [add all data from @c begin to @c end] get_value() */ template <typename Iterator> T compute_crc(Iterator begin, Iterator end) { reset(); while(begin != end) { add(*begin); ++begin; } return get_value(); } private: static constexpr int multibyte_shift = (sizeof(T) * 8) - 8; T xor_table[256]; T value_; constexpr uint8_t reverse_byte(uint8_t byte) const { return ((byte & 0x80) ? 0x01 : 0x00) | ((byte & 0x40) ? 0x02 : 0x00) | ((byte & 0x20) ? 0x04 : 0x00) | ((byte & 0x10) ? 0x08 : 0x00) | ((byte & 0x08) ? 0x10 : 0x00) | ((byte & 0x04) ? 0x20 : 0x00) | ((byte & 0x02) ? 0x40 : 0x00) | ((byte & 0x01) ? 0x80 : 0x00); } }; /*! Provides a generator of 16-bit CCITT CRCs, which amongst other uses are those used by the FM and MFM disk encodings. */ struct CCITT: public Generator<uint16_t, 0xffff, 0x0000, false, false> { CCITT(): Generator(0x1021) {} }; /*! Provides a generator of "standard 32-bit" CRCs. */ struct CRC32: public Generator<uint32_t, 0xffffffff, 0xffffffff, true, true> { CRC32(): Generator(0x04c11db7) {} }; } #endif /* CRC_hpp */ <commit_msg>Renames `T` to the more-communicative `IntType`, adds some explicit `constexpr`a.<commit_after>// // CRC.hpp // Clock Signal // // Created by Thomas Harte on 18/09/2016. // Copyright 2016 Thomas Harte. All rights reserved. // #ifndef CRC_hpp #define CRC_hpp #include <cstdint> #include <vector> namespace CRC { /*! Provides a class capable of generating a CRC from source data. */ template <typename IntType, IntType reset_value, IntType output_xor, bool reflect_input, bool reflect_output> class Generator { public: /*! Instantiates a CRC16 that will compute the CRC16 specified by the supplied @c polynomial and @c reset_value. */ Generator(IntType polynomial): value_(reset_value) { const IntType top_bit = IntType(~(IntType(~0) >> 1)); for(int c = 0; c < 256; c++) { IntType shift_value = IntType(c << multibyte_shift); for(int b = 0; b < 8; b++) { IntType exclusive_or = (shift_value&top_bit) ? polynomial : 0; shift_value = IntType(shift_value << 1) ^ exclusive_or; } xor_table[c] = shift_value; } } /// Resets the CRC to the reset value. void reset() { value_ = reset_value; } /// Updates the CRC to include @c byte. void add(uint8_t byte) { if constexpr (reflect_input) byte = reverse_byte(byte); value_ = IntType((value_ << 8) ^ xor_table[(value_ >> multibyte_shift) ^ byte]); } /// @returns The current value of the CRC. inline IntType get_value() const { IntType result = value_ ^ output_xor; if constexpr (reflect_output) { IntType reflected_output = 0; for(std::size_t c = 0; c < sizeof(IntType); ++c) { reflected_output = IntType(reflected_output << 8) | IntType(reverse_byte(result & 0xff)); result >>= 8; } return reflected_output; } return result; } /// Sets the current value of the CRC. inline void set_value(IntType value) { value_ = value; } /*! A compound for: reset() [add all data from @c data] get_value() */ template <typename Collection> IntType compute_crc(const Collection &data) { return compute_crc(data.begin(), data.end()); } /*! A compound for: reset() [add all data from @c begin to @c end] get_value() */ template <typename Iterator> IntType compute_crc(Iterator begin, Iterator end) { reset(); while(begin != end) { add(*begin); ++begin; } return get_value(); } private: static constexpr int multibyte_shift = (sizeof(IntType) * 8) - 8; IntType xor_table[256]; IntType value_; constexpr uint8_t reverse_byte(uint8_t byte) const { return ((byte & 0x80) ? 0x01 : 0x00) | ((byte & 0x40) ? 0x02 : 0x00) | ((byte & 0x20) ? 0x04 : 0x00) | ((byte & 0x10) ? 0x08 : 0x00) | ((byte & 0x08) ? 0x10 : 0x00) | ((byte & 0x04) ? 0x20 : 0x00) | ((byte & 0x02) ? 0x40 : 0x00) | ((byte & 0x01) ? 0x80 : 0x00); } }; /*! Provides a generator of 16-bit CCITT CRCs, which amongst other uses are those used by the FM and MFM disk encodings. */ struct CCITT: public Generator<uint16_t, 0xffff, 0x0000, false, false> { CCITT(): Generator(0x1021) {} }; /*! Provides a generator of "standard 32-bit" CRCs. */ struct CRC32: public Generator<uint32_t, 0xffffffff, 0xffffffff, true, true> { CRC32(): Generator(0x04c11db7) {} }; } #endif /* CRC_hpp */ <|endoftext|>
<commit_before>#include <boost/test/unit_test.hpp> #include "main.h" #include "wallet.h" #include "util.h" BOOST_AUTO_TEST_SUITE(base64_tests) BOOST_AUTO_TEST_CASE(base64_testvectors) { static const std::string vstrIn[] = {"","f","fo","foo","foob","fooba","foobar"}; static const std::string vstrOut[] = {"","Zg==","Zm8=","Zm9v","Zm9vYg==","Zm9vYmE=","Zm9vYmFy"}; for (unsigned int i=0; i<sizeof(vstrIn)/sizeof(vstrIn[0]); i++) { std::string strEnc = EncodeBase64(vstrIn[i]); BOOST_CHECK(strEnc == vstrOut[i]); std::string strDec = DecodeBase64(strEnc); BOOST_CHECK(strDec == vstrIn[i]); } } BOOST_AUTO_TEST_SUITE_END() <commit_msg>Delete base64_tests.cpp<commit_after><|endoftext|>
<commit_before>/* WordPerfectImportFilter: Sets up the filter, and calls DocumentCollector * to do the actual filtering * * Copyright (C) 2000 by Sun Microsystems, Inc. * Copyright (C) 2002-2004 William Lachance (wlach@interlog.com) * Copyright (C) 2004 Net Integration Technologies (http://www.net-itech.com) * Copyright (C) 2004 Fridrich Strba <fridrich.strba@bluewin.ch> * * 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., 59 Temple Place - Suite 330, Boston, MA * 02111-1307, USA. * * Contributor(s): Martin Gallwey (gallwey@sun.com) * */ /* "This product is not manufactured, approved, or supported by * Corel Corporation or Corel Corporation Limited." */ #ifndef _OSL_DIAGNOSE_H_ #include <osl/diagnose.h> #endif #ifndef _RTL_TENCINFO_H_ #include <rtl/tencinfo.h> #endif #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_IO_XINPUTSTREAM_HPP_ #include <com/sun/star/io/XInputStream.hpp> #endif #ifndef _COM_SUN_STAR_XML_SAX_XATTRIBUTELIST_HPP_ #include <com/sun/star/xml/sax/XAttributeList.hpp> #endif #ifndef _COM_SUN_STAR_XML_SAX_XDOCUMENTHANDLER_HPP_ #include <com/sun/star/xml/sax/XDocumentHandler.hpp> #endif #ifndef _COM_SUN_STAR_XML_SAX_INPUTSOURCE_HPP_ #include <com/sun/star/xml/sax/InputSource.hpp> #endif #ifndef _COM_SUN_STAR_XML_SAX_XPARSER_HPP_ #include <com/sun/star/xml/sax/XParser.hpp> #endif #ifndef _COM_SUN_STAR_UCB_XCOMMANDENVIRONMENT_HPP #include <com/sun/star/ucb/XCommandEnvironment.hpp> #endif #ifndef _ATTRLIST_HPP_ #include <xmloff/attrlist.hxx> #endif #ifndef _XMLKYWD_HPP #include <xmloff/xmlkywd.hxx> #endif #ifndef _UCBHELPER_CONTENT_HXX #include <ucbhelper/content.hxx> #endif #include "filter/FilterInternal.hxx" #include "filter/DocumentHandler.hxx" #include "filter/DocumentCollector.hxx" #include "stream/WPXSvStream.h" #if defined _MSC_VER #pragma warning( push, 1 ) #endif #include <libwpd/WPDocument.h> #if defined _MSC_VER #pragma warning( pop ) #endif #include "WordPerfectCollector.hxx" #include "WordPerfectImportFilter.hxx" using namespace ::rtl; using namespace ::com::sun::star; using rtl::OString; using rtl::OUString; using com::sun::star::uno::Sequence; using com::sun::star::uno::Reference; using com::sun::star::uno::Any; using com::sun::star::uno::UNO_QUERY; using com::sun::star::uno::XInterface; using com::sun::star::uno::Exception; using com::sun::star::uno::RuntimeException; using com::sun::star::lang::XMultiServiceFactory; using com::sun::star::beans::PropertyValue; using com::sun::star::document::XFilter; using com::sun::star::document::XExtendedFilterDetection; using com::sun::star::ucb::XCommandEnvironment; using com::sun::star::io::XInputStream; using com::sun::star::document::XImporter; using com::sun::star::xml::sax::InputSource; using com::sun::star::xml::sax::XAttributeList; using com::sun::star::xml::sax::XDocumentHandler; using com::sun::star::xml::sax::XParser; void callHandler(uno::Reference < XDocumentHandler > xDocHandler); sal_Bool SAL_CALL WordPerfectImportFilter::importImpl( const Sequence< ::com::sun::star::beans::PropertyValue >& aDescriptor ) throw (RuntimeException) { WRITER_DEBUG_MSG(("WordPerfectImportFilter::importImpl: Got here!\n")); sal_Int32 nLength = aDescriptor.getLength(); const PropertyValue * pValue = aDescriptor.getConstArray(); OUString sURL; uno::Reference < XInputStream > xInputStream; for ( sal_Int32 i = 0 ; i < nLength; i++) { if ( pValue[i].Name.equalsAsciiL ( RTL_CONSTASCII_STRINGPARAM ( "InputStream" ) ) ) pValue[i].Value >>= xInputStream; else if ( pValue[i].Name.equalsAsciiL ( RTL_CONSTASCII_STRINGPARAM ( "URL" ) ) ) pValue[i].Value >>= sURL; } if ( !xInputStream.is() ) { OSL_ASSERT( 0 ); return sal_False; } OString sFileName; sFileName = OUStringToOString(sURL, RTL_TEXTENCODING_INFO_ASCII); // An XML import service: what we push sax messages to.. OUString sXMLImportService ( RTL_CONSTASCII_USTRINGPARAM ( "com.sun.star.comp.Writer.XMLImporter" ) ); uno::Reference < XDocumentHandler > xInternalHandler( mxMSF->createInstance( sXMLImportService ), UNO_QUERY ); // The XImporter sets up an empty target document for XDocumentHandler to write to.. uno::Reference < XImporter > xImporter(xInternalHandler, UNO_QUERY); xImporter->setTargetDocument(mxDoc); // OO Document Handler: abstract class to handle document SAX messages, concrete implementation here // writes to in-memory target doc DocumentHandler xHandler(xInternalHandler); WPXSvInputStream input( xInputStream ); WordPerfectCollector collector(&input, &xHandler); collector.filter(); return true; } sal_Bool SAL_CALL WordPerfectImportFilter::filter( const Sequence< ::com::sun::star::beans::PropertyValue >& aDescriptor ) throw (RuntimeException) { WRITER_DEBUG_MSG(("WordPerfectImportFilter::filter: Got here!\n")); return importImpl ( aDescriptor ); } void SAL_CALL WordPerfectImportFilter::cancel( ) throw (RuntimeException) { WRITER_DEBUG_MSG(("WordPerfectImportFilter::cancel: Got here!\n")); } // XImporter void SAL_CALL WordPerfectImportFilter::setTargetDocument( const uno::Reference< ::com::sun::star::lang::XComponent >& xDoc ) throw (::com::sun::star::lang::IllegalArgumentException, RuntimeException) { WRITER_DEBUG_MSG(("WordPerfectImportFilter::getTargetDocument: Got here!\n")); meType = FILTER_IMPORT; mxDoc = xDoc; } // XExtendedFilterDetection OUString SAL_CALL WordPerfectImportFilter::detect( com::sun::star::uno::Sequence< PropertyValue >& Descriptor ) throw( com::sun::star::uno::RuntimeException ) { WRITER_DEBUG_MSG(("WordPerfectImportFilter::detect: Got here!\n")); WPDConfidence confidence = WPD_CONFIDENCE_NONE; OUString sTypeName = OUString( RTL_CONSTASCII_USTRINGPARAM ( "" ) ); sal_Int32 nLength = Descriptor.getLength(); sal_Int32 location = nLength; OUString sURL; const PropertyValue * pValue = Descriptor.getConstArray(); uno::Reference < XInputStream > xInputStream; for ( sal_Int32 i = 0 ; i < nLength; i++) { if ( pValue[i].Name.equalsAsciiL ( RTL_CONSTASCII_STRINGPARAM ( "TypeName" ) ) ) location=i; else if ( pValue[i].Name.equalsAsciiL ( RTL_CONSTASCII_STRINGPARAM ( "InputStream" ) ) ) pValue[i].Value >>= xInputStream; else if ( pValue[i].Name.equalsAsciiL ( RTL_CONSTASCII_STRINGPARAM ( "URL" ) ) ) pValue[i].Value >>= sURL; } uno::Reference< com::sun::star::ucb::XCommandEnvironment > xEnv; if (!xInputStream.is()) { try { ::ucbhelper::Content aContent(sURL, xEnv); xInputStream = aContent.openStream(); } catch ( ... ) { return ::rtl::OUString(); } if (!xInputStream.is()) return ::rtl::OUString(); } WPXSvInputStream input( xInputStream ); if (input.atEOS()) return ::rtl::OUString(); confidence = WPDocument::isFileFormatSupported(&input, false); if (confidence == WPD_CONFIDENCE_EXCELLENT) sTypeName = OUString( RTL_CONSTASCII_USTRINGPARAM ( "writer_WordPerfect_Document" ) ); if (sTypeName.getLength()) { if ( location == Descriptor.getLength() ) { Descriptor.realloc(nLength+1); Descriptor[location].Name = ::rtl::OUString::createFromAscii( "TypeName" ); } Descriptor[location].Value <<=sTypeName; } return sTypeName; } // XInitialization void SAL_CALL WordPerfectImportFilter::initialize( const Sequence< Any >& aArguments ) throw (Exception, RuntimeException) { WRITER_DEBUG_MSG(("WordPerfectImportFilter::initialize: Got here!\n")); Sequence < PropertyValue > aAnySeq; sal_Int32 nLength = aArguments.getLength(); if ( nLength && ( aArguments[0] >>= aAnySeq ) ) { const PropertyValue * pValue = aAnySeq.getConstArray(); nLength = aAnySeq.getLength(); for ( sal_Int32 i = 0 ; i < nLength; i++) { if ( pValue[i].Name.equalsAsciiL ( RTL_CONSTASCII_STRINGPARAM ( "Type" ) ) ) { pValue[i].Value >>= msFilterName; break; } } } } OUString WordPerfectImportFilter_getImplementationName () throw (RuntimeException) { return OUString ( RTL_CONSTASCII_USTRINGPARAM ( "com.sun.star.comp.Writer.WordPerfectImportFilter" ) ); } #define SERVICE_NAME1 "com.sun.star.document.ImportFilter" #define SERVICE_NAME2 "com.sun.star.document.ExtendedTypeDetection" sal_Bool SAL_CALL WordPerfectImportFilter_supportsService( const OUString& ServiceName ) throw (RuntimeException) { return (ServiceName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM ( SERVICE_NAME1 ) ) || ServiceName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM ( SERVICE_NAME2 ) ) ); } Sequence< OUString > SAL_CALL WordPerfectImportFilter_getSupportedServiceNames( ) throw (RuntimeException) { Sequence < OUString > aRet(2); // Sequence < OUString > aRet(1); OUString* pArray = aRet.getArray(); pArray[0] = OUString ( RTL_CONSTASCII_USTRINGPARAM ( SERVICE_NAME1 ) ); pArray[1] = OUString ( RTL_CONSTASCII_USTRINGPARAM ( SERVICE_NAME2 ) ); return aRet; } #undef SERVICE_NAME2 #undef SERVICE_NAME1 uno::Reference< XInterface > SAL_CALL WordPerfectImportFilter_createInstance( const uno::Reference< XMultiServiceFactory > & rSMgr) throw( Exception ) { return (cppu::OWeakObject*) new WordPerfectImportFilter( rSMgr ); } // XServiceInfo OUString SAL_CALL WordPerfectImportFilter::getImplementationName( ) throw (RuntimeException) { return WordPerfectImportFilter_getImplementationName(); } sal_Bool SAL_CALL WordPerfectImportFilter::supportsService( const OUString& rServiceName ) throw (RuntimeException) { return WordPerfectImportFilter_supportsService( rServiceName ); } Sequence< OUString > SAL_CALL WordPerfectImportFilter::getSupportedServiceNames( ) throw (RuntimeException) { return WordPerfectImportFilter_getSupportedServiceNames(); } <commit_msg>INTEGRATION: CWS changefileheader (1.4.12); FILE MERGED 2008/04/01 16:06:57 thb 1.4.12.2: #i85898# Stripping all external header guards 2008/04/01 13:02:39 thb 1.4.12.1: #i85898# Stripping all external header guards<commit_after>/* WordPerfectImportFilter: Sets up the filter, and calls DocumentCollector * to do the actual filtering * * Copyright (C) 2000 by Sun Microsystems, Inc. * Copyright (C) 2002-2004 William Lachance (wlach@interlog.com) * Copyright (C) 2004 Net Integration Technologies (http://www.net-itech.com) * Copyright (C) 2004 Fridrich Strba <fridrich.strba@bluewin.ch> * * 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., 59 Temple Place - Suite 330, Boston, MA * 02111-1307, USA. * * Contributor(s): Martin Gallwey (gallwey@sun.com) * */ /* "This product is not manufactured, approved, or supported by * Corel Corporation or Corel Corporation Limited." */ #include <osl/diagnose.h> #ifndef _RTL_TENCINFO_H_ #include <rtl/tencinfo.h> #endif #include <com/sun/star/lang/XMultiServiceFactory.hpp> #include <com/sun/star/io/XInputStream.hpp> #include <com/sun/star/xml/sax/XAttributeList.hpp> #include <com/sun/star/xml/sax/XDocumentHandler.hpp> #include <com/sun/star/xml/sax/InputSource.hpp> #include <com/sun/star/xml/sax/XParser.hpp> #ifndef _COM_SUN_STAR_UCB_XCOMMANDENVIRONMENT_HPP #include <com/sun/star/ucb/XCommandEnvironment.hpp> #endif #ifndef _ATTRLIST_HPP_ #include <xmloff/attrlist.hxx> #endif #ifndef _XMLKYWD_HPP #include <xmloff/xmlkywd.hxx> #endif #include <ucbhelper/content.hxx> #include "filter/FilterInternal.hxx" #include "filter/DocumentHandler.hxx" #include "filter/DocumentCollector.hxx" #include "stream/WPXSvStream.h" #if defined _MSC_VER #pragma warning( push, 1 ) #endif #include <libwpd/WPDocument.h> #if defined _MSC_VER #pragma warning( pop ) #endif #include "WordPerfectCollector.hxx" #include "WordPerfectImportFilter.hxx" using namespace ::rtl; using namespace ::com::sun::star; using rtl::OString; using rtl::OUString; using com::sun::star::uno::Sequence; using com::sun::star::uno::Reference; using com::sun::star::uno::Any; using com::sun::star::uno::UNO_QUERY; using com::sun::star::uno::XInterface; using com::sun::star::uno::Exception; using com::sun::star::uno::RuntimeException; using com::sun::star::lang::XMultiServiceFactory; using com::sun::star::beans::PropertyValue; using com::sun::star::document::XFilter; using com::sun::star::document::XExtendedFilterDetection; using com::sun::star::ucb::XCommandEnvironment; using com::sun::star::io::XInputStream; using com::sun::star::document::XImporter; using com::sun::star::xml::sax::InputSource; using com::sun::star::xml::sax::XAttributeList; using com::sun::star::xml::sax::XDocumentHandler; using com::sun::star::xml::sax::XParser; void callHandler(uno::Reference < XDocumentHandler > xDocHandler); sal_Bool SAL_CALL WordPerfectImportFilter::importImpl( const Sequence< ::com::sun::star::beans::PropertyValue >& aDescriptor ) throw (RuntimeException) { WRITER_DEBUG_MSG(("WordPerfectImportFilter::importImpl: Got here!\n")); sal_Int32 nLength = aDescriptor.getLength(); const PropertyValue * pValue = aDescriptor.getConstArray(); OUString sURL; uno::Reference < XInputStream > xInputStream; for ( sal_Int32 i = 0 ; i < nLength; i++) { if ( pValue[i].Name.equalsAsciiL ( RTL_CONSTASCII_STRINGPARAM ( "InputStream" ) ) ) pValue[i].Value >>= xInputStream; else if ( pValue[i].Name.equalsAsciiL ( RTL_CONSTASCII_STRINGPARAM ( "URL" ) ) ) pValue[i].Value >>= sURL; } if ( !xInputStream.is() ) { OSL_ASSERT( 0 ); return sal_False; } OString sFileName; sFileName = OUStringToOString(sURL, RTL_TEXTENCODING_INFO_ASCII); // An XML import service: what we push sax messages to.. OUString sXMLImportService ( RTL_CONSTASCII_USTRINGPARAM ( "com.sun.star.comp.Writer.XMLImporter" ) ); uno::Reference < XDocumentHandler > xInternalHandler( mxMSF->createInstance( sXMLImportService ), UNO_QUERY ); // The XImporter sets up an empty target document for XDocumentHandler to write to.. uno::Reference < XImporter > xImporter(xInternalHandler, UNO_QUERY); xImporter->setTargetDocument(mxDoc); // OO Document Handler: abstract class to handle document SAX messages, concrete implementation here // writes to in-memory target doc DocumentHandler xHandler(xInternalHandler); WPXSvInputStream input( xInputStream ); WordPerfectCollector collector(&input, &xHandler); collector.filter(); return true; } sal_Bool SAL_CALL WordPerfectImportFilter::filter( const Sequence< ::com::sun::star::beans::PropertyValue >& aDescriptor ) throw (RuntimeException) { WRITER_DEBUG_MSG(("WordPerfectImportFilter::filter: Got here!\n")); return importImpl ( aDescriptor ); } void SAL_CALL WordPerfectImportFilter::cancel( ) throw (RuntimeException) { WRITER_DEBUG_MSG(("WordPerfectImportFilter::cancel: Got here!\n")); } // XImporter void SAL_CALL WordPerfectImportFilter::setTargetDocument( const uno::Reference< ::com::sun::star::lang::XComponent >& xDoc ) throw (::com::sun::star::lang::IllegalArgumentException, RuntimeException) { WRITER_DEBUG_MSG(("WordPerfectImportFilter::getTargetDocument: Got here!\n")); meType = FILTER_IMPORT; mxDoc = xDoc; } // XExtendedFilterDetection OUString SAL_CALL WordPerfectImportFilter::detect( com::sun::star::uno::Sequence< PropertyValue >& Descriptor ) throw( com::sun::star::uno::RuntimeException ) { WRITER_DEBUG_MSG(("WordPerfectImportFilter::detect: Got here!\n")); WPDConfidence confidence = WPD_CONFIDENCE_NONE; OUString sTypeName = OUString( RTL_CONSTASCII_USTRINGPARAM ( "" ) ); sal_Int32 nLength = Descriptor.getLength(); sal_Int32 location = nLength; OUString sURL; const PropertyValue * pValue = Descriptor.getConstArray(); uno::Reference < XInputStream > xInputStream; for ( sal_Int32 i = 0 ; i < nLength; i++) { if ( pValue[i].Name.equalsAsciiL ( RTL_CONSTASCII_STRINGPARAM ( "TypeName" ) ) ) location=i; else if ( pValue[i].Name.equalsAsciiL ( RTL_CONSTASCII_STRINGPARAM ( "InputStream" ) ) ) pValue[i].Value >>= xInputStream; else if ( pValue[i].Name.equalsAsciiL ( RTL_CONSTASCII_STRINGPARAM ( "URL" ) ) ) pValue[i].Value >>= sURL; } uno::Reference< com::sun::star::ucb::XCommandEnvironment > xEnv; if (!xInputStream.is()) { try { ::ucbhelper::Content aContent(sURL, xEnv); xInputStream = aContent.openStream(); } catch ( ... ) { return ::rtl::OUString(); } if (!xInputStream.is()) return ::rtl::OUString(); } WPXSvInputStream input( xInputStream ); if (input.atEOS()) return ::rtl::OUString(); confidence = WPDocument::isFileFormatSupported(&input, false); if (confidence == WPD_CONFIDENCE_EXCELLENT) sTypeName = OUString( RTL_CONSTASCII_USTRINGPARAM ( "writer_WordPerfect_Document" ) ); if (sTypeName.getLength()) { if ( location == Descriptor.getLength() ) { Descriptor.realloc(nLength+1); Descriptor[location].Name = ::rtl::OUString::createFromAscii( "TypeName" ); } Descriptor[location].Value <<=sTypeName; } return sTypeName; } // XInitialization void SAL_CALL WordPerfectImportFilter::initialize( const Sequence< Any >& aArguments ) throw (Exception, RuntimeException) { WRITER_DEBUG_MSG(("WordPerfectImportFilter::initialize: Got here!\n")); Sequence < PropertyValue > aAnySeq; sal_Int32 nLength = aArguments.getLength(); if ( nLength && ( aArguments[0] >>= aAnySeq ) ) { const PropertyValue * pValue = aAnySeq.getConstArray(); nLength = aAnySeq.getLength(); for ( sal_Int32 i = 0 ; i < nLength; i++) { if ( pValue[i].Name.equalsAsciiL ( RTL_CONSTASCII_STRINGPARAM ( "Type" ) ) ) { pValue[i].Value >>= msFilterName; break; } } } } OUString WordPerfectImportFilter_getImplementationName () throw (RuntimeException) { return OUString ( RTL_CONSTASCII_USTRINGPARAM ( "com.sun.star.comp.Writer.WordPerfectImportFilter" ) ); } #define SERVICE_NAME1 "com.sun.star.document.ImportFilter" #define SERVICE_NAME2 "com.sun.star.document.ExtendedTypeDetection" sal_Bool SAL_CALL WordPerfectImportFilter_supportsService( const OUString& ServiceName ) throw (RuntimeException) { return (ServiceName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM ( SERVICE_NAME1 ) ) || ServiceName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM ( SERVICE_NAME2 ) ) ); } Sequence< OUString > SAL_CALL WordPerfectImportFilter_getSupportedServiceNames( ) throw (RuntimeException) { Sequence < OUString > aRet(2); // Sequence < OUString > aRet(1); OUString* pArray = aRet.getArray(); pArray[0] = OUString ( RTL_CONSTASCII_USTRINGPARAM ( SERVICE_NAME1 ) ); pArray[1] = OUString ( RTL_CONSTASCII_USTRINGPARAM ( SERVICE_NAME2 ) ); return aRet; } #undef SERVICE_NAME2 #undef SERVICE_NAME1 uno::Reference< XInterface > SAL_CALL WordPerfectImportFilter_createInstance( const uno::Reference< XMultiServiceFactory > & rSMgr) throw( Exception ) { return (cppu::OWeakObject*) new WordPerfectImportFilter( rSMgr ); } // XServiceInfo OUString SAL_CALL WordPerfectImportFilter::getImplementationName( ) throw (RuntimeException) { return WordPerfectImportFilter_getImplementationName(); } sal_Bool SAL_CALL WordPerfectImportFilter::supportsService( const OUString& rServiceName ) throw (RuntimeException) { return WordPerfectImportFilter_supportsService( rServiceName ); } Sequence< OUString > SAL_CALL WordPerfectImportFilter::getSupportedServiceNames( ) throw (RuntimeException) { return WordPerfectImportFilter_getSupportedServiceNames(); } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: skeletonmaker.cxx,v $ * * $Revision: 1.9 $ * * last change: $Author: ihi $ $Date: 2006-12-20 12:43:27 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #include <iostream> #include "sal/main.h" #include "rtl/process.h" #include "rtl/ustrbuf.hxx" #include "unodevtools/typemanager.hxx" #include "unodevtools/options.hxx" #include "skeletonjava.hxx" #include "skeletoncpp.hxx" #include "com/sun/star/uno/Reference.hxx" using namespace ::rtl; using namespace ::skeletonmaker; using namespace ::unodevtools; using namespace ::com::sun::star::uno; namespace { static const char usageText[] = "\n sub-commands:\n" " dump dump declarations on stdout (e.g. constructors, methods, type\n" " mapping for properties) or complete method bodies with\n" " method forwarding.\n" " component generates language specific code skeleton files using the\n" " implementation name as the file and class name\n" " calc-add-in generates a language specific code skeleton for a calc add-in\n" " using the implementation name as the file and class name. A \n" " service type is necessary, referencing an interface which defines\n" " the new add-in functions.\n" " add-on generates a language specific code skeleton for an add-on compnent\n" " using the implementation name as the file and class name. The protocol\n" " name(s) and the corresponding command(s) have to be specified with the\n" " '-p' option.\n" "\n options:\n" " -env:INIFILENAME=<url> url specifies a URL to an UNO ini|rc file of an\n" " existing UNO environment (URE, office installation).\n" " -env:UNO_TYPES=<url> url specifies a binary type library file. It can be\n" " a space separated list of urls.\n" " -a, --all list all interface methods, not only the direct\n" " ones\n" " --(java4|java5|cpp) select the target language\n" " --java4 generate output for Java 1.4 or earlier\n" " --java5 generate output for Java 1.5 or later (is \n" " currently the default)\n" " --cpp generate output for C++\n" " -sn, --shortnames using namespace abbreviation 'css:': for\n" " '::com::sun::star::', only valid for sub-command\n" " 'dump' and target language 'cpp'. It is default for the\n" " sub-command 'component'.\n" " --propertysetmixin the generated skeleton implements the cppu::PropertySetMixin\n" " helper if a referenced new style service specifies an\n" " interface which provides attributes (directly or inherited).\n" " -lh --licenseheader generates a default OpenOffice.org LGPL license\n" " header at the beginning of a component source file.\n" " This option is taken into account in 'component' mode\n" " only and if -o is unequal 'stdout'.\n" " -bc specifies that the generated calc add-in is backward\n" " --backward-compatible compatible to older office versions and implement the\n" " former required add-in interfaces where the implementation\n" " is mapped on the new add-in configuration. In this case\n" " the config schema needs to be bundled with the extension\n" " add-in as well. Default is a minimal add-in component\n" " skeleton based on the configuration coming with the\n" " office since OO.org 2.0.4.\n" " -o <path> path specifies an existing directory where the\n" " output files are generated to, only valid for\n" " sub-command 'component'. If path=stdout the generated\n" " code is generated on standard out instead of a file.\n" " -l <file> specifies a binary type library (can be used more\n" " than once). The type library is integrated as an\n" " additional type provider in the bootstrapped type\n" " system.\n" " -n <name> specifies an implementation name for the component\n" " (used as classname, filename and package|namespace\n" " name). In 'dump' mode it is used as classname (e.g.\n" " \"MyBase::\", C++ only) to generate method bodies not\n" " inline.\n" " -d <name> specifies a base classname or a delegator.\n" " In 'dump' mode it is used as a delegator to forward\n" " methods. It can be used as '<name>::' for base\n" " forwarding, or '<name>->|.' for composition.\n" " Using \"_\" means that a default bodies with default\n" " return values are dumped.\n" " -t <name> specifies an UNOIDL type name, e.g.\n" " com.sun.star.text.XText (can be used more than once)\n" " -p <protocol:cmd(s)> specifies an add-on protocol name and the corresponding\n" " command names, where the commands are a ',' separated list\n" " of unique commands. This option is only valid for add-ons.\n" " -V, --version print version number and exit\n" " -h, --help print this help and exit\n\n" " Sun Microsystems (R) "; void printUsageAndExit(const char* programname, const char* version) { std::cerr << "\n using: " << programname << " (-env:INIFILENAME=<url> | -env:UNO_TYPES=<url>)\n" << " dump [<options>] -t <type> ...\n" << " " << programname << " (-env:INIFILENAME=<url> | -env:UNO_TYPES=<url>)\n" << " component [<options>] -n <name> -t <type> ...\n" << " " << programname << " (-env:INIFILENAME=<url> | -env:UNO_TYPES=<url>)\n" << " calc-add-in [<options>] -n <name> -t <add-in_service>\n" << " " << programname << " (-env:INIFILENAME=<url> | -env:UNO_TYPES=<url>)\n" << " add-on [<options>] -n <name> -p <protocol_name:command,...>\n" << " " << programname << " -V, --version\n" << " " << programname << " -h, --help\n" << usageText << programname << " Version " << version << "\n\n"; } } SAL_IMPLEMENT_MAIN_WITH_ARGS(argc, /*argv*/) { const char* version = "0.4"; const char* programname = "uno-skeletonmaker"; if ( argc <= 1 ) { printUsageAndExit(programname, version); exit(EXIT_FAILURE); } ProgramOptions options; std::vector< OUString > registries; std::vector< OString > types; OString delegate; try { sal_Int32 nPos = 0; sal_Int32 nCount = (sal_Int32)rtl_getAppCommandArgCount(); OUString arg, sOption; sal_Bool bOption=sal_False; // check command rtl_getAppCommandArg(nPos++, &arg.pData); if ( arg.equals(OUString(RTL_CONSTASCII_USTRINGPARAM("dump"))) ) { options.dump = true; } else if ( arg.equals(OUString(RTL_CONSTASCII_USTRINGPARAM("component"))) ) { options.dump = false; options.shortnames = true; } else if ( arg.equals(OUString(RTL_CONSTASCII_USTRINGPARAM("calc-add-in"))) ) { options.dump = false; options.shortnames = true; options.componenttype = 2; } else if ( arg.equals(OUString(RTL_CONSTASCII_USTRINGPARAM("add-on"))) ) { options.dump = false; options.shortnames = true; options.componenttype = 3; } else if ( readOption( &bOption, "h", &nPos, arg) || readOption( &bOption, "help", &nPos, arg) ) { printUsageAndExit(programname, version); exit(EXIT_SUCCESS); } else if ( readOption( &bOption, "V", &nPos, arg) || readOption( &bOption, "version", &nPos, arg) ) { std::cerr << "\n Sun Microsystems (R) " << programname << " Version " << version << "\n\n"; exit(EXIT_SUCCESS); } else { std::cerr << "ERROR: unexpected command \"" << OUStringToOString(arg, RTL_TEXTENCODING_UTF8).getStr() << "\"!\n"; printUsageAndExit(programname, version); exit(EXIT_FAILURE); } // read up to arguments while ( nPos < nCount ) { rtl_getAppCommandArg(nPos, &arg.pData); if ( readOption( &bOption, "a", &nPos, arg) || readOption( &bOption, "all", &nPos, arg) ) { options.all = true; continue; } if ( readOption( &bOption, "java4", &nPos, arg) ) { options.java5 = false; options.language = 1; continue; } if ( readOption( &bOption, "java5", &nPos, arg) ) { options.java5 = true; options.language = 1; continue; } if ( readOption( &bOption, "cpp", &nPos, arg) ) { options.java5 = false; options.language = 2; continue; } if ( readOption( &bOption, "sn", &nPos, arg) || readOption( &bOption, "shortnames", &nPos, arg) ) { options.shortnames = true; continue; } if ( readOption( &bOption, "lh", &nPos, arg) || readOption( &bOption, "licenseheader", &nPos, arg) ) { options.license = true; continue; } if ( readOption( &bOption, "bc", &nPos, arg) || readOption( &bOption, "backward-compatible", &nPos, arg) ) { options.backwardcompatible = true; continue; } if ( readOption( &bOption, "propertysetmixin", &nPos, arg) ) { options.supportpropertysetmixin = true; continue; } if ( readOption( &sOption, "d", &nPos, arg) ) { delegate = OUStringToOString(sOption, RTL_TEXTENCODING_UTF8); continue; } if ( readOption( &sOption, "n", &nPos, arg) ) { options.implname = OUStringToOString(sOption, RTL_TEXTENCODING_UTF8); continue; } if ( readOption( &sOption, "o", &nPos, arg) ) { options.outputpath = OUStringToOString(sOption, RTL_TEXTENCODING_UTF8); continue; } if ( readOption( &sOption, "l", &nPos, arg) ) { registries.push_back(sOption); continue; } if ( readOption( &sOption, "t", &nPos, arg) ) { types.push_back(OUStringToOString(sOption, RTL_TEXTENCODING_UTF8)); continue; } if ( readOption( &sOption, "p", &nPos, arg) ) { OString sTmp(OUStringToOString(sOption, RTL_TEXTENCODING_UTF8)); sal_Int32 nIndex= sTmp.indexOf(':'); OString sPrt = sTmp.copy(0, nIndex+1); OString sCmds = sTmp.copy(nIndex+1); nIndex = 0; std::vector< OString > vCmds; do { OString sCmd = sCmds.getToken( 0, ',', nIndex ); vCmds.push_back(sCmd); } while ( nIndex >= 0 ); options.protocolCmdMap.insert(ProtocolCmdMap::value_type(sPrt, vCmds)); continue; } // else illegal argument OUStringBuffer buf( 64 ); buf.appendAscii(RTL_CONSTASCII_STRINGPARAM("unexpected parameter \"")); buf.append(arg); buf.appendAscii(RTL_CONSTASCII_STRINGPARAM("\"!")); throw RuntimeException(buf.makeStringAndClear(), Reference< XInterface >()); } if ( types.empty() && options.componenttype != 3) { std::cerr << ("\nError: no type is specified, use the -T option at least once\n"); printUsageAndExit(programname, version); exit(EXIT_FAILURE); } UnoTypeManager manager; if ( !manager.init(registries) ) { std::cerr << ("\nError: Using the binary type libraries failed, check the -L" " options\n"); exit(EXIT_FAILURE); } if ( options.dump ) { std::vector< OString >::const_iterator iter = types.begin(); while (iter != types.end()) { std::cout << "\n/***************************************************" "*****************************/\n"; switch (options.language ) { case 1: //Java java::generateDocumentation(std::cout, options, manager, *iter, delegate); break; case 2: //C++ cpp::generateDocumentation(std::cout, options, manager, *iter, delegate); break; default: OSL_ASSERT(false); break; } ++iter; } } else { switch ( options.language ) { case 1: //Java java::generateSkeleton(options, manager, types, delegate); break; case 2: //C++ cpp::generateSkeleton(options, manager, types, delegate); break; default: OSL_ASSERT(false); break; } } } catch (CannotDumpException & e) { std::cout.flush(); std::cerr << "\nError: " << e.m_message << std::endl; } catch(Exception& e) { std::cout.flush(); std::cerr << "\nError: " << OUStringToOString(e.Message, RTL_TEXTENCODING_UTF8).getStr() << std::endl; } return 0; } <commit_msg>INTEGRATION: CWS changefileheader (1.9.28); FILE MERGED 2008/03/28 15:51:24 rt 1.9.28.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: skeletonmaker.cxx,v $ * $Revision: 1.10 $ * * 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 <iostream> #include "sal/main.h" #include "rtl/process.h" #include "rtl/ustrbuf.hxx" #include "unodevtools/typemanager.hxx" #include "unodevtools/options.hxx" #include "skeletonjava.hxx" #include "skeletoncpp.hxx" #include "com/sun/star/uno/Reference.hxx" using namespace ::rtl; using namespace ::skeletonmaker; using namespace ::unodevtools; using namespace ::com::sun::star::uno; namespace { static const char usageText[] = "\n sub-commands:\n" " dump dump declarations on stdout (e.g. constructors, methods, type\n" " mapping for properties) or complete method bodies with\n" " method forwarding.\n" " component generates language specific code skeleton files using the\n" " implementation name as the file and class name\n" " calc-add-in generates a language specific code skeleton for a calc add-in\n" " using the implementation name as the file and class name. A \n" " service type is necessary, referencing an interface which defines\n" " the new add-in functions.\n" " add-on generates a language specific code skeleton for an add-on compnent\n" " using the implementation name as the file and class name. The protocol\n" " name(s) and the corresponding command(s) have to be specified with the\n" " '-p' option.\n" "\n options:\n" " -env:INIFILENAME=<url> url specifies a URL to an UNO ini|rc file of an\n" " existing UNO environment (URE, office installation).\n" " -env:UNO_TYPES=<url> url specifies a binary type library file. It can be\n" " a space separated list of urls.\n" " -a, --all list all interface methods, not only the direct\n" " ones\n" " --(java4|java5|cpp) select the target language\n" " --java4 generate output for Java 1.4 or earlier\n" " --java5 generate output for Java 1.5 or later (is \n" " currently the default)\n" " --cpp generate output for C++\n" " -sn, --shortnames using namespace abbreviation 'css:': for\n" " '::com::sun::star::', only valid for sub-command\n" " 'dump' and target language 'cpp'. It is default for the\n" " sub-command 'component'.\n" " --propertysetmixin the generated skeleton implements the cppu::PropertySetMixin\n" " helper if a referenced new style service specifies an\n" " interface which provides attributes (directly or inherited).\n" " -lh --licenseheader generates a default OpenOffice.org LGPL license\n" " header at the beginning of a component source file.\n" " This option is taken into account in 'component' mode\n" " only and if -o is unequal 'stdout'.\n" " -bc specifies that the generated calc add-in is backward\n" " --backward-compatible compatible to older office versions and implement the\n" " former required add-in interfaces where the implementation\n" " is mapped on the new add-in configuration. In this case\n" " the config schema needs to be bundled with the extension\n" " add-in as well. Default is a minimal add-in component\n" " skeleton based on the configuration coming with the\n" " office since OO.org 2.0.4.\n" " -o <path> path specifies an existing directory where the\n" " output files are generated to, only valid for\n" " sub-command 'component'. If path=stdout the generated\n" " code is generated on standard out instead of a file.\n" " -l <file> specifies a binary type library (can be used more\n" " than once). The type library is integrated as an\n" " additional type provider in the bootstrapped type\n" " system.\n" " -n <name> specifies an implementation name for the component\n" " (used as classname, filename and package|namespace\n" " name). In 'dump' mode it is used as classname (e.g.\n" " \"MyBase::\", C++ only) to generate method bodies not\n" " inline.\n" " -d <name> specifies a base classname or a delegator.\n" " In 'dump' mode it is used as a delegator to forward\n" " methods. It can be used as '<name>::' for base\n" " forwarding, or '<name>->|.' for composition.\n" " Using \"_\" means that a default bodies with default\n" " return values are dumped.\n" " -t <name> specifies an UNOIDL type name, e.g.\n" " com.sun.star.text.XText (can be used more than once)\n" " -p <protocol:cmd(s)> specifies an add-on protocol name and the corresponding\n" " command names, where the commands are a ',' separated list\n" " of unique commands. This option is only valid for add-ons.\n" " -V, --version print version number and exit\n" " -h, --help print this help and exit\n\n" " Sun Microsystems (R) "; void printUsageAndExit(const char* programname, const char* version) { std::cerr << "\n using: " << programname << " (-env:INIFILENAME=<url> | -env:UNO_TYPES=<url>)\n" << " dump [<options>] -t <type> ...\n" << " " << programname << " (-env:INIFILENAME=<url> | -env:UNO_TYPES=<url>)\n" << " component [<options>] -n <name> -t <type> ...\n" << " " << programname << " (-env:INIFILENAME=<url> | -env:UNO_TYPES=<url>)\n" << " calc-add-in [<options>] -n <name> -t <add-in_service>\n" << " " << programname << " (-env:INIFILENAME=<url> | -env:UNO_TYPES=<url>)\n" << " add-on [<options>] -n <name> -p <protocol_name:command,...>\n" << " " << programname << " -V, --version\n" << " " << programname << " -h, --help\n" << usageText << programname << " Version " << version << "\n\n"; } } SAL_IMPLEMENT_MAIN_WITH_ARGS(argc, /*argv*/) { const char* version = "0.4"; const char* programname = "uno-skeletonmaker"; if ( argc <= 1 ) { printUsageAndExit(programname, version); exit(EXIT_FAILURE); } ProgramOptions options; std::vector< OUString > registries; std::vector< OString > types; OString delegate; try { sal_Int32 nPos = 0; sal_Int32 nCount = (sal_Int32)rtl_getAppCommandArgCount(); OUString arg, sOption; sal_Bool bOption=sal_False; // check command rtl_getAppCommandArg(nPos++, &arg.pData); if ( arg.equals(OUString(RTL_CONSTASCII_USTRINGPARAM("dump"))) ) { options.dump = true; } else if ( arg.equals(OUString(RTL_CONSTASCII_USTRINGPARAM("component"))) ) { options.dump = false; options.shortnames = true; } else if ( arg.equals(OUString(RTL_CONSTASCII_USTRINGPARAM("calc-add-in"))) ) { options.dump = false; options.shortnames = true; options.componenttype = 2; } else if ( arg.equals(OUString(RTL_CONSTASCII_USTRINGPARAM("add-on"))) ) { options.dump = false; options.shortnames = true; options.componenttype = 3; } else if ( readOption( &bOption, "h", &nPos, arg) || readOption( &bOption, "help", &nPos, arg) ) { printUsageAndExit(programname, version); exit(EXIT_SUCCESS); } else if ( readOption( &bOption, "V", &nPos, arg) || readOption( &bOption, "version", &nPos, arg) ) { std::cerr << "\n Sun Microsystems (R) " << programname << " Version " << version << "\n\n"; exit(EXIT_SUCCESS); } else { std::cerr << "ERROR: unexpected command \"" << OUStringToOString(arg, RTL_TEXTENCODING_UTF8).getStr() << "\"!\n"; printUsageAndExit(programname, version); exit(EXIT_FAILURE); } // read up to arguments while ( nPos < nCount ) { rtl_getAppCommandArg(nPos, &arg.pData); if ( readOption( &bOption, "a", &nPos, arg) || readOption( &bOption, "all", &nPos, arg) ) { options.all = true; continue; } if ( readOption( &bOption, "java4", &nPos, arg) ) { options.java5 = false; options.language = 1; continue; } if ( readOption( &bOption, "java5", &nPos, arg) ) { options.java5 = true; options.language = 1; continue; } if ( readOption( &bOption, "cpp", &nPos, arg) ) { options.java5 = false; options.language = 2; continue; } if ( readOption( &bOption, "sn", &nPos, arg) || readOption( &bOption, "shortnames", &nPos, arg) ) { options.shortnames = true; continue; } if ( readOption( &bOption, "lh", &nPos, arg) || readOption( &bOption, "licenseheader", &nPos, arg) ) { options.license = true; continue; } if ( readOption( &bOption, "bc", &nPos, arg) || readOption( &bOption, "backward-compatible", &nPos, arg) ) { options.backwardcompatible = true; continue; } if ( readOption( &bOption, "propertysetmixin", &nPos, arg) ) { options.supportpropertysetmixin = true; continue; } if ( readOption( &sOption, "d", &nPos, arg) ) { delegate = OUStringToOString(sOption, RTL_TEXTENCODING_UTF8); continue; } if ( readOption( &sOption, "n", &nPos, arg) ) { options.implname = OUStringToOString(sOption, RTL_TEXTENCODING_UTF8); continue; } if ( readOption( &sOption, "o", &nPos, arg) ) { options.outputpath = OUStringToOString(sOption, RTL_TEXTENCODING_UTF8); continue; } if ( readOption( &sOption, "l", &nPos, arg) ) { registries.push_back(sOption); continue; } if ( readOption( &sOption, "t", &nPos, arg) ) { types.push_back(OUStringToOString(sOption, RTL_TEXTENCODING_UTF8)); continue; } if ( readOption( &sOption, "p", &nPos, arg) ) { OString sTmp(OUStringToOString(sOption, RTL_TEXTENCODING_UTF8)); sal_Int32 nIndex= sTmp.indexOf(':'); OString sPrt = sTmp.copy(0, nIndex+1); OString sCmds = sTmp.copy(nIndex+1); nIndex = 0; std::vector< OString > vCmds; do { OString sCmd = sCmds.getToken( 0, ',', nIndex ); vCmds.push_back(sCmd); } while ( nIndex >= 0 ); options.protocolCmdMap.insert(ProtocolCmdMap::value_type(sPrt, vCmds)); continue; } // else illegal argument OUStringBuffer buf( 64 ); buf.appendAscii(RTL_CONSTASCII_STRINGPARAM("unexpected parameter \"")); buf.append(arg); buf.appendAscii(RTL_CONSTASCII_STRINGPARAM("\"!")); throw RuntimeException(buf.makeStringAndClear(), Reference< XInterface >()); } if ( types.empty() && options.componenttype != 3) { std::cerr << ("\nError: no type is specified, use the -T option at least once\n"); printUsageAndExit(programname, version); exit(EXIT_FAILURE); } UnoTypeManager manager; if ( !manager.init(registries) ) { std::cerr << ("\nError: Using the binary type libraries failed, check the -L" " options\n"); exit(EXIT_FAILURE); } if ( options.dump ) { std::vector< OString >::const_iterator iter = types.begin(); while (iter != types.end()) { std::cout << "\n/***************************************************" "*****************************/\n"; switch (options.language ) { case 1: //Java java::generateDocumentation(std::cout, options, manager, *iter, delegate); break; case 2: //C++ cpp::generateDocumentation(std::cout, options, manager, *iter, delegate); break; default: OSL_ASSERT(false); break; } ++iter; } } else { switch ( options.language ) { case 1: //Java java::generateSkeleton(options, manager, types, delegate); break; case 2: //C++ cpp::generateSkeleton(options, manager, types, delegate); break; default: OSL_ASSERT(false); break; } } } catch (CannotDumpException & e) { std::cout.flush(); std::cerr << "\nError: " << e.m_message << std::endl; } catch(Exception& e) { std::cout.flush(); std::cerr << "\nError: " << OUStringToOString(e.Message, RTL_TEXTENCODING_UTF8).getStr() << std::endl; } return 0; } <|endoftext|>
<commit_before>#include "Key.h" namespace OpenPGP { namespace Packet { Key::Key(uint8_t tag) : Tag(tag), time(), pka(), mpi(), expire() {} Key::Key() : Key(0) {} Key::Key(const Key & copy) : Tag(copy), time(copy.time), pka(copy.pka), mpi(copy.mpi), expire(copy.expire) {} Key::Key(const std::string & data) : Key() { read(data); } Key::~Key(){} void Key::read(const std::string & data){ std::string::size_type pos = 0; read_common(data, pos); } std::string Key::show(const std::size_t indents, const std::size_t indent_size) const{ const std::string tab(indents * indent_size, ' '); return tab + show_title() + "\n" + show_common(indents, indent_size); } std::string Key::raw() const{ return raw_common(); } void Key::read_common(const std::string & data, std::string::size_type & pos){ size = data.size(); version = data[pos]; time = toint(data.substr(pos + 1, 4), 256); if (version < 4){ expire = (data[pos + 5] << 8) + data[pos + 6]; pka = data[pos + 7]; pos += 8; mpi.push_back(read_MPI(data, pos)); // RSA n mpi.push_back(read_MPI(data, pos)); // RSA e } else if (version == 4){ pka = data[pos + 5]; pos += 6; // at minimum RSA mpi.push_back(read_MPI(data, pos)); // RSA n, DSA p, ELGAMAL p mpi.push_back(read_MPI(data, pos)); // RSA e, DSA q, ELGAMAL g // DSA if (pka == PKA::ID::DSA){ mpi.push_back(read_MPI(data, pos)); // DSA g mpi.push_back(read_MPI(data, pos)); // DSA y } // ELGAMAL else if (pka == PKA::ID::ELGAMAL){ mpi.push_back(read_MPI(data, pos)); // ELGAMAL y } } } std::string Key::show_common(const std::size_t indents, const std::size_t indent_size) const{ const std::string indent(indents * indent_size, ' '); const std::string tab(indent_size, ' '); std::string out = indent + tab + "Version: " + std::to_string(version) + " - " + ((version < 4)?"Old":"New") + "\n" + indent + tab + "Creation Time: " + show_time(time) + "\n"; if (version < 4){ out += indent + tab + "Expiration Time (Days): " + std::to_string(expire) + "\n"; if (!expire){ out += " (Never)\n"; } out += indent + tab + "Public Key Algorithm: " + PKA::NAME.at(pka) + " (pka " + std::to_string(pka) + ")\n" + indent + tab + "RSA n: " + mpitohex(mpi[0]) + "(" + std::to_string(bitsize(mpi[0])) + " bits)\n" + indent + tab + "RSA e: " + mpitohex(mpi[1]); } else if (version == 4){ out += indent + tab + "Public Key Algorithm: " + PKA::NAME.at(pka) + " (pka " + std::to_string(pka) + ")\n"; if (PKA::is_RSA(pka)){ out += indent + tab + "RSA n (" + std::to_string(bitsize(mpi[0])) + " bits): " + mpitohex(mpi[0]) + "\n" + indent + tab + "RSA e (" + std::to_string(bitsize(mpi[1])) + " bits): " + mpitohex(mpi[1]); } else if (pka == PKA::ID::ELGAMAL){ out += indent + tab + "ELGAMAL p (" + std::to_string(bitsize(mpi[0])) + " bits): " + mpitohex(mpi[0]) + "\n" + indent + tab + "ELGAMAL g (" + std::to_string(bitsize(mpi[1])) + " bits): " + mpitohex(mpi[1]) + "\n" + indent + tab + "ELGAMAL y (" + std::to_string(bitsize(mpi[2])) + " bits): " + mpitohex(mpi[2]); } else if (pka == PKA::ID::DSA){ out += indent + tab + "DSA p (" + std::to_string(bitsize(mpi[0])) + " bits): " + mpitohex(mpi[0]) + "\n" + indent + tab + "DSA q (" + std::to_string(bitsize(mpi[1])) + " bits): " + mpitohex(mpi[1]) + "\n" + indent + tab + "DSA g (" + std::to_string(bitsize(mpi[2])) + " bits): " + mpitohex(mpi[2]) + "\n" + indent + tab + "DSA y (" + std::to_string(bitsize(mpi[3])) + " bits): " + mpitohex(mpi[3]); } } return out; } std::string Key::raw_common() const{ std::string out = std::string(1, version) + unhexlify(makehex(time, 8)); if (version < 4){ // to recreate older keys out += unhexlify(makehex(expire, 4)); } out += std::string(1, pka); for(MPI const m : mpi){ out += write_MPI(m); } return out; } uint32_t Key::get_time() const{ return time; } uint32_t Key::get_exp_time() const { if (version < 4){ return expire; }else{ throw std::runtime_error("Expiration time is defined only for version 3"); } } uint8_t Key::get_pka() const{ return pka; } PKA::Values Key::get_mpi() const{ return mpi; } void Key::set_time(uint32_t t){ time = t; } void Key::set_pka(uint8_t p){ pka = p; } void Key::set_mpi(const PKA::Values & m){ mpi = m; size = raw().size(); } std::string Key::get_fingerprint() const{ if (version == 3 || version == 2){ std::string data = ""; for(MPI const & i : mpi){ std::string m = write_MPI(i); data += m.substr(2, m.size() - 2); } return MD5(data).digest(); } else if (version == 4){ std::string packet = raw_common(); return SHA1("\x99" + unhexlify(makehex(packet.size(), 4)) + packet).digest(); } else{ throw std::runtime_error("Error: Key packet version " + std::to_string(version) + " not defined."); } return ""; // should never reach here; mainly just to remove compiler warnings } std::string Key::get_keyid() const{ if (version == 3 || version == 2){ std::string data = write_MPI(mpi[0]); return data.substr(data.size() - 8, 8); } else if (version == 4){ return get_fingerprint().substr(12, 8); } else{ throw std::runtime_error("Error: Key packet version " + std::to_string(version) + " not defined."); } return ""; // should never reach here; mainly just to remove compiler warnings } Tag::Ptr Key::clone() const{ return std::make_shared <Key> (*this); } Key & Key::operator=(const Key & copy) { Tag::operator=(copy); time = copy.time; pka = copy.pka; mpi = copy.mpi; expire = copy.expire; return *this; } } } <commit_msg>small changes<commit_after>#include "Key.h" namespace OpenPGP { namespace Packet { Key::Key(uint8_t tag) : Tag(tag), time(), pka(), mpi(), expire() {} Key::Key() : Key(0) {} Key::Key(const Key & copy) : Tag(copy), time(copy.time), pka(copy.pka), mpi(copy.mpi), expire(copy.expire) {} Key::Key(const std::string & data) : Key() { read(data); } Key::~Key(){} void Key::read(const std::string & data){ std::string::size_type pos = 0; read_common(data, pos); } std::string Key::show(const std::size_t indents, const std::size_t indent_size) const{ const std::string tab(indents * indent_size, ' '); return tab + show_title() + "\n" + show_common(indents, indent_size); } std::string Key::raw() const{ return raw_common(); } void Key::read_common(const std::string & data, std::string::size_type & pos){ size = data.size(); version = data[pos]; time = toint(data.substr(pos + 1, 4), 256); if (version < 4){ expire = (data[pos + 5] << 8) + data[pos + 6]; pka = data[pos + 7]; pos += 8; mpi.push_back(read_MPI(data, pos)); // RSA n mpi.push_back(read_MPI(data, pos)); // RSA e } else if (version == 4){ pka = data[pos + 5]; pos += 6; // at minimum RSA mpi.push_back(read_MPI(data, pos)); // RSA n, DSA p, ELGAMAL p mpi.push_back(read_MPI(data, pos)); // RSA e, DSA q, ELGAMAL g // DSA if (pka == PKA::ID::DSA){ mpi.push_back(read_MPI(data, pos)); // DSA g mpi.push_back(read_MPI(data, pos)); // DSA y } // ELGAMAL else if (pka == PKA::ID::ELGAMAL){ mpi.push_back(read_MPI(data, pos)); // ELGAMAL y } } } std::string Key::show_common(const std::size_t indents, const std::size_t indent_size) const{ const std::string indent(indents * indent_size, ' '); const std::string tab(indent_size, ' '); std::string out = indent + tab + "Version: " + std::to_string(version) + " - " + ((version < 4)?"Old":"New") + "\n" + indent + tab + "Creation Time: " + show_time(time) + "\n"; if (version < 4){ out += indent + tab + "Expiration Time (Days): " + std::to_string(expire) + "\n"; if (!expire){ out += " (Never)\n"; } out += indent + tab + "Public Key Algorithm: " + PKA::NAME.at(pka) + " (pka " + std::to_string(pka) + ")\n" + indent + tab + "RSA n: " + mpitohex(mpi[0]) + "(" + std::to_string(bitsize(mpi[0])) + " bits)\n" + indent + tab + "RSA e: " + mpitohex(mpi[1]); } else if (version == 4){ out += indent + tab + "Public Key Algorithm: " + PKA::NAME.at(pka) + " (pka " + std::to_string(pka) + ")\n"; if (PKA::is_RSA(pka)){ out += indent + tab + "RSA n (" + std::to_string(bitsize(mpi[0])) + " bits): " + mpitohex(mpi[0]) + "\n" + indent + tab + "RSA e (" + std::to_string(bitsize(mpi[1])) + " bits): " + mpitohex(mpi[1]); } else if (pka == PKA::ID::ELGAMAL){ out += indent + tab + "ELGAMAL p (" + std::to_string(bitsize(mpi[0])) + " bits): " + mpitohex(mpi[0]) + "\n" + indent + tab + "ELGAMAL g (" + std::to_string(bitsize(mpi[1])) + " bits): " + mpitohex(mpi[1]) + "\n" + indent + tab + "ELGAMAL y (" + std::to_string(bitsize(mpi[2])) + " bits): " + mpitohex(mpi[2]); } else if (pka == PKA::ID::DSA){ out += indent + tab + "DSA p (" + std::to_string(bitsize(mpi[0])) + " bits): " + mpitohex(mpi[0]) + "\n" + indent + tab + "DSA q (" + std::to_string(bitsize(mpi[1])) + " bits): " + mpitohex(mpi[1]) + "\n" + indent + tab + "DSA g (" + std::to_string(bitsize(mpi[2])) + " bits): " + mpitohex(mpi[2]) + "\n" + indent + tab + "DSA y (" + std::to_string(bitsize(mpi[3])) + " bits): " + mpitohex(mpi[3]); } } return out; } std::string Key::raw_common() const{ std::string out = std::string(1, version) + unhexlify(makehex(time, 8)); if (version < 4){ // to recreate older keys out += unhexlify(makehex(expire, 4)); } out += std::string(1, pka); for(MPI const m : mpi){ out += write_MPI(m); } return out; } uint32_t Key::get_time() const{ return time; } uint32_t Key::get_exp_time() const { if (version < 4){ return expire; }else{ throw std::runtime_error("Expiration time is defined only for version 3"); } } uint8_t Key::get_pka() const{ return pka; } PKA::Values Key::get_mpi() const{ return mpi; } void Key::set_time(uint32_t t){ time = t; } void Key::set_pka(uint8_t p){ pka = p; } void Key::set_mpi(const PKA::Values & m){ mpi = m; size = raw().size(); } std::string Key::get_fingerprint() const{ if (version == 3){ std::string data = ""; for(MPI const & i : mpi){ std::string m = write_MPI(i); data += m.substr(2, m.size() - 2); } return MD5(data).digest(); } else if (version == 4){ std::string packet = raw_common(); return SHA1("\x99" + unhexlify(makehex(packet.size(), 4)) + packet).digest(); } else{ throw std::runtime_error("Error: Key packet version " + std::to_string(version) + " not defined."); } return ""; // should never reach here; mainly just to remove compiler warnings } std::string Key::get_keyid() const{ if (version == 3){ std::string data = write_MPI(mpi[0]); return data.substr(data.size() - 8, 8); } else if (version == 4){ return get_fingerprint().substr(12, 8); } else{ throw std::runtime_error("Error: Key packet version " + std::to_string(version) + " not defined."); } return ""; // should never reach here; mainly just to remove compiler warnings } Tag::Ptr Key::clone() const{ return std::make_shared <Key> (*this); } Key & Key::operator=(const Key & copy) { Tag::operator=(copy); time = copy.time; pka = copy.pka; mpi = copy.mpi; expire = copy.expire; return *this; } } } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: XMLIndexBibliographyEntryContext.cxx,v $ * * $Revision: 1.7 $ * * last change: $Author: dvo $ $Date: 2002-01-18 11:08:29 $ * * 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 _XMLOFF_XMLINDEXBIBLIOGRAPHYENTRYCONTEXT_HXX_ #include "XMLIndexBibliographyEntryContext.hxx" #endif #ifndef _XMLOFF_XMLINDEXTEMPLATECONTEXT_HXX_ #include "XMLIndexTemplateContext.hxx" #endif #ifndef _XMLOFF_XMLICTXT_HXX #include "xmlictxt.hxx" #endif #ifndef _XMLOFF_XMLIMP_HXX #include "xmlimp.hxx" #endif #ifndef _XMLOFF_TEXTIMP_HXX_ #include "txtimp.hxx" #endif #ifndef _XMLOFF_NMSPMAP_HXX #include "nmspmap.hxx" #endif #ifndef _XMLOFF_XMLNMSPE_HXX #include "xmlnmspe.hxx" #endif #ifndef _XMLOFF_XMLTOKEN_HXX #include "xmltoken.hxx" #endif #ifndef _XMLOFF_XMLUCONV_HXX #include "xmluconv.hxx" #endif #ifndef _COM_SUN_STAR_TEXT_BIBLIOGRAPHYDATAFIELD_HPP_ #include <com/sun/star/text/BibliographyDataField.hpp> #endif using namespace ::com::sun::star::text; using namespace ::xmloff::token; using ::rtl::OUString; using ::com::sun::star::beans::PropertyValue; using ::com::sun::star::beans::PropertyValues; using ::com::sun::star::uno::Reference; using ::com::sun::star::uno::Sequence; using ::com::sun::star::uno::Any; using ::com::sun::star::xml::sax::XAttributeList; const sal_Char sAPI_TokenType[] = "TokenType"; const sal_Char sAPI_CharacterStyleName[] = "CharacterStyleName"; TYPEINIT1( XMLIndexBibliographyEntryContext, XMLIndexSimpleEntryContext); XMLIndexBibliographyEntryContext::XMLIndexBibliographyEntryContext( SvXMLImport& rImport, XMLIndexTemplateContext& rTemplate, sal_uInt16 nPrfx, const OUString& rLocalName ) : XMLIndexSimpleEntryContext(rImport, rTemplate.sTokenBibliographyDataField, rTemplate, nPrfx, rLocalName), nBibliographyInfo(BibliographyDataField::IDENTIFIER), bBibliographyInfoOK(sal_False) { } XMLIndexBibliographyEntryContext::~XMLIndexBibliographyEntryContext() { } const SvXMLEnumMapEntry aBibliographyDataFieldMap[] = { { XML_ADDRESS, BibliographyDataField::ADDRESS }, { XML_ANNOTE, BibliographyDataField::ANNOTE }, { XML_AUTHOR, BibliographyDataField::AUTHOR }, { XML_BIBLIOGRAPHY_TYPE, BibliographyDataField::BIBILIOGRAPHIC_TYPE }, // #96658#: also read old documents (bib*i*liographic...) { XML_BIBILIOGRAPHIC_TYPE, BibliographyDataField::BIBILIOGRAPHIC_TYPE }, { XML_BOOKTITLE, BibliographyDataField::BOOKTITLE }, { XML_CHAPTER, BibliographyDataField::CHAPTER }, { XML_CUSTOM1, BibliographyDataField::CUSTOM1 }, { XML_CUSTOM2, BibliographyDataField::CUSTOM2 }, { XML_CUSTOM3, BibliographyDataField::CUSTOM3 }, { XML_CUSTOM4, BibliographyDataField::CUSTOM4 }, { XML_CUSTOM5, BibliographyDataField::CUSTOM5 }, { XML_EDITION, BibliographyDataField::EDITION }, { XML_EDITOR, BibliographyDataField::EDITOR }, { XML_HOWPUBLISHED, BibliographyDataField::HOWPUBLISHED }, { XML_IDENTIFIER, BibliographyDataField::IDENTIFIER }, { XML_INSTITUTION, BibliographyDataField::INSTITUTION }, { XML_ISBN, BibliographyDataField::ISBN }, { XML_JOURNAL, BibliographyDataField::JOURNAL }, { XML_MONTH, BibliographyDataField::MONTH }, { XML_NOTE, BibliographyDataField::NOTE }, { XML_NUMBER, BibliographyDataField::NUMBER }, { XML_ORGANIZATIONS, BibliographyDataField::ORGANIZATIONS }, { XML_PAGES, BibliographyDataField::PAGES }, { XML_PUBLISHER, BibliographyDataField::PUBLISHER }, { XML_REPORT_TYPE, BibliographyDataField::REPORT_TYPE }, { XML_SCHOOL, BibliographyDataField::SCHOOL }, { XML_SERIES, BibliographyDataField::SERIES }, { XML_TITLE, BibliographyDataField::TITLE }, { XML_URL, BibliographyDataField::URL }, { XML_VOLUME, BibliographyDataField::VOLUME }, { XML_YEAR, BibliographyDataField::YEAR }, { XML_TOKEN_INVALID, 0 } }; void XMLIndexBibliographyEntryContext::StartElement( const Reference<XAttributeList> & xAttrList) { // handle both, style name and bibliography info sal_Int16 nLength = xAttrList->getLength(); for(sal_Int16 nAttr = 0; nAttr < nLength; nAttr++) { OUString sLocalName; sal_uInt16 nPrefix = GetImport().GetNamespaceMap(). GetKeyByAttrName( xAttrList->getNameByIndex(nAttr), &sLocalName ); if (XML_NAMESPACE_TEXT == nPrefix) { if ( IsXMLToken( sLocalName, XML_STYLE_NAME ) ) { sCharStyleName = xAttrList->getValueByIndex(nAttr); bCharStyleNameOK = sal_True; } else if ( IsXMLToken( sLocalName, XML_BIBLIOGRAPHY_DATA_FIELD ) ) { sal_uInt16 nTmp; if (SvXMLUnitConverter::convertEnum( nTmp, xAttrList->getValueByIndex(nAttr), aBibliographyDataFieldMap)) { nBibliographyInfo = nTmp; bBibliographyInfoOK = sal_True; } } } } // if we have a style name, set it! if (bCharStyleNameOK) { nValues++; } // always bibliography; else element is not valid nValues++; } void XMLIndexBibliographyEntryContext::EndElement() { // only valid, if we have bibliography info if (bBibliographyInfoOK) { XMLIndexSimpleEntryContext::EndElement(); } } void XMLIndexBibliographyEntryContext::FillPropertyValues( ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue> & rValues) { // entry name and (optionally) style name in parent class XMLIndexSimpleEntryContext::FillPropertyValues(rValues); // bibliography data field sal_Int32 nIndex = bCharStyleNameOK ? 2 : 1; rValues[nIndex].Name = rTemplateContext.sBibliographyDataField; Any aAny; aAny <<= nBibliographyInfo; rValues[nIndex].Value = aAny; } <commit_msg>INTEGRATION: CWS ooo19126 (1.7.620); FILE MERGED 2005/09/05 14:39:48 rt 1.7.620.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: XMLIndexBibliographyEntryContext.cxx,v $ * * $Revision: 1.8 $ * * last change: $Author: rt $ $Date: 2005-09-09 15:03:25 $ * * 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 _XMLOFF_XMLINDEXBIBLIOGRAPHYENTRYCONTEXT_HXX_ #include "XMLIndexBibliographyEntryContext.hxx" #endif #ifndef _XMLOFF_XMLINDEXTEMPLATECONTEXT_HXX_ #include "XMLIndexTemplateContext.hxx" #endif #ifndef _XMLOFF_XMLICTXT_HXX #include "xmlictxt.hxx" #endif #ifndef _XMLOFF_XMLIMP_HXX #include "xmlimp.hxx" #endif #ifndef _XMLOFF_TEXTIMP_HXX_ #include "txtimp.hxx" #endif #ifndef _XMLOFF_NMSPMAP_HXX #include "nmspmap.hxx" #endif #ifndef _XMLOFF_XMLNMSPE_HXX #include "xmlnmspe.hxx" #endif #ifndef _XMLOFF_XMLTOKEN_HXX #include "xmltoken.hxx" #endif #ifndef _XMLOFF_XMLUCONV_HXX #include "xmluconv.hxx" #endif #ifndef _COM_SUN_STAR_TEXT_BIBLIOGRAPHYDATAFIELD_HPP_ #include <com/sun/star/text/BibliographyDataField.hpp> #endif using namespace ::com::sun::star::text; using namespace ::xmloff::token; using ::rtl::OUString; using ::com::sun::star::beans::PropertyValue; using ::com::sun::star::beans::PropertyValues; using ::com::sun::star::uno::Reference; using ::com::sun::star::uno::Sequence; using ::com::sun::star::uno::Any; using ::com::sun::star::xml::sax::XAttributeList; const sal_Char sAPI_TokenType[] = "TokenType"; const sal_Char sAPI_CharacterStyleName[] = "CharacterStyleName"; TYPEINIT1( XMLIndexBibliographyEntryContext, XMLIndexSimpleEntryContext); XMLIndexBibliographyEntryContext::XMLIndexBibliographyEntryContext( SvXMLImport& rImport, XMLIndexTemplateContext& rTemplate, sal_uInt16 nPrfx, const OUString& rLocalName ) : XMLIndexSimpleEntryContext(rImport, rTemplate.sTokenBibliographyDataField, rTemplate, nPrfx, rLocalName), nBibliographyInfo(BibliographyDataField::IDENTIFIER), bBibliographyInfoOK(sal_False) { } XMLIndexBibliographyEntryContext::~XMLIndexBibliographyEntryContext() { } const SvXMLEnumMapEntry aBibliographyDataFieldMap[] = { { XML_ADDRESS, BibliographyDataField::ADDRESS }, { XML_ANNOTE, BibliographyDataField::ANNOTE }, { XML_AUTHOR, BibliographyDataField::AUTHOR }, { XML_BIBLIOGRAPHY_TYPE, BibliographyDataField::BIBILIOGRAPHIC_TYPE }, // #96658#: also read old documents (bib*i*liographic...) { XML_BIBILIOGRAPHIC_TYPE, BibliographyDataField::BIBILIOGRAPHIC_TYPE }, { XML_BOOKTITLE, BibliographyDataField::BOOKTITLE }, { XML_CHAPTER, BibliographyDataField::CHAPTER }, { XML_CUSTOM1, BibliographyDataField::CUSTOM1 }, { XML_CUSTOM2, BibliographyDataField::CUSTOM2 }, { XML_CUSTOM3, BibliographyDataField::CUSTOM3 }, { XML_CUSTOM4, BibliographyDataField::CUSTOM4 }, { XML_CUSTOM5, BibliographyDataField::CUSTOM5 }, { XML_EDITION, BibliographyDataField::EDITION }, { XML_EDITOR, BibliographyDataField::EDITOR }, { XML_HOWPUBLISHED, BibliographyDataField::HOWPUBLISHED }, { XML_IDENTIFIER, BibliographyDataField::IDENTIFIER }, { XML_INSTITUTION, BibliographyDataField::INSTITUTION }, { XML_ISBN, BibliographyDataField::ISBN }, { XML_JOURNAL, BibliographyDataField::JOURNAL }, { XML_MONTH, BibliographyDataField::MONTH }, { XML_NOTE, BibliographyDataField::NOTE }, { XML_NUMBER, BibliographyDataField::NUMBER }, { XML_ORGANIZATIONS, BibliographyDataField::ORGANIZATIONS }, { XML_PAGES, BibliographyDataField::PAGES }, { XML_PUBLISHER, BibliographyDataField::PUBLISHER }, { XML_REPORT_TYPE, BibliographyDataField::REPORT_TYPE }, { XML_SCHOOL, BibliographyDataField::SCHOOL }, { XML_SERIES, BibliographyDataField::SERIES }, { XML_TITLE, BibliographyDataField::TITLE }, { XML_URL, BibliographyDataField::URL }, { XML_VOLUME, BibliographyDataField::VOLUME }, { XML_YEAR, BibliographyDataField::YEAR }, { XML_TOKEN_INVALID, 0 } }; void XMLIndexBibliographyEntryContext::StartElement( const Reference<XAttributeList> & xAttrList) { // handle both, style name and bibliography info sal_Int16 nLength = xAttrList->getLength(); for(sal_Int16 nAttr = 0; nAttr < nLength; nAttr++) { OUString sLocalName; sal_uInt16 nPrefix = GetImport().GetNamespaceMap(). GetKeyByAttrName( xAttrList->getNameByIndex(nAttr), &sLocalName ); if (XML_NAMESPACE_TEXT == nPrefix) { if ( IsXMLToken( sLocalName, XML_STYLE_NAME ) ) { sCharStyleName = xAttrList->getValueByIndex(nAttr); bCharStyleNameOK = sal_True; } else if ( IsXMLToken( sLocalName, XML_BIBLIOGRAPHY_DATA_FIELD ) ) { sal_uInt16 nTmp; if (SvXMLUnitConverter::convertEnum( nTmp, xAttrList->getValueByIndex(nAttr), aBibliographyDataFieldMap)) { nBibliographyInfo = nTmp; bBibliographyInfoOK = sal_True; } } } } // if we have a style name, set it! if (bCharStyleNameOK) { nValues++; } // always bibliography; else element is not valid nValues++; } void XMLIndexBibliographyEntryContext::EndElement() { // only valid, if we have bibliography info if (bBibliographyInfoOK) { XMLIndexSimpleEntryContext::EndElement(); } } void XMLIndexBibliographyEntryContext::FillPropertyValues( ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue> & rValues) { // entry name and (optionally) style name in parent class XMLIndexSimpleEntryContext::FillPropertyValues(rValues); // bibliography data field sal_Int32 nIndex = bCharStyleNameOK ? 2 : 1; rValues[nIndex].Name = rTemplateContext.sBibliographyDataField; Any aAny; aAny <<= nBibliographyInfo; rValues[nIndex].Value = aAny; } <|endoftext|>
<commit_before>// -*- c++ -*- // $Id$ #include "unittest.hxx" #include "vigra/multi_array.hxx" #include "vigra/multi_pointoperators.hxx" #include "vigra/multi_convolution.hxx" #include "vigra/basicimageview.hxx" #include "vigra/convolution.hxx" #include "vigra/navigator.hxx" #include "vigra/functorexpression.hxx" using namespace vigra; using namespace vigra::functor; struct MultiArrayPointoperatorsTest { typedef float PixelType; typedef MultiArray<3,PixelType> Image3D; typedef Image3D::difference_type Size3; Image3D img; MultiArrayPointoperatorsTest() : img(Size3(5,4,3)) { unsigned int i; PixelType c = 0.1; for(i=0; i<img.elementCount(); ++i, ++c) img.data()[i] = c; } void testInit() { Image3D res(img.shape()); const Image3D::value_type ini = 1.1; should(res.shape() == Size3(5,4,3)); initMultiArray(destMultiArrayRange(res), ini); int x,y,z; for(z=0; z<img.shape(2); ++z) for(y=0; y<img.shape(1); ++y) for(x=0; x<img.shape(0); ++x) shouldEqual(res(x,y,z), ini); } void testCopy() { Image3D res(img.shape()); initMultiArray(destMultiArrayRange(res), 0.0); copyMultiArray(srcMultiArrayRange(img), destMultiArray(res)); int x,y,z; for(z=0; z<img.shape(2); ++z) for(y=0; y<img.shape(1); ++y) for(x=0; x<img.shape(0); ++x) shouldEqual(res(x,y,z), img(x,y,z)); } void testTransform() { Image3D res(img.shape()); initMultiArray(destMultiArrayRange(res), 0.0); transformMultiArray(srcMultiArrayRange(img), destMultiArray(res), Arg1() + Arg1()); int x,y,z; for(z=0; z<img.shape(2); ++z) for(y=0; y<img.shape(1); ++y) for(x=0; x<img.shape(0); ++x) shouldEqual(res(x,y,z), 2.0*img(x,y,z)); } void testCombine2() { Image3D res(img.shape()); initMultiArray(destMultiArrayRange(res), 0.0); combineTwoMultiArrays(srcMultiArrayRange(img), srcMultiArray(img), destMultiArray(res), Arg1() + Arg2()); int x,y,z; for(z=0; z<img.shape(2); ++z) for(y=0; y<img.shape(1); ++y) for(x=0; x<img.shape(0); ++x) shouldEqual(res(x,y,z), 2.0*img(x,y,z)); } void testCombine3() { Image3D res(img.shape()); initMultiArray(destMultiArrayRange(res), 0.0); combineThreeMultiArrays(srcMultiArrayRange(img), srcMultiArray(img), srcMultiArray(img), destMultiArray(res), Arg1() + Arg2() + Arg3()); int x,y,z; for(z=0; z<img.shape(2); ++z) for(y=0; y<img.shape(1); ++y) for(x=0; x<img.shape(0); ++x) shouldEqual(res(x,y,z), 3.0*img(x,y,z)); } }; struct MultiArraySeparableConvolutionTest { typedef float PixelType; typedef TinyVector<PixelType,3> VectorPixelType; typedef MultiArray<3, VectorPixelType> Image3x3; typedef MultiArray<3,PixelType> Image3D; typedef Image3D::difference_type Size3; typedef BasicImage<PixelType> Image2D; typedef Image2D::difference_type Size2; // - - - - - - - - - - - - - - - - - - - - - - - - void makeWedge( Image3D &image ) { const Size3 size = image.shape(); const int width = size[0]; const int height = size[1]; const int depth = size[2]; for( int z = 0; z < depth; ++z ) { for( int y = 0; y < height; ++y ) { for( int x = 0; x < width; ++x ) { const Image3D::value_type val = x + y + z; image( x, y, z ) = val; } } } } void makeBox( Image3D &image ) { const int b = 8; const Size3 size = image.shape(); const int width = size[0]; const int height = size[1]; const int depth = size[2]; for( int z = 0; z < depth; ++z ) { for( int y = 0; y < height; ++y ) { for( int x = 0; x < width; ++x ) { Image3D::value_type val = 80; if( (x > b) && x < (width-b) && (y > b) && y < (height-b) && (z > b) && z < (depth-b) ) { val = 220; } image( x, y, z ) = val; } } } } // - - - - - - - - - - - - - - - - - - - - - - - - void test_1DValidity( const Image3D &src, float ksize ) { Image3D d1( src.size() ); Image3D dn( src.size() ); Image3D dest3( src.size() ); int depth = src.size()[2]; for( int d = 0; d < 3; ++d ) { std::vector<vigra::Kernel1D<float> > kernels( 3 ); kernels[d].initGaussianDerivative( ksize, 1 ); separableConvolveMultiArray( srcMultiArrayRange(src), destMultiArray(dn), kernels.begin() ); separableConvolveMultiArray( srcMultiArrayRange(src), destMultiArray(d1), d, kernels[d] ); shouldEqualSequence( dn.begin(), dn.end(), d1.begin() ); } } // - - - - - - - - - - - - - - - - - - - - - - - - void test_1DValidityB( const Image3D &src, float ksize ) { Image3D dst1( src.size() ); Image3D dst2( src.size() ); const int depth = src.size()[2]; vigra::Kernel1D<float> kernx; vigra::Kernel1D<float> kerny; kernx.initGaussian( ksize ); kerny.initGaussianDerivative( ksize, 1 ); int z; // x convolution separableConvolveMultiArray( srcMultiArrayRange(src), destMultiArray(dst1), 0, kernx ); for( z = 0; z < depth; ++z ) { BasicImageView<Image3D::value_type> sslice = makeBasicImageView( src.bindOuter(z) ); BasicImageView<Image3D::value_type> dslice = makeBasicImageView( dst2.bindOuter(z) ); vigra::separableConvolveX( srcImageRange(sslice), destImage(dslice), vigra::kernel1d(kernx) ); } shouldEqualSequence( dst1.begin(), dst1.end(), dst2.begin() ); // y convolution separableConvolveMultiArray( srcMultiArrayRange(src), destMultiArray(dst1), 1, kerny ); for( z = 0; z < depth; ++z ) { BasicImageView<Image3D::value_type> sslice = makeBasicImageView( src.bindOuter(z) ); BasicImageView<Image3D::value_type> dslice = makeBasicImageView( dst2.bindOuter(z) ); vigra::separableConvolveY( srcImageRange(sslice), destImage(dslice), vigra::kernel1d(kerny) ); } shouldEqualSequence( dst1.begin(), dst1.end(), dst2.begin() ); } void test_2DValidity( const Image3D &src, float ksize ) { Image3D d2( src.size() ); Image3D dn( src.size() ); int depth = src.size()[2]; std::vector<vigra::Kernel1D<float> > kernels( 3 ); kernels[0].initGaussian( ksize ); kernels[1].initGaussianDerivative( ksize, 1 ); for( int z = 0; z < depth; ++z ) { BasicImageView<Image3D::value_type> sslice = makeBasicImageView( src.bindOuter(z) ); BasicImageView<Image3D::value_type> dslice = makeBasicImageView( d2.bindOuter(z) ); vigra::convolveImage( srcImageRange(sslice), destImage(dslice), kernels[0], kernels[1] ); } separableConvolveMultiArray( srcMultiArrayRange(src), destMultiArray(dn), kernels.begin() ); shouldEqualSequence( dn.begin(), dn.end(), d2.begin() ); } // - - - - - - - - - - - - - - - - - - - - - - - - void test_inplacenessN( const Image3D &src, float ksize ) { Image3D da( src.size() ); Image3D db( src.size() ); std::vector<vigra::Kernel1D<float> > kernels( 3 ); kernels[0].initGaussian( ksize ); kernels[1].initGaussianDerivative( ksize, 1 ); vigra::separableConvolveMultiArray( srcMultiArrayRange(src), destMultiArray(da), kernels.begin() ); copyMultiArray(srcMultiArrayRange(src), destMultiArray(db)); vigra::separableConvolveMultiArray( srcMultiArrayRange(db), destMultiArray(db), kernels.begin() ); shouldEqualSequenceTolerance( da.begin(), da.end(), db.begin(), 1e-5 ); } // - - - - - - - - - - - - - - - - - - - - - - - - void test_inplaceness1( const Image3D &src, float ksize, bool useDerivative ) { Image3D da( src.size() ); Image3D db( src.size() ); Kernel1D<float> kernel; if( ! useDerivative ) kernel.initGaussian( ksize ); else kernel.initGaussianDerivative( ksize, 1 ); for( int i = 0; i < 3; ++i ) { const int d = 2-i; vigra::separableConvolveMultiArray( srcMultiArrayRange(src), destMultiArray(da), d, kernel ); copyMultiArray(srcMultiArrayRange(src), destMultiArray(db)); vigra::separableConvolveMultiArray( srcMultiArrayRange(db), destMultiArray(db), d, kernel ); shouldEqualSequence( da.begin(), da.end(), db.begin() ); } } // - - - - - - - - - - - - - - - - - - - - - - - - void test_gradient1( const Image3D &base, bool useGaussian ) { const double sigma = kernelSize/2; const int b = useGaussian ? int( 0.5 + 3*sigma ) : 1; Image3D src( base.size() ); Image3x3 grad( src.size() ); makeWedge( src ); if( ! useGaussian ) symmetricGradientMultiArray( srcMultiArrayRange(src), destMultiArray(grad) ); else gaussianGradientMultiArray( srcMultiArrayRange(src), destMultiArray(grad), sigma ); Image3x3::value_type v; v[0] = 1; v[1] = 1; v[2] = 1; const float v2 = dot(v,v); const Size3 size = src.shape(); const int width = size[0]; const int height = size[1]; const int depth = size[2]; for( int z = b; z < depth-b; ++z ) { for( int y = b; y < height-b; ++y ) { for( int x = b; x < width-b; ++x ) { shouldEqualTolerance( dot(grad(x,y,z), v), v2, 1e-5 ); } } } } void test_gradient_magnitude( const Image3D &src ) { // just a test for mere compileability Image3D dst( src.size() ); Image3x3 grad( src.size() ); symmetricGradientMultiArray( srcMultiArrayRange(src), destMultiArray(grad) ); transformMultiArray( srcMultiArrayRange(grad), destMultiArray(dst), VectorNormFunctor<Image3x3::value_type>() ); } //-------------------------------------------- const Size3 size; Image3D srcImage; const float kernelSize; MultiArraySeparableConvolutionTest() : size( 60, 70, 50 ), srcImage( size ), kernelSize( 1.8 ) { makeBox( srcImage ); } void test_Valid1() { test_1DValidity( srcImage, kernelSize ); } void test_Valid3() { test_1DValidityB( srcImage, kernelSize ); } void test_Valid2() { test_2DValidity( srcImage, kernelSize ); } void test_InplaceN() { test_inplacenessN( srcImage, kernelSize ); } void test_Inplace1() { test_inplaceness1( srcImage, kernelSize, false ); test_inplaceness1( srcImage, kernelSize, true ); } void test_gradient1() { test_gradient1( srcImage, false ); test_gradient1( srcImage, true ); } void test_gradient_magnitude() { test_gradient_magnitude( srcImage ); } }; //-- struct MultiArraySeparableConvolutionTest //-------------------------------------------------------- struct MultiArraySeparableConvolutionTestSuite : public vigra::test_suite { MultiArraySeparableConvolutionTestSuite() : vigra::test_suite("MultiArraySeparableConvolutionTestSuite") { // add( testCase( &MultiArrayTest::test_default_ctor ) ); add( testCase( &MultiArrayPointoperatorsTest::testInit ) ); add( testCase( &MultiArrayPointoperatorsTest::testCopy ) ); add( testCase( &MultiArrayPointoperatorsTest::testTransform ) ); add( testCase( &MultiArrayPointoperatorsTest::testCombine2 ) ); add( testCase( &MultiArrayPointoperatorsTest::testCombine3 ) ); add( testCase( &MultiArraySeparableConvolutionTest::test_Valid1 ) ); add( testCase( &MultiArraySeparableConvolutionTest::test_Valid2 ) ); add( testCase( &MultiArraySeparableConvolutionTest::test_Valid3 ) ); add( testCase( &MultiArraySeparableConvolutionTest::test_InplaceN ) ); add( testCase( &MultiArraySeparableConvolutionTest::test_Inplace1 ) ); add( testCase( &MultiArraySeparableConvolutionTest::test_gradient1 ) ); add( testCase( &MultiArraySeparableConvolutionTest::test_gradient_magnitude ) ); } }; // struct MultiArraySeparableConvolutionTestSuite //-------------------------------------------------------- int main() { // run the multi-array separable convolutiontestsuite MultiArraySeparableConvolutionTestSuite test1; int failed = test1.run(); std::cout << test1.report() << std::endl; return (failed != 0); } <commit_msg>adaptation after refactoring of multi_convolution.hxx<commit_after>// -*- c++ -*- // $Id$ #include "unittest.hxx" #include "vigra/multi_array.hxx" #include "vigra/multi_pointoperators.hxx" #include "vigra/multi_convolution.hxx" #include "vigra/basicimageview.hxx" #include "vigra/convolution.hxx" #include "vigra/navigator.hxx" #include "vigra/functorexpression.hxx" using namespace vigra; using namespace vigra::functor; struct MultiArrayPointoperatorsTest { typedef float PixelType; typedef MultiArray<3,PixelType> Image3D; typedef Image3D::difference_type Size3; Image3D img; MultiArrayPointoperatorsTest() : img(Size3(5,4,3)) { unsigned int i; PixelType c = 0.1; for(i=0; i<img.elementCount(); ++i, ++c) img.data()[i] = c; } void testInit() { Image3D res(img.shape()); const Image3D::value_type ini = 1.1; should(res.shape() == Size3(5,4,3)); initMultiArray(destMultiArrayRange(res), ini); int x,y,z; for(z=0; z<img.shape(2); ++z) for(y=0; y<img.shape(1); ++y) for(x=0; x<img.shape(0); ++x) shouldEqual(res(x,y,z), ini); } void testCopy() { Image3D res(img.shape()); initMultiArray(destMultiArrayRange(res), 0.0); copyMultiArray(srcMultiArrayRange(img), destMultiArray(res)); int x,y,z; for(z=0; z<img.shape(2); ++z) for(y=0; y<img.shape(1); ++y) for(x=0; x<img.shape(0); ++x) shouldEqual(res(x,y,z), img(x,y,z)); } void testTransform() { Image3D res(img.shape()); initMultiArray(destMultiArrayRange(res), 0.0); transformMultiArray(srcMultiArrayRange(img), destMultiArray(res), Arg1() + Arg1()); int x,y,z; for(z=0; z<img.shape(2); ++z) for(y=0; y<img.shape(1); ++y) for(x=0; x<img.shape(0); ++x) shouldEqual(res(x,y,z), 2.0*img(x,y,z)); } void testCombine2() { Image3D res(img.shape()); initMultiArray(destMultiArrayRange(res), 0.0); combineTwoMultiArrays(srcMultiArrayRange(img), srcMultiArray(img), destMultiArray(res), Arg1() + Arg2()); int x,y,z; for(z=0; z<img.shape(2); ++z) for(y=0; y<img.shape(1); ++y) for(x=0; x<img.shape(0); ++x) shouldEqual(res(x,y,z), 2.0*img(x,y,z)); } void testCombine3() { Image3D res(img.shape()); initMultiArray(destMultiArrayRange(res), 0.0); combineThreeMultiArrays(srcMultiArrayRange(img), srcMultiArray(img), srcMultiArray(img), destMultiArray(res), Arg1() + Arg2() + Arg3()); int x,y,z; for(z=0; z<img.shape(2); ++z) for(y=0; y<img.shape(1); ++y) for(x=0; x<img.shape(0); ++x) shouldEqual(res(x,y,z), 3.0*img(x,y,z)); } }; struct MultiArraySeparableConvolutionTest { typedef float PixelType; typedef TinyVector<PixelType,3> VectorPixelType; typedef MultiArray<3, VectorPixelType> Image3x3; typedef MultiArray<3,PixelType> Image3D; typedef Image3D::difference_type Size3; typedef BasicImage<PixelType> Image2D; typedef Image2D::difference_type Size2; // - - - - - - - - - - - - - - - - - - - - - - - - void makeWedge( Image3D &image ) { const Size3 size = image.shape(); const int width = size[0]; const int height = size[1]; const int depth = size[2]; for( int z = 0; z < depth; ++z ) { for( int y = 0; y < height; ++y ) { for( int x = 0; x < width; ++x ) { const Image3D::value_type val = x + y + z; image( x, y, z ) = val; } } } } void makeBox( Image3D &image ) { const int b = 8; const Size3 size = image.shape(); const int width = size[0]; const int height = size[1]; const int depth = size[2]; for( int z = 0; z < depth; ++z ) { for( int y = 0; y < height; ++y ) { for( int x = 0; x < width; ++x ) { Image3D::value_type val = 80; if( (x > b) && x < (width-b) && (y > b) && y < (height-b) && (z > b) && z < (depth-b) ) { val = 220; } image( x, y, z ) = val; } } } } // - - - - - - - - - - - - - - - - - - - - - - - - void test_1DValidity( const Image3D &src, float ksize ) { Image3D d1( src.size() ); Image3D dn( src.size() ); Image3D dest3( src.size() ); int depth = src.size()[2]; for( int d = 0; d < 3; ++d ) { std::vector<vigra::Kernel1D<float> > kernels( 3 ); kernels[d].initGaussianDerivative( ksize, 1 ); separableConvolveMultiArray( srcMultiArrayRange(src), destMultiArray(dn), kernels.begin() ); convolveMultiArrayOneDimension( srcMultiArrayRange(src), destMultiArray(d1), d, kernels[d] ); shouldEqualSequence( dn.begin(), dn.end(), d1.begin() ); } } // - - - - - - - - - - - - - - - - - - - - - - - - void test_1DValidityB( const Image3D &src, float ksize ) { Image3D dst1( src.size() ); Image3D dst2( src.size() ); const int depth = src.size()[2]; vigra::Kernel1D<float> kernx; vigra::Kernel1D<float> kerny; kernx.initGaussian( ksize ); kerny.initGaussianDerivative( ksize, 1 ); int z; // x convolution convolveMultiArrayOneDimension( srcMultiArrayRange(src), destMultiArray(dst1), 0, kernx ); for( z = 0; z < depth; ++z ) { BasicImageView<Image3D::value_type> sslice = makeBasicImageView( src.bindOuter(z) ); BasicImageView<Image3D::value_type> dslice = makeBasicImageView( dst2.bindOuter(z) ); vigra::separableConvolveX( srcImageRange(sslice), destImage(dslice), vigra::kernel1d(kernx) ); } shouldEqualSequence( dst1.begin(), dst1.end(), dst2.begin() ); // y convolution convolveMultiArrayOneDimension( srcMultiArrayRange(src), destMultiArray(dst1), 1, kerny ); for( z = 0; z < depth; ++z ) { BasicImageView<Image3D::value_type> sslice = makeBasicImageView( src.bindOuter(z) ); BasicImageView<Image3D::value_type> dslice = makeBasicImageView( dst2.bindOuter(z) ); vigra::separableConvolveY( srcImageRange(sslice), destImage(dslice), vigra::kernel1d(kerny) ); } shouldEqualSequence( dst1.begin(), dst1.end(), dst2.begin() ); } void test_2DValidity( const Image3D &src, float ksize ) { Image3D d2( src.size() ); Image3D dn( src.size() ); int depth = src.size()[2]; std::vector<vigra::Kernel1D<float> > kernels( 3 ); kernels[0].initGaussian( ksize ); kernels[1].initGaussianDerivative( ksize, 1 ); for( int z = 0; z < depth; ++z ) { BasicImageView<Image3D::value_type> sslice = makeBasicImageView( src.bindOuter(z) ); BasicImageView<Image3D::value_type> dslice = makeBasicImageView( d2.bindOuter(z) ); vigra::convolveImage( srcImageRange(sslice), destImage(dslice), kernels[0], kernels[1] ); } separableConvolveMultiArray( srcMultiArrayRange(src), destMultiArray(dn), kernels.begin() ); shouldEqualSequence( dn.begin(), dn.end(), d2.begin() ); } // - - - - - - - - - - - - - - - - - - - - - - - - void test_inplacenessN( const Image3D &src, float ksize ) { Image3D da( src.size() ); Image3D db( src.size() ); std::vector<vigra::Kernel1D<float> > kernels( 3 ); kernels[0].initGaussian( ksize ); kernels[1].initGaussianDerivative( ksize, 1 ); vigra::separableConvolveMultiArray( srcMultiArrayRange(src), destMultiArray(da), kernels.begin() ); copyMultiArray(srcMultiArrayRange(src), destMultiArray(db)); vigra::separableConvolveMultiArray( srcMultiArrayRange(db), destMultiArray(db), kernels.begin() ); shouldEqualSequenceTolerance( da.begin(), da.end(), db.begin(), 1e-5 ); } // - - - - - - - - - - - - - - - - - - - - - - - - void test_inplaceness1( const Image3D &src, float ksize, bool useDerivative ) { Image3D da( src.size() ); Image3D db( src.size() ); Kernel1D<float> kernel; if( ! useDerivative ) kernel.initGaussian( ksize ); else kernel.initGaussianDerivative( ksize, 1 ); for( int i = 0; i < 3; ++i ) { const int d = 2-i; vigra::convolveMultiArrayOneDimension( srcMultiArrayRange(src), destMultiArray(da), d, kernel ); copyMultiArray(srcMultiArrayRange(src), destMultiArray(db)); vigra::convolveMultiArrayOneDimension( srcMultiArrayRange(db), destMultiArray(db), d, kernel ); shouldEqualSequence( da.begin(), da.end(), db.begin() ); } } // - - - - - - - - - - - - - - - - - - - - - - - - void test_gradient1( const Image3D &base, bool useGaussian ) { const double sigma = kernelSize/2; const int b = useGaussian ? int( 0.5 + 3*sigma ) : 1; Image3D src( base.size() ); Image3x3 grad( src.size() ); makeWedge( src ); if( ! useGaussian ) symmetricGradientMultiArray( srcMultiArrayRange(src), destMultiArray(grad) ); else gaussianGradientMultiArray( srcMultiArrayRange(src), destMultiArray(grad), sigma ); Image3x3::value_type v; v[0] = 1; v[1] = 1; v[2] = 1; const float v2 = dot(v,v); const Size3 size = src.shape(); const int width = size[0]; const int height = size[1]; const int depth = size[2]; for( int z = b; z < depth-b; ++z ) { for( int y = b; y < height-b; ++y ) { for( int x = b; x < width-b; ++x ) { shouldEqualTolerance( dot(grad(x,y,z), v), v2, 1e-5 ); } } } } void test_gradient_magnitude( const Image3D &src ) { // just a test for mere compileability Image3D dst( src.size() ); Image3x3 grad( src.size() ); symmetricGradientMultiArray( srcMultiArrayRange(src), destMultiArray(grad) ); transformMultiArray( srcMultiArrayRange(grad), destMultiArray(dst), VectorNormFunctor<Image3x3::value_type>() ); } //-------------------------------------------- const Size3 size; Image3D srcImage; const float kernelSize; MultiArraySeparableConvolutionTest() : size( 60, 70, 50 ), srcImage( size ), kernelSize( 1.8 ) { makeBox( srcImage ); } void test_Valid1() { test_1DValidity( srcImage, kernelSize ); } void test_Valid3() { test_1DValidityB( srcImage, kernelSize ); } void test_Valid2() { test_2DValidity( srcImage, kernelSize ); } void test_InplaceN() { test_inplacenessN( srcImage, kernelSize ); } void test_Inplace1() { test_inplaceness1( srcImage, kernelSize, false ); test_inplaceness1( srcImage, kernelSize, true ); } void test_gradient1() { test_gradient1( srcImage, false ); test_gradient1( srcImage, true ); } void test_gradient_magnitude() { test_gradient_magnitude( srcImage ); } }; //-- struct MultiArraySeparableConvolutionTest //-------------------------------------------------------- struct MultiArraySeparableConvolutionTestSuite : public vigra::test_suite { MultiArraySeparableConvolutionTestSuite() : vigra::test_suite("MultiArraySeparableConvolutionTestSuite") { // add( testCase( &MultiArrayTest::test_default_ctor ) ); add( testCase( &MultiArrayPointoperatorsTest::testInit ) ); add( testCase( &MultiArrayPointoperatorsTest::testCopy ) ); add( testCase( &MultiArrayPointoperatorsTest::testTransform ) ); add( testCase( &MultiArrayPointoperatorsTest::testCombine2 ) ); add( testCase( &MultiArrayPointoperatorsTest::testCombine3 ) ); add( testCase( &MultiArraySeparableConvolutionTest::test_Valid1 ) ); add( testCase( &MultiArraySeparableConvolutionTest::test_Valid2 ) ); add( testCase( &MultiArraySeparableConvolutionTest::test_Valid3 ) ); add( testCase( &MultiArraySeparableConvolutionTest::test_InplaceN ) ); add( testCase( &MultiArraySeparableConvolutionTest::test_Inplace1 ) ); add( testCase( &MultiArraySeparableConvolutionTest::test_gradient1 ) ); add( testCase( &MultiArraySeparableConvolutionTest::test_gradient_magnitude ) ); } }; // struct MultiArraySeparableConvolutionTestSuite //-------------------------------------------------------- int main() { // run the multi-array separable convolutiontestsuite MultiArraySeparableConvolutionTestSuite test1; int failed = test1.run(); std::cout << test1.report() << std::endl; return (failed != 0); } <|endoftext|>
<commit_before>#include <iostream> #include "TString.h" #include "TFile.h" #include "TTree.h" #include "TSystem.h" #include "TMVA/Factory.h" #include "TMVA/Reader.h" #include "TMVA/DataLoader.h" #include "TMVA/PyMethodBase.h" int testPyTorchRegression(){ // Get data file std::cout << "Get test data..." << std::endl; TString fname = "./tmva_reg_example.root"; if (gSystem->AccessPathName(fname)) // file does not exist in local directory gSystem->Exec("curl -L http://root.cern.ch/files/tmva_reg_example.root -L"); TFile *input = TFile::Open(fname); // Build model from python file std::cout << "Generate PyTorch model..." << std::endl; UInt_t ret; ret = gSystem->Exec("python generatePyTorchModelRegression.py"); if(ret!=0){ std::cout << "[ERROR] Failed to generate model using python" << std::endl; return 1; } // Setup PyMVA and factory std::cout << "Setup TMVA..." << std::endl; TMVA::PyMethodBase::PyInitialize(); TFile* outputFile = TFile::Open("ResultsTestPyTorchRegression.root", "RECREATE"); TMVA::Factory *factory = new TMVA::Factory("testPyTorchRegression", outputFile, "!V:Silent:Color:!DrawProgressBar:AnalysisType=Regression"); // Load data TMVA::DataLoader *dataloader = new TMVA::DataLoader("datasetTestPyTorchRegression"); TTree *tree = (TTree*)input->Get("TreeR"); dataloader->AddRegressionTree(tree); dataloader->AddVariable("var1"); dataloader->AddVariable("var2"); dataloader->AddTarget("fvalue"); dataloader->PrepareTrainingAndTestTree("", "SplitMode=Random:NormMode=NumEvents:!V"); // Book and train method factory->BookMethod(dataloader, TMVA::Types::kPyTorch, "PyTorch", "!H:!V:VarTransform=D,G:FilenameModel=PyTorchModelRegression.pt:FilenameTrainedModel=trainedPyTorchModelRegression.h5:NumEpochs=10:BatchSize=32:SaveBestOnly=false:UserCode=generatePyTorchModelRegression.py"); std::cout << "Train model..." << std::endl; factory->TrainAllMethods(); // Clean-up delete factory; delete dataloader; delete outputFile; // Setup reader UInt_t numEvents = 100; std::cout << "Run reader and estimate target of " << numEvents << " events..." << std::endl; TMVA::Reader *reader = new TMVA::Reader("!Color:Silent"); Float_t vars[3]; reader->AddVariable("var1", vars+0); reader->AddVariable("var2", vars+1); reader->BookMVA("PyTorch", "datasetTestPyTorchRegression/weights/testPyTorchRegression_PyTorch.weights.xml"); // Get mean squared error on events tree->SetBranchAddress("var1", vars+0); tree->SetBranchAddress("var2", vars+1); tree->SetBranchAddress("fvalue", vars+2); Float_t meanMvaError = 0; for(UInt_t i=0; i<numEvents; i++){ tree->GetEntry(i); meanMvaError += std::pow(vars[2]-reader->EvaluateMVA("PyTorch"),2); } meanMvaError = meanMvaError/float(numEvents); // Check whether the response is obviously better than guessing std::cout << "Mean squared error: " << meanMvaError << std::endl; if(meanMvaError > 30.0){ std::cout << "[ERROR] Mean squared error is " << meanMvaError << " (>30.0)" << std::endl; return 1; } return 0; } int main(){ int err = testPyTorchRegression(); return err; } <commit_msg>Fix curl typo<commit_after>#include <iostream> #include "TString.h" #include "TFile.h" #include "TTree.h" #include "TSystem.h" #include "TMVA/Factory.h" #include "TMVA/Reader.h" #include "TMVA/DataLoader.h" #include "TMVA/PyMethodBase.h" int testPyTorchRegression(){ // Get data file std::cout << "Get test data..." << std::endl; TString fname = "./tmva_reg_example.root"; if (gSystem->AccessPathName(fname)) // file does not exist in local directory gSystem->Exec("curl -O -L http://root.cern.ch/files/tmva_reg_example.root"); TFile *input = TFile::Open(fname); // Build model from python file std::cout << "Generate PyTorch model..." << std::endl; UInt_t ret; ret = gSystem->Exec("python generatePyTorchModelRegression.py"); if(ret!=0){ std::cout << "[ERROR] Failed to generate model using python" << std::endl; return 1; } // Setup PyMVA and factory std::cout << "Setup TMVA..." << std::endl; TMVA::PyMethodBase::PyInitialize(); TFile* outputFile = TFile::Open("ResultsTestPyTorchRegression.root", "RECREATE"); TMVA::Factory *factory = new TMVA::Factory("testPyTorchRegression", outputFile, "!V:Silent:Color:!DrawProgressBar:AnalysisType=Regression"); // Load data TMVA::DataLoader *dataloader = new TMVA::DataLoader("datasetTestPyTorchRegression"); TTree *tree = (TTree*)input->Get("TreeR"); dataloader->AddRegressionTree(tree); dataloader->AddVariable("var1"); dataloader->AddVariable("var2"); dataloader->AddTarget("fvalue"); dataloader->PrepareTrainingAndTestTree("", "SplitMode=Random:NormMode=NumEvents:!V"); // Book and train method factory->BookMethod(dataloader, TMVA::Types::kPyTorch, "PyTorch", "!H:!V:VarTransform=D,G:FilenameModel=PyTorchModelRegression.pt:FilenameTrainedModel=trainedPyTorchModelRegression.h5:NumEpochs=10:BatchSize=32:SaveBestOnly=false:UserCode=generatePyTorchModelRegression.py"); std::cout << "Train model..." << std::endl; factory->TrainAllMethods(); // Clean-up delete factory; delete dataloader; delete outputFile; // Setup reader UInt_t numEvents = 100; std::cout << "Run reader and estimate target of " << numEvents << " events..." << std::endl; TMVA::Reader *reader = new TMVA::Reader("!Color:Silent"); Float_t vars[3]; reader->AddVariable("var1", vars+0); reader->AddVariable("var2", vars+1); reader->BookMVA("PyTorch", "datasetTestPyTorchRegression/weights/testPyTorchRegression_PyTorch.weights.xml"); // Get mean squared error on events tree->SetBranchAddress("var1", vars+0); tree->SetBranchAddress("var2", vars+1); tree->SetBranchAddress("fvalue", vars+2); Float_t meanMvaError = 0; for(UInt_t i=0; i<numEvents; i++){ tree->GetEntry(i); meanMvaError += std::pow(vars[2]-reader->EvaluateMVA("PyTorch"),2); } meanMvaError = meanMvaError/float(numEvents); // Check whether the response is obviously better than guessing std::cout << "Mean squared error: " << meanMvaError << std::endl; if(meanMvaError > 30.0){ std::cout << "[ERROR] Mean squared error is " << meanMvaError << " (>30.0)" << std::endl; return 1; } return 0; } int main(){ int err = testPyTorchRegression(); return err; } <|endoftext|>
<commit_before>#include "testApp.h" //-------------------------------------------------------------- void testApp::setup(){ ofBackground(0,0,0); ofSetBackgroundAuto(false); isFullScreen = false; ofSetFrameRate(30); masterCounter = 0; direction = 1; //count up // OSC STUFF receiver.setup(PORT); meters = new float[7]; //RECT STUFF rectX = 0; rectY = 0; rectSize = 30; rectSpacing = 0; numYRects = ofGetWidth()/rectSize-rectSpacing; numXRects = ofGetHeight()/rectSize-rectSpacing; numRects = numYRects*numXRects; rectCount = 0; } //-------------------------------------------------------------- void testApp::update(){ parseOSCMessages(); // FUN STUFF masterCounter+=direction; if (masterCounter > 2000) { direction = -1; } if (masterCounter < -2000) { direction = 1; } } //-------------------------------------------------------------- void testApp::draw(){ //drawHorizon(); // Structured rectangles int xPos = ofGetWidth()/2+ofGetWidth()/2*meters[4]; //percussion int yPos = ofGetHeight()/2; int rectSize = 100; ofSetColor(0, 255*meters[4], 0); ofRect(xPos, yPos, rectSize, rectSize); } //-------------------------------------------------------------- void testApp::drawHorizon() { //Abstract line stuff for (int i = 0; i < ofGetWidth(); i++) { // set the color for each line int r = meters[0]*255; int g = meters[1]*255; int b = meters[2]*255; // line start and destination int xStart = i; int yStart = ofGetHeight()/2; int xDest = i*sin(i)*400; //400 is arbitrary. int yDest = i*cos(i)*masterCounter*meters[1]; //shake the signal if (masterCounter%2 == 0) { yStart += meters[1]*10; xDest += xDest*meters[1]; yDest += yDest*meters[1]; } else { yStart -= meters[1]*10; xDest -= xDest*meters[1]; yDest -= yDest*meters[1]; } ofSetColor(r, g, b); //Replace this with pixel colors from feed ofLine(xStart, yStart, xDest, yDest); } } //-------------------------------------------------------------- void testApp::parseOSCMessages() { // check for waiting messages while(receiver.hasWaitingMessages()){ // get the next message ofxOscMessage m; receiver.getNextMessage(&m); // check for meter messages if(m.getAddress() == "/main/meter") { //Go through arguments, get them as floats for (int i = 0; i < m.getNumArgs(); i++) { meters[i] = m.getArgAsFloat(i); // ofLogNotice("meter0"+ofToString(i)+": "+ofToString(meters[i])); } } } } //-------------------------------------------------------------- void testApp::keyPressed(int key){ if (key == 'f' || 'F') { isFullScreen = !isFullScreen; ofSetFullscreen(isFullScreen); } } //-------------------------------------------------------------- void testApp::keyReleased(int key){ } //-------------------------------------------------------------- void testApp::mouseMoved(int x, int y ){ } //-------------------------------------------------------------- void testApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void testApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void testApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void testApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void testApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void testApp::dragEvent(ofDragInfo dragInfo){ } <commit_msg>logging rect stuff in setup<commit_after>#include "testApp.h" //-------------------------------------------------------------- void testApp::setup(){ ofBackground(0,0,0); ofSetBackgroundAuto(false); isFullScreen = false; ofSetFrameRate(30); masterCounter = 0; direction = 1; //count up // OSC STUFF receiver.setup(PORT); meters = new float[7]; //RECT STUFF rectX = 0; rectY = 0; rectSize = 30; rectSpacing = 0; numYRects = ofGetWidth()/rectSize-rectSpacing; numXRects = ofGetHeight()/rectSize-rectSpacing; numRects = numYRects*numXRects; rectCount = 0; ofLogNotice("\n numYRects: "+ofToString(numYRects)+"\n numXRects: "+ofToString(numXRects)+"\n numRects: "+ofToString(numRects)); } //-------------------------------------------------------------- void testApp::update(){ parseOSCMessages(); // FUN STUFF masterCounter+=direction; if (masterCounter > 2000) { direction = -1; } if (masterCounter < -2000) { direction = 1; } } //-------------------------------------------------------------- void testApp::draw(){ //drawHorizon(); // Structured rectangles int xPos = ofGetWidth()/2+ofGetWidth()/2*meters[4]; //percussion int yPos = ofGetHeight()/2; int rectSize = 100; ofSetColor(0, 255*meters[4], 0); ofRect(xPos, yPos, rectSize, rectSize); } //-------------------------------------------------------------- void testApp::drawHorizon() { //Abstract line stuff for (int i = 0; i < ofGetWidth(); i++) { // set the color for each line int r = meters[0]*255; int g = meters[1]*255; int b = meters[2]*255; // line start and destination int xStart = i; int yStart = ofGetHeight()/2; int xDest = i*sin(i)*400; //400 is arbitrary. int yDest = i*cos(i)*masterCounter*meters[1]; //shake the signal if (masterCounter%2 == 0) { yStart += meters[1]*10; xDest += xDest*meters[1]; yDest += yDest*meters[1]; } else { yStart -= meters[1]*10; xDest -= xDest*meters[1]; yDest -= yDest*meters[1]; } ofSetColor(r, g, b); //Replace this with pixel colors from feed ofLine(xStart, yStart, xDest, yDest); } } //-------------------------------------------------------------- void testApp::parseOSCMessages() { // check for waiting messages while(receiver.hasWaitingMessages()){ // get the next message ofxOscMessage m; receiver.getNextMessage(&m); // check for meter messages if(m.getAddress() == "/main/meter") { //Go through arguments, get them as floats for (int i = 0; i < m.getNumArgs(); i++) { meters[i] = m.getArgAsFloat(i); // ofLogNotice("meter0"+ofToString(i)+": "+ofToString(meters[i])); } } } } //-------------------------------------------------------------- void testApp::keyPressed(int key){ if (key == 'f' || 'F') { isFullScreen = !isFullScreen; ofSetFullscreen(isFullScreen); } } //-------------------------------------------------------------- void testApp::keyReleased(int key){ } //-------------------------------------------------------------- void testApp::mouseMoved(int x, int y ){ } //-------------------------------------------------------------- void testApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void testApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void testApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void testApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void testApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void testApp::dragEvent(ofDragInfo dragInfo){ } <|endoftext|>
<commit_before>#include <reconstructmesdk/reme.h> #include <sstream> #include <iostream> using std::cin; using std::cout; using std::endl; using std::stringstream; int main () { reme_context_t context; reme_context_create(&context); reme_options_t options, options_sub; reme_options_create(context, &options); reme_options_create(context, &options_sub); reme_error_t error; if (reme_context_bind_opencl_info(context, options) != REME_ERROR_SUCCESS) { cout << "Error while getting OpenCL compatible devices." << endl; return 0; } int num_devices = 0; reme_options_get_repeated_count(context, options, "devices", &num_devices); cout << "Found " << num_devices << " OpenCL compatible devices." << endl; char name[256], vendor[256], type[256]; for (int idx = 0; idx < num_devices; ++idx) { cout << "---------------------------------" << endl; reme_options_bind_repeated_message(context, options, "devices", idx, options_sub); reme_options_get(context, options_sub, "name", name, 256); reme_options_get(context, options_sub, "vendor", vendor, 256); reme_options_get(context, options_sub, "type", type, 256); cout << "\tDeviceID: " << idx << endl; cout << "\tName: " << name << endl; cout << "\tVendor: " << vendor << endl; cout << "\tType: " << type << endl; } reme_options_t main_options; reme_options_create(context, &main_options); error = reme_context_bind_reconstruction_options(context, main_options); int device_id = -1; cout << "Enter device ID to use: "; cin >> device_id; stringstream sstream; sstream << device_id; reme_options_set(context, main_options, "device_id", sstream.str().c_str()); reme_context_compile(context); reme_context_print_errors(context); } <commit_msg>Getting data from sensor, displaying it.<commit_after>#include <reconstructmesdk/reme.h> #include <sstream> #include <iostream> using std::cin; using std::cout; using std::endl; using std::stringstream; int main () { reme_context_t context; reme_context_create(&context); reme_options_t options, options_sub; reme_options_create(context, &options); reme_options_create(context, &options_sub); reme_error_t error; if (reme_context_bind_opencl_info(context, options) != REME_ERROR_SUCCESS) { cout << "Error while getting OpenCL compatible devices." << endl; return 0; } int num_devices = 0; reme_options_get_repeated_count(context, options, "devices", &num_devices); cout << "Found " << num_devices << " OpenCL compatible devices." << endl; char name[256], vendor[256], type[256]; for (int idx = 0; idx < num_devices; ++idx) { cout << "---------------------------------" << endl; reme_options_bind_repeated_message(context, options, "devices", idx, options_sub); reme_options_get(context, options_sub, "name", name, 256); reme_options_get(context, options_sub, "vendor", vendor, 256); reme_options_get(context, options_sub, "type", type, 256); cout << "\tDeviceID: " << idx << endl; cout << "\tName: " << name << endl; cout << "\tVendor: " << vendor << endl; cout << "\tType: " << type << endl; } reme_options_t main_options; reme_options_create(context, &main_options); error = reme_context_bind_reconstruction_options(context, main_options); int device_id = -1; cout << "Enter device ID to use: "; cin >> device_id; stringstream sstream; sstream << device_id; reme_options_set(context, main_options, "device_id", sstream.str().c_str()); reme_context_compile(context); reme_context_print_errors(context); reme_sensor_t sensor; reme_sensor_create(context, "openni", true, &sensor); reme_sensor_open(context, sensor); reme_image_t image_aux, image_depth, image_volume; reme_image_create(context, &image_aux); reme_image_create(context, &image_depth); reme_image_create(context, &image_volume); reme_viewer_t viewer; reme_viewer_create_image(context, "Image", &viewer); reme_viewer_add_image(context, viewer, image_aux); reme_viewer_add_image(context, viewer, image_depth); reme_viewer_add_image(context, viewer, image_volume); while (REME_SUCCESS(reme_sensor_grab(context, sensor))) { if (REME_SUCCESS(reme_sensor_track_position(context, sensor))) { reme_sensor_update_volume(context, sensor); } reme_sensor_prepare_images(context, sensor); reme_sensor_get_image(context, sensor, REME_IMAGE_AUX, image_aux); reme_sensor_get_image(context, sensor, REME_IMAGE_DEPTH, image_depth); reme_sensor_get_image(context, sensor, REME_IMAGE_VOLUME, image_volume); reme_viewer_update(context, viewer); } reme_context_print_errors(context); reme_context_destroy(&context); } <|endoftext|>
<commit_before>/************************************************************************* * * REALM CONFIDENTIAL * __________________ * * [2011] - [2012] Realm Inc * All Rights Reserved. * * NOTICE: All information contained herein is, and remains * the property of Realm Incorporated and its suppliers, * if any. The intellectual and technical concepts contained * herein are proprietary to Realm Incorporated * and its suppliers and may be covered by U.S. and Foreign Patents, * patents in process, and are protected by trade secret or copyright law. * Dissemination of this information or reproduction of this material * is strictly forbidden unless prior written permission is obtained * from Realm Incorporated. * **************************************************************************/ #include <iostream> #include <sstream> #include <realm/util/features.h> #if REALM_PLATFORM_APPLE # include <dlfcn.h> # include <execinfo.h> # include <CoreFoundation/CoreFoundation.h> #endif #ifdef __ANDROID__ # include <android/log.h> #endif #include <realm/util/terminate.hpp> // extern "C" and noinline so that a readable message shows up in the stack trace // of the crash // prototype here to silence warning extern "C" REALM_NORETURN REALM_NOINLINE void please_report_this_error_to_help_at_realm_dot_io(); // LCOV_EXCL_START extern "C" REALM_NORETURN REALM_NOINLINE void please_report_this_error_to_help_at_realm_dot_io() { std::abort(); } // LCOV_EXCL_STOP namespace { #if REALM_PLATFORM_APPLE void nslog(const char *message) noexcept { CFStringRef str = CFStringCreateWithCStringNoCopy(kCFAllocatorDefault, message, kCFStringEncodingUTF8, kCFAllocatorNull); CFShow(str); // Log the message to Crashlytics if it's loaded into the process void* addr = dlsym(RTLD_DEFAULT, "CLSLog"); if (addr) { auto fn = reinterpret_cast<void (*)(CFStringRef, ...)>(reinterpret_cast<size_t>(addr)); fn(CFSTR("%@"), str); } CFRelease(str); } void(*termination_notification_callback)(const char*) noexcept = nslog; #elif REALM_PLATFORM_ANDROID void android_log(const char* message) noexcept { __android_log_print(ANDROID_LOG_ERROR, "REALM", message); } void(*termination_notification_callback)(const char*) noexcept = android_log; #else void(*termination_notification_callback)(const char*) noexcept = nullptr; #endif } // unnamed namespace namespace realm { namespace util { void set_termination_notification_callback(void(*callback)(const char* ) noexcept) noexcept { termination_notification_callback = callback; } // LCOV_EXCL_START REALM_NORETURN void terminate_internal(std::stringstream& ss) noexcept { #if REALM_PLATFORM_APPLE void* callstack[128]; int frames = backtrace(callstack, 128); char** strs = backtrace_symbols(callstack, frames); for (int i = 0; i < frames; ++i) { ss << strs[i] << '\n'; } free(strs); #endif ss << "IMPORTANT: if you see this error, please send this log to help@realm.io."; #ifdef REALM_DEBUG std::cerr << ss.rdbuf() << '\n'; #endif if (termination_notification_callback) { termination_notification_callback(ss.str().c_str()); } please_report_this_error_to_help_at_realm_dot_io(); } REALM_NORETURN void terminate(const char* message, const char* file, long line) noexcept { std::stringstream ss; ss << file << ":" << line << ": " REALM_VER_CHUNK " " << message << '\n'; terminate_internal(ss); } // LCOV_EXCL_STOP } // namespace util } // namespace realm <commit_msg>Have `terminate` log to both stderr and Apple System Log.<commit_after>/************************************************************************* * * REALM CONFIDENTIAL * __________________ * * [2011] - [2012] Realm Inc * All Rights Reserved. * * NOTICE: All information contained herein is, and remains * the property of Realm Incorporated and its suppliers, * if any. The intellectual and technical concepts contained * herein are proprietary to Realm Incorporated * and its suppliers and may be covered by U.S. and Foreign Patents, * patents in process, and are protected by trade secret or copyright law. * Dissemination of this information or reproduction of this material * is strictly forbidden unless prior written permission is obtained * from Realm Incorporated. * **************************************************************************/ #include <iostream> #include <sstream> #include <realm/util/features.h> #if REALM_PLATFORM_APPLE # include <asl.h> # include <dlfcn.h> # include <execinfo.h> # include <CoreFoundation/CoreFoundation.h> #endif #ifdef __ANDROID__ # include <android/log.h> #endif #include <realm/util/terminate.hpp> // extern "C" and noinline so that a readable message shows up in the stack trace // of the crash // prototype here to silence warning extern "C" REALM_NORETURN REALM_NOINLINE void please_report_this_error_to_help_at_realm_dot_io(); // LCOV_EXCL_START extern "C" REALM_NORETURN REALM_NOINLINE void please_report_this_error_to_help_at_realm_dot_io() { std::abort(); } // LCOV_EXCL_STOP namespace { #if REALM_PLATFORM_APPLE void nslog(const char *message) noexcept { // Standard error goes nowhere for applications managed by launchd, so log to ASL as well. fputs(message, stderr); asl_log(nullptr, nullptr, ASL_LEVEL_ERR, "%s", message); // Log the message to Crashlytics if it's loaded into the process void* addr = dlsym(RTLD_DEFAULT, "CLSLog"); if (addr) { CFStringRef str = CFStringCreateWithCStringNoCopy(kCFAllocatorDefault, message, kCFStringEncodingUTF8, kCFAllocatorNull); auto fn = reinterpret_cast<void (*)(CFStringRef, ...)>(reinterpret_cast<size_t>(addr)); fn(CFSTR("%@"), str); CFRelease(str); } } void(*termination_notification_callback)(const char*) noexcept = nslog; #elif REALM_PLATFORM_ANDROID void android_log(const char* message) noexcept { __android_log_print(ANDROID_LOG_ERROR, "REALM", message); } void(*termination_notification_callback)(const char*) noexcept = android_log; #else void(*termination_notification_callback)(const char*) noexcept = nullptr; #endif } // unnamed namespace namespace realm { namespace util { void set_termination_notification_callback(void(*callback)(const char* ) noexcept) noexcept { termination_notification_callback = callback; } // LCOV_EXCL_START REALM_NORETURN void terminate_internal(std::stringstream& ss) noexcept { #if REALM_PLATFORM_APPLE void* callstack[128]; int frames = backtrace(callstack, 128); char** strs = backtrace_symbols(callstack, frames); for (int i = 0; i < frames; ++i) { ss << strs[i] << '\n'; } free(strs); #endif ss << "IMPORTANT: if you see this error, please send this log to help@realm.io."; #ifdef REALM_DEBUG std::cerr << ss.rdbuf() << '\n'; #endif if (termination_notification_callback) { termination_notification_callback(ss.str().c_str()); } please_report_this_error_to_help_at_realm_dot_io(); } REALM_NORETURN void terminate(const char* message, const char* file, long line) noexcept { std::stringstream ss; ss << file << ":" << line << ": " REALM_VER_CHUNK " " << message << '\n'; terminate_internal(ss); } // LCOV_EXCL_STOP } // namespace util } // namespace realm <|endoftext|>
<commit_before>#include "scene.h" #include "game.h" #include "player_context.h" #include "text_entity.h" #include "welcome_state.h" using namespace space_invaders; inline std::string toScoreString(int score) { auto result = std::to_string(score); auto difference = (4 - result.size()); if (difference >= 0) { result = "0000" + result; } return result.substr(result.length() - 4, 4); } Scene::Scene(Game& game) : mGame(game), mState(std::make_shared<WelcomeState>(game)), mScore1Caption(std::make_shared<TextEntity>(game)), mHiScoreCaption(std::make_shared<TextEntity>(game)), mScore2Caption(std::make_shared<TextEntity>(game)), mScore1Text(std::make_shared<TextEntity>(game)), mHiScoreText(std::make_shared<TextEntity>(game)), mScore2Text(std::make_shared<TextEntity>(game)) { // initialize the static caption for the 1st player score. mScore1Caption->setText("SCORE<1>"); mScore1Caption->setX(125 - (mScore1Caption->getWidth() / 2)); mScore1Caption->setY(40); // initialize the static caption for the high score. mHiScoreCaption->setText("HI-SCORE"); mHiScoreCaption->setX(672 / 2 - (mHiScoreCaption->getWidth() / 2)); mHiScoreCaption->setY(mScore1Caption->getY()); // initialize the static caption for the 2nd player score. mScore2Caption->setText("SCORE<2>"); mScore2Caption->setX(672 - 130 - (mScore2Caption->getWidth() / 2)); mScore2Caption->setY(mScore1Caption->getY()); // initialize the dynamic score value for the 1st player. mScore1Text->setText("0000"); mScore1Text->setX(125 - (mScore1Text->getWidth() / 2)); mScore1Text->setY(mScore1Caption->getY() + 35); // initialize the dynamic score value for the high score. mHiScoreText->setText("0000"); mHiScoreText->setX(672 / 2 - (mHiScoreText->getWidth() / 2)); mHiScoreText->setY(mScore1Text->getY()); // initialize the dynamic score value for the 2nd player. mScore2Text->setText("0000"); mScore2Text->setX(672 - 130 - (mScore2Text->getWidth() / 2)); mScore2Text->setY(mScore1Text->getY()); } void Scene::update(unsigned long dt) { // get references to both player context containers. const auto& ctx1 = mGame.getPlayerContext1(); const auto& ctx2 = mGame.getPlayerContext2(); // ensure that player scores are up-to-date. mScore1Text->setText(toScoreString(ctx1.getScore())); mScore2Text->setText(toScoreString(ctx2.getScore())); mScore1Caption->update(dt); mHiScoreCaption->update(dt); mScore2Caption->update(dt); mScore1Text->update(dt); mHiScoreText->update(dt); mScore2Text->update(dt); mState->update(dt); } void Scene::render(SDL_Renderer& renderer) { mScore1Caption->render(renderer); mHiScoreCaption->render(renderer); mScore2Caption->render(renderer); mScore1Text->render(renderer); mHiScoreText->render(renderer); mScore2Text->render(renderer); mState->render(renderer); } void Scene::onKeyUp(SDL_KeyboardEvent& event) { mState->onKeyUp(event); } void Scene::onKeyDown(SDL_KeyboardEvent& event) { mState->onKeyDown(event); } void Scene::setState(StatePtr state) { // exit from the old state (if defined). if (mState) { mState->onExit(); } // assign and enter the new state (if not null) mState = state; if (mState) { mState->onEnter(); } }<commit_msg>Constantly keep track of the current hi-score in the scene.cpp.<commit_after>#include "scene.h" #include "game.h" #include "player_context.h" #include "text_entity.h" #include "welcome_state.h" using namespace space_invaders; inline std::string toScoreString(int score) { auto result = std::to_string(score); auto difference = (4 - result.size()); if (difference >= 0) { result = "0000" + result; } return result.substr(result.length() - 4, 4); } Scene::Scene(Game& game) : mGame(game), mState(std::make_shared<WelcomeState>(game)), mScore1Caption(std::make_shared<TextEntity>(game)), mHiScoreCaption(std::make_shared<TextEntity>(game)), mScore2Caption(std::make_shared<TextEntity>(game)), mScore1Text(std::make_shared<TextEntity>(game)), mHiScoreText(std::make_shared<TextEntity>(game)), mScore2Text(std::make_shared<TextEntity>(game)) { // initialize the static caption for the 1st player score. mScore1Caption->setText("SCORE<1>"); mScore1Caption->setX(125 - (mScore1Caption->getWidth() / 2)); mScore1Caption->setY(40); // initialize the static caption for the high score. mHiScoreCaption->setText("HI-SCORE"); mHiScoreCaption->setX(672 / 2 - (mHiScoreCaption->getWidth() / 2)); mHiScoreCaption->setY(mScore1Caption->getY()); // initialize the static caption for the 2nd player score. mScore2Caption->setText("SCORE<2>"); mScore2Caption->setX(672 - 130 - (mScore2Caption->getWidth() / 2)); mScore2Caption->setY(mScore1Caption->getY()); // initialize the dynamic score value for the 1st player. mScore1Text->setText("0000"); mScore1Text->setX(125 - (mScore1Text->getWidth() / 2)); mScore1Text->setY(mScore1Caption->getY() + 35); // initialize the dynamic score value for the high score. mHiScoreText->setText("0000"); mHiScoreText->setX(672 / 2 - (mHiScoreText->getWidth() / 2)); mHiScoreText->setY(mScore1Text->getY()); // initialize the dynamic score value for the 2nd player. mScore2Text->setText("0000"); mScore2Text->setX(672 - 130 - (mScore2Text->getWidth() / 2)); mScore2Text->setY(mScore1Text->getY()); } void Scene::update(unsigned long dt) { // get references to both player context containers. const auto& ctx1 = mGame.getPlayerContext1(); const auto& ctx2 = mGame.getPlayerContext2(); // ensure that player scores are up-to-date. mScore1Text->setText(toScoreString(ctx1.getScore())); mScore2Text->setText(toScoreString(ctx2.getScore())); // ensure that the hi-score is up-to-date. const auto hiScore = mGame.getHiScore(); mHiScoreText->setText(toScoreString(hiScore)); mScore1Caption->update(dt); mHiScoreCaption->update(dt); mScore2Caption->update(dt); mScore1Text->update(dt); mHiScoreText->update(dt); mScore2Text->update(dt); mState->update(dt); } void Scene::render(SDL_Renderer& renderer) { mScore1Caption->render(renderer); mHiScoreCaption->render(renderer); mScore2Caption->render(renderer); mScore1Text->render(renderer); mHiScoreText->render(renderer); mScore2Text->render(renderer); mState->render(renderer); } void Scene::onKeyUp(SDL_KeyboardEvent& event) { mState->onKeyUp(event); } void Scene::onKeyDown(SDL_KeyboardEvent& event) { mState->onKeyDown(event); } void Scene::setState(StatePtr state) { // exit from the old state (if defined). if (mState) { mState->onExit(); } // assign and enter the new state (if not null) mState = state; if (mState) { mState->onEnter(); } }<|endoftext|>
<commit_before>// This file is part of the dune-gdt project: // http://users.dune-project.org/projects/dune-gdt // Copyright holders: Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_GDT_TEST_PRODUCTS_SWIPDGPENALTY_HH #define DUNE_GDT_TEST_PRODUCTS_SWIPDGPENALTY_HH #include <dune/stuff/functions/checkerboard.hh> #include <dune/stuff/functions/constant.hh> #include <dune/stuff/functions/expression.hh> #include <dune/stuff/functions/interfaces.hh> #include <dune/stuff/la/container/common.hh> #include <dune/gdt/discretefunction/default.hh> #include <dune/gdt/operators/projections.hh> #include <dune/gdt/localevaluation/swipdg.hh> #include <dune/gdt/playground/products/swipdgpenalty.hh> #include "products.hh" using namespace Dune; using namespace Dune::GDT; template <class SpaceType> struct SwipdgPenaltyProductBase : public ::testing::Test { typedef typename SpaceType::GridViewType GridViewType; typedef typename GridViewType::Grid GridType; typedef Dune::Stuff::Grid::Providers::Cube<GridType> GridProviderType; typedef typename GridViewType::template Codim<0>::Entity EntityType; typedef typename SpaceType::DomainFieldType DomainFieldType; static const unsigned int dimDomain = SpaceType::dimDomain; typedef typename SpaceType::RangeFieldType RangeFieldType; static const unsigned int dimRange = SpaceType::dimRange; typedef Stuff::Functions::Expression<EntityType, DomainFieldType, dimDomain, RangeFieldType, dimRange> ScalarType; typedef Stuff::Functions::Constant<EntityType, DomainFieldType, dimDomain, RangeFieldType, dimDomain, dimDomain> TensorType; typedef Stuff::Functions::Checkerboard<EntityType, DomainFieldType, dimDomain, RangeFieldType, dimRange> JumpFunctionType; typedef Stuff::LocalizableFunctionInterface<EntityType, DomainFieldType, dimDomain, RangeFieldType, dimRange> FunctionType; static DSC::Configuration jump_config() { DSC::Configuration cfg = JumpFunctionType::default_config(); cfg["num_elements"] = "[2 1 1]"; cfg["values"] = "[0 1]"; return cfg; } SwipdgPenaltyProductBase() : grid_provider_(0.0, 1.0, 2u) , space_(grid_provider_.template leaf<SpaceType::part_view_type>()) , one_("x", "1", 0) , unit_matrix_(Stuff::Functions::internal::unit_matrix<RangeFieldType, dimDomain>()) , continuous_("x", "x[0] - 1", 1) , jump_(JumpFunctionType::create(jump_config())) { } virtual RangeFieldType compute(const FunctionType& function) const = 0; void continuous_arguments() const { // there is no jump in the middle, but at the left boundary we are not zero // the 1 is the order of continuous_ check(compute(continuous_), LocalEvaluation::SWIPDG::internal::boundary_sigma(1), 1e-13); } void discontinuous_arguments() const { // there is a jump in the middle and at the right boundary we are not zero // the 0 is the order of *jump_ // *0.5 because the value of *jump_ is 0 left and 1 right check(compute(*jump_), 0.5 * LocalEvaluation::SWIPDG::internal::inner_sigma(0) + LocalEvaluation::SWIPDG::internal::boundary_sigma(0)); } void check(const RangeFieldType& result, const RangeFieldType& expected, const RangeFieldType epsilon = 1e-14) const { const auto error = std::abs(expected - result); EXPECT_LE(error, epsilon) << "result: " << result << "\n" << "expected: " << expected << "\n" << "difference: " << std::scientific << error; } // ... check(...) GridProviderType grid_provider_; const SpaceType space_; const ScalarType one_; const TensorType unit_matrix_; const ScalarType continuous_; const std::unique_ptr<const JumpFunctionType> jump_; }; // struct SwipdgPenaltyProductBase template <class SpaceType> struct SwipdgPenaltyLocalizableProduct : public SwipdgPenaltyProductBase<SpaceType> { typedef SwipdgPenaltyProductBase<SpaceType> BaseType; typedef typename BaseType::GridViewType GridViewType; typedef typename BaseType::ScalarType ScalarType; typedef typename BaseType::TensorType TensorType; typedef typename BaseType::FunctionType FunctionType; typedef typename BaseType::RangeFieldType RangeFieldType; virtual RangeFieldType compute(const FunctionType& function) const override final { return Products::SwipdgPenaltyLocalizable<GridViewType, ScalarType, TensorType, FunctionType, FunctionType>( this->space_.grid_view(), function, function, this->one_, this->unit_matrix_) .apply2(); } void fulfills_interface() const { typedef Products::SwipdgPenaltyLocalizable<GridViewType, ScalarType, TensorType, ScalarType, ScalarType> ProductType; ProductType product(this->space_.grid_view(), this->one_, this->one_, this->one_, this->unit_matrix_); LocalizableProductBase<SpaceType, ProductType>::fulfills_interface(product); } }; // struct SwipdgPenaltyLocalizableProduct template <class SpaceType> struct SwipdgPenaltyAssemblableProduct : public SwipdgPenaltyProductBase<SpaceType> { typedef SwipdgPenaltyProductBase<SpaceType> BaseType; typedef typename BaseType::RangeFieldType RangeFieldType; typedef typename BaseType::ScalarType ScalarType; typedef typename BaseType::TensorType TensorType; typedef typename BaseType::FunctionType FunctionType; typedef typename BaseType::GridViewType GridViewType; typedef typename Dune::Stuff::LA::CommonDenseVector<RangeFieldType> VectorType; typedef typename Dune::Stuff::LA::CommonDenseMatrix<RangeFieldType> MatrixType; typedef Dune::GDT::DiscreteFunction<SpaceType, VectorType> DiscreteFunctionType; typedef Dune::GDT::Operators::Projection<GridViewType> ProjectionOperatorType; virtual RangeFieldType compute(const FunctionType& function) const override final { // create the product typedef Products::SwipdgPenaltyAssemblable<MatrixType, ScalarType, TensorType, SpaceType, GridViewType, SpaceType> Product; Product product(this->space_, this->one_, this->unit_matrix_); product.assemble(false); // project the function DiscreteFunctionType discrete_function(this->space_); ProjectionOperatorType(this->space_.grid_view()).apply(function, discrete_function); // compute the product const auto result = product.apply2(discrete_function, discrete_function); Product product_tbb(this->space_, this->one_, this->unit_matrix_); product_tbb.assemble(true); const auto result_tbb = product_tbb.apply2(discrete_function, discrete_function); EXPECT_DOUBLE_EQ(result_tbb, result); return result; } // ... compute(...) void fulfills_interface() const { typedef Products::SwipdgPenaltyAssemblable<MatrixType, ScalarType, TensorType, SpaceType, GridViewType, SpaceType> ProductType; ProductType product(this->space_, this->one_, this->unit_matrix_); AssemblableProductBase<SpaceType, ProductType, VectorType>::fulfills_interface(product); } }; // struct SwipdgPenaltyAssemblableProduct template <class SpaceType> struct SwipdgPenaltyProduct : public SwipdgPenaltyProductBase<SpaceType> { typedef SwipdgPenaltyProductBase<SpaceType> BaseType; typedef typename BaseType::RangeFieldType RangeFieldType; typedef typename BaseType::ScalarType ScalarType; typedef typename BaseType::TensorType TensorType; typedef typename BaseType::FunctionType FunctionType; typedef typename BaseType::GridViewType GridViewType; virtual RangeFieldType compute(const FunctionType& function) const override final { Products::SwipdgPenalty<GridViewType, FunctionType, TensorType> product( this->space_.grid_view(), this->one_, this->unit_matrix_); return product.apply2(function, function); } // ... compute(...) void fulfills_interface() const { typedef Products::SwipdgPenalty<GridViewType, FunctionType, TensorType> ProductType; ProductBase<SpaceType, ProductType>::fulfills_interface( ProductType(this->space_.grid_view(), this->one_, this->unit_matrix_)); } }; // struct SwipdgPenaltyProduct #endif // DUNE_GDT_TEST_PRODUCTS_SWIPDGPENALTY_HH <commit_msg>[test.products_swipdgpenalty] update sigma<commit_after>// This file is part of the dune-gdt project: // http://users.dune-project.org/projects/dune-gdt // Copyright holders: Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_GDT_TEST_PRODUCTS_SWIPDGPENALTY_HH #define DUNE_GDT_TEST_PRODUCTS_SWIPDGPENALTY_HH #include <dune/stuff/functions/checkerboard.hh> #include <dune/stuff/functions/constant.hh> #include <dune/stuff/functions/expression.hh> #include <dune/stuff/functions/interfaces.hh> #include <dune/stuff/la/container/common.hh> #include <dune/gdt/discretefunction/default.hh> #include <dune/gdt/operators/projections.hh> #include <dune/gdt/localevaluation/swipdg.hh> #include <dune/gdt/playground/products/swipdgpenalty.hh> #include "products.hh" using namespace Dune; using namespace Dune::GDT; template <class SpaceType> struct SwipdgPenaltyProductBase : public ::testing::Test { typedef typename SpaceType::GridViewType GridViewType; typedef typename GridViewType::Grid GridType; typedef Dune::Stuff::Grid::Providers::Cube<GridType> GridProviderType; typedef typename GridViewType::template Codim<0>::Entity EntityType; typedef typename SpaceType::DomainFieldType DomainFieldType; static const unsigned int dimDomain = SpaceType::dimDomain; typedef typename SpaceType::RangeFieldType RangeFieldType; static const unsigned int dimRange = SpaceType::dimRange; typedef Stuff::Functions::Expression<EntityType, DomainFieldType, dimDomain, RangeFieldType, dimRange> ScalarType; typedef Stuff::Functions::Constant<EntityType, DomainFieldType, dimDomain, RangeFieldType, dimDomain, dimDomain> TensorType; typedef Stuff::Functions::Checkerboard<EntityType, DomainFieldType, dimDomain, RangeFieldType, dimRange> JumpFunctionType; typedef Stuff::LocalizableFunctionInterface<EntityType, DomainFieldType, dimDomain, RangeFieldType, dimRange> FunctionType; static DSC::Configuration jump_config() { DSC::Configuration cfg = JumpFunctionType::default_config(); cfg["num_elements"] = "[2 1 1]"; cfg["values"] = "[0 1]"; return cfg; } SwipdgPenaltyProductBase() : grid_provider_(0.0, 1.0, 2u) , space_(grid_provider_.template leaf<SpaceType::part_view_type>()) , one_("x", "1", 0) , unit_matrix_(Stuff::Functions::internal::unit_matrix<RangeFieldType, dimDomain>()) , continuous_("x", "x[0] - 1", 1) , jump_(JumpFunctionType::create(jump_config())) { } virtual RangeFieldType compute(const FunctionType& function) const = 0; void continuous_arguments() const { // there is no jump in the middle, but at the left boundary we are not zero // the 1 is the order of continuous_ check(compute(continuous_), LocalEvaluation::SIPDG::internal::boundary_sigma(1), 1e-13); } void discontinuous_arguments() const { // there is a jump in the middle and at the right boundary we are not zero // the 0 is the order of *jump_ // *0.5 because the value of *jump_ is 0 left and 1 right check(compute(*jump_), 0.5 * LocalEvaluation::SIPDG::internal::inner_sigma(0) + LocalEvaluation::SIPDG::internal::boundary_sigma(0)); } void check(const RangeFieldType& result, const RangeFieldType& expected, const RangeFieldType epsilon = 1e-14) const { const auto error = std::abs(expected - result); EXPECT_LE(error, epsilon) << "result: " << result << "\n" << "expected: " << expected << "\n" << "difference: " << std::scientific << error; } // ... check(...) GridProviderType grid_provider_; const SpaceType space_; const ScalarType one_; const TensorType unit_matrix_; const ScalarType continuous_; const std::unique_ptr<const JumpFunctionType> jump_; }; // struct SwipdgPenaltyProductBase template <class SpaceType> struct SwipdgPenaltyLocalizableProduct : public SwipdgPenaltyProductBase<SpaceType> { typedef SwipdgPenaltyProductBase<SpaceType> BaseType; typedef typename BaseType::GridViewType GridViewType; typedef typename BaseType::ScalarType ScalarType; typedef typename BaseType::TensorType TensorType; typedef typename BaseType::FunctionType FunctionType; typedef typename BaseType::RangeFieldType RangeFieldType; virtual RangeFieldType compute(const FunctionType& function) const override final { return Products::SwipdgPenaltyLocalizable<GridViewType, ScalarType, TensorType, FunctionType, FunctionType>( this->space_.grid_view(), function, function, this->one_, this->unit_matrix_) .apply2(); } void fulfills_interface() const { typedef Products::SwipdgPenaltyLocalizable<GridViewType, ScalarType, TensorType, ScalarType, ScalarType> ProductType; ProductType product(this->space_.grid_view(), this->one_, this->one_, this->one_, this->unit_matrix_); LocalizableProductBase<SpaceType, ProductType>::fulfills_interface(product); } }; // struct SwipdgPenaltyLocalizableProduct template <class SpaceType> struct SwipdgPenaltyAssemblableProduct : public SwipdgPenaltyProductBase<SpaceType> { typedef SwipdgPenaltyProductBase<SpaceType> BaseType; typedef typename BaseType::RangeFieldType RangeFieldType; typedef typename BaseType::ScalarType ScalarType; typedef typename BaseType::TensorType TensorType; typedef typename BaseType::FunctionType FunctionType; typedef typename BaseType::GridViewType GridViewType; typedef typename Dune::Stuff::LA::CommonDenseVector<RangeFieldType> VectorType; typedef typename Dune::Stuff::LA::CommonDenseMatrix<RangeFieldType> MatrixType; typedef Dune::GDT::DiscreteFunction<SpaceType, VectorType> DiscreteFunctionType; typedef Dune::GDT::Operators::Projection<GridViewType> ProjectionOperatorType; virtual RangeFieldType compute(const FunctionType& function) const override final { // create the product typedef Products::SwipdgPenaltyAssemblable<MatrixType, ScalarType, TensorType, SpaceType, GridViewType, SpaceType> Product; Product product(this->space_, this->one_, this->unit_matrix_); product.assemble(false); // project the function DiscreteFunctionType discrete_function(this->space_); ProjectionOperatorType(this->space_.grid_view()).apply(function, discrete_function); // compute the product const auto result = product.apply2(discrete_function, discrete_function); Product product_tbb(this->space_, this->one_, this->unit_matrix_); product_tbb.assemble(true); const auto result_tbb = product_tbb.apply2(discrete_function, discrete_function); EXPECT_DOUBLE_EQ(result_tbb, result); return result; } // ... compute(...) void fulfills_interface() const { typedef Products::SwipdgPenaltyAssemblable<MatrixType, ScalarType, TensorType, SpaceType, GridViewType, SpaceType> ProductType; ProductType product(this->space_, this->one_, this->unit_matrix_); AssemblableProductBase<SpaceType, ProductType, VectorType>::fulfills_interface(product); } }; // struct SwipdgPenaltyAssemblableProduct template <class SpaceType> struct SwipdgPenaltyProduct : public SwipdgPenaltyProductBase<SpaceType> { typedef SwipdgPenaltyProductBase<SpaceType> BaseType; typedef typename BaseType::RangeFieldType RangeFieldType; typedef typename BaseType::ScalarType ScalarType; typedef typename BaseType::TensorType TensorType; typedef typename BaseType::FunctionType FunctionType; typedef typename BaseType::GridViewType GridViewType; virtual RangeFieldType compute(const FunctionType& function) const override final { Products::SwipdgPenalty<GridViewType, FunctionType, TensorType> product( this->space_.grid_view(), this->one_, this->unit_matrix_); return product.apply2(function, function); } // ... compute(...) void fulfills_interface() const { typedef Products::SwipdgPenalty<GridViewType, FunctionType, TensorType> ProductType; ProductBase<SpaceType, ProductType>::fulfills_interface( ProductType(this->space_.grid_view(), this->one_, this->unit_matrix_)); } }; // struct SwipdgPenaltyProduct #endif // DUNE_GDT_TEST_PRODUCTS_SWIPDGPENALTY_HH <|endoftext|>
<commit_before>#include <gmock/gmock.h> #include <set> #include "oddlib/stream.hpp" #include <jsonxx/jsonxx.h> #include "logger.hpp" using namespace ::testing; size_t StringHash(const char* s) { // FNV hasher size_t result = 2166136261U; while (*s) { result = (16777619 * result) ^ static_cast<unsigned char>(*s); s++; } return result; } size_t StringHash(const std::string& s) { return StringHash(s.c_str()); } std::vector<Uint8> StringToVector(const std::string& str) { return std::vector<Uint8>(str.begin(), str.end()); } class IFileSystem { public: virtual ~IFileSystem() = default; virtual std::unique_ptr<Oddlib::IStream> Open(const char* fileName) = 0; // TODO impl this and other required helpers //virtual std::string UserSettingsDirectory() = 0; }; class FileSystem : public IFileSystem { public: virtual std::unique_ptr<Oddlib::IStream> Open(const char* fileName) override { // TODO std::ignore = fileName; return nullptr; } }; class MockFileSystem : public IFileSystem { public: virtual std::unique_ptr<Oddlib::IStream> Open(const char* fileName) override { // Can't mock unique_ptr return, so mock raw one which the unique_ptr one will call return std::unique_ptr<Oddlib::IStream>(OpenProxy(fileName)); } MOCK_METHOD1(OpenProxy, Oddlib::IStream*(const char*)); }; // AOPC, AOPSX, FoosMod etc class GameDefinition { public: GameDefinition(IFileSystem& fileSystem, const char* gameDefinitionFile) { // TODO std::ignore = fileSystem; std::ignore = gameDefinitionFile; } GameDefinition() = default; private: std::string mName; std::string mDescription; std::string mAuthor; // TODO: initial level, how maps connect, etc. // Depends on DataSets }; class ResourceMapper { public: ResourceMapper() = default; ResourceMapper(ResourceMapper&& rhs) { *this = std::move(rhs); } ResourceMapper& operator = (ResourceMapper&& rhs) { if (this != &rhs) { mAnimMaps = std::move(rhs.mAnimMaps); } return *this; } ResourceMapper(IFileSystem& fileSystem, const char* resourceMapFile) { auto stream = fileSystem.Open(resourceMapFile); assert(stream != nullptr); const auto jsonData = stream->LoadAllToString(); Parse(jsonData); } struct AnimMapping { std::string mFile; Uint32 mId; Uint32 mBlendingMode; }; const AnimMapping* Find(const char* resourceName) const { auto it = mAnimMaps.find(resourceName); if (it != std::end(mAnimMaps)) { return &it->second; } return nullptr; } void AddAnimMapping(const std::string& resourceName, const AnimMapping& mapping) { mAnimMaps[resourceName] = mapping; } private: std::map<std::string, AnimMapping> mAnimMaps; void Parse(const std::string& json) { jsonxx::Object root; root.parse(json); if (root.has<jsonxx::Array>("anims")) { const jsonxx::Array& anims = root.get<jsonxx::Array>("anims"); const auto& file = root.get<jsonxx::String>("file"); const auto id = static_cast<Uint32>(root.get<jsonxx::Number>("id")); for (size_t i = 0; i < anims.size(); i++) { AnimMapping mapping; mapping.mFile = file; mapping.mId = static_cast<Uint32>(id); const jsonxx::Object& animRecord = anims.get<jsonxx::Object>(static_cast<Uint32>(i)); const auto& name = animRecord.get<jsonxx::String>("name"); const auto blendMode = animRecord.get<jsonxx::Number>("blend_mode"); mapping.mBlendingMode = static_cast<Uint32>(blendMode); AddAnimMapping(name, mapping); } } } }; class ResourceBase { public: virtual ~ResourceBase() = default; virtual void Reload() = 0; }; class Animation : public ResourceBase { public: virtual void Reload() override { // TODO } }; // TODO: Handle resources that have been loaded via explicit dataset name class ResourceCache { public: void Add(size_t resourceHash, std::shared_ptr<ResourceBase> resource) { mCache[resourceHash] = resource; } void Remove(size_t resourceHash) { auto it = mCache.find(resourceHash); if (it != std::end(mCache)) { auto sPtr = it->second.lock(); if (!sPtr) { mCache.erase(it); } } } template<class T> std::shared_ptr<T> Find(size_t resourceHash) { auto it = mCache.find(resourceHash); if (it != std::end(mCache)) { auto sPtr = it->second.lock(); if (!sPtr) { mCache.erase(it); return nullptr; } return std::static_pointer_cast<T>(sPtr); } return nullptr; } private: std::map<size_t, std::weak_ptr<ResourceBase>> mCache; }; template<class T> class Resource { public: Resource(ResourceCache& cache, std::shared_ptr<T> ptr) : mCache(cache) { mPtr = ptr; } Resource(const Resource& rhs) : mCache(rhs.mCache) { *this = rhs; } Resource& operator = (const Resource& rhs) { if (this != &rhs) { mResourceNameHash = rhs.mResourceNameHash; mPtr = rhs.mPtr; } return *this; } Resource(size_t resourceNameHash, ResourceCache& cache, std::unique_ptr<Oddlib::IStream>) : mResourceNameHash(resourceNameHash), mCache(cache) { mPtr = std::make_shared<T>(); // TODO: Pass in stream mCache.Add(mResourceNameHash, mPtr); } ~Resource() { mCache.Remove(mResourceNameHash); } void Reload() { mPtr->Reload(); } T* Ptr() { return mPtr.get(); } private: std::shared_ptr<T> mPtr; size_t mResourceNameHash; ResourceCache& mCache; }; class DataPaths { public: DataPaths(const DataPaths&) = delete; DataPaths& operator = (const DataPaths&) = delete; DataPaths(IFileSystem& fs) :mFs(fs) { } std::unique_ptr<Oddlib::IStream> Open(const std::string& fileName) { for (auto& path : mDataPaths) { // TODO: We need to search in each LVL that the animMapping->mFile could be in // within each path.mPath, however if the data path is a path to a mod then apply // the override rules such as looking for PNGs instead. auto stream = mFs.Open((path.mPath + "\\" + fileName).c_str()); if (stream) { return stream; } } return nullptr; } void Add(const char* dataPath, Sint32 priority) { mDataPaths.insert({ dataPath, priority }); } private: struct DataPath { std::string mPath; Sint32 mPriority; // Sort such that the lowest priority number is first. bool operator < (const DataPath& rhs) const { return mPriority < rhs.mPriority; } }; std::set<DataPath> mDataPaths; IFileSystem& mFs; }; class ResourceLocator { public: ResourceLocator(const ResourceLocator&) = delete; ResourceLocator& operator =(const ResourceLocator&) = delete; ResourceLocator(IFileSystem& fileSystem, GameDefinition& game, ResourceMapper&& resourceMapper) : mDataPaths(fileSystem), mResMapper(std::move(resourceMapper)) { std::ignore = game; } void AddDataPath(const char* dataPath, Sint32 priority) { mDataPaths.Add(dataPath, priority); } template<typename T> Resource<T> Locate(const char* resourceName) { // TODO: Use hashses for names after this point? const size_t strHash = StringHash(resourceName); // Check if the resource is cached std::shared_ptr<T> cachedRes = mResourceCache.Find<T>(strHash); if (cachedRes) { return Resource<T>(mResourceCache, cachedRes); } // For each data set attempt to find resourceName by mapping // to a LVL/file/chunk. Or in the case of a mod dataset something else. const ResourceMapper::AnimMapping* animMapping = mResMapper.Find(resourceName); if (animMapping) { const auto& lvlFileToFind = animMapping->mFile; auto stream = mDataPaths.Open(lvlFileToFind); if (stream) { return Resource<T>(strHash, mResourceCache, std::move(stream)); } } // TODO return Resource<T>(StringHash(""), mResourceCache, nullptr); } // This method should be used for debugging only - i.e so we can compare what resource X looks like // in dataset A and B. template<typename T> Resource<T> Locate(const char* resourceName, const char* dataSetName) { std::ignore = resourceName; std::ignore = dataSetName; // TODO return Resource<T>(StringHash(""), mResourceCache, nullptr); } private: DataPaths mDataPaths; ResourceMapper mResMapper; ResourceCache mResourceCache; }; TEST(DataPaths, Open) { MockFileSystem fs; DataPaths paths(fs); EXPECT_CALL(fs, OpenProxy(StrEq("C:\\dataset_location1\\SLIGZ.BND"))) .WillRepeatedly(Return(nullptr)); EXPECT_CALL(fs, OpenProxy(StrEq("C:\\dataset_location2\\SLIGZ.BND"))) .Times(1) .WillOnce(Return(new Oddlib::Stream(StringToVector("test")))); auto stream = paths.Open("SLIGZ.BND"); ASSERT_NE(nullptr, stream); const auto str = stream->LoadAllToString(); ASSERT_EQ(str, "test"); } TEST(ResourceLocator, Cache) { ResourceCache cache; const size_t resNameHash = StringHash("foo"); ASSERT_EQ(nullptr, cache.Find<Animation>(resNameHash)); { Resource<Animation> res1(resNameHash, cache, nullptr); std::shared_ptr<Animation> cached = cache.Find<Animation>(resNameHash); ASSERT_NE(nullptr, cached); ASSERT_EQ(cached.get(), res1.Ptr()); } ASSERT_EQ(nullptr, cache.Find<Animation>(resNameHash)); } TEST(ResourceLocator, ParseResourceMap) { const std::string resourceMapsJson = R"({"anims":[{"blend_mode":1,"name":"SLIGZ.BND_417_1"},{"blend_mode":1,"name":"SLIGZ.BND_417_2"}],"file":"SLIGZ.BND","id":417})"; MockFileSystem fs; EXPECT_CALL(fs, OpenProxy(StrEq("resource_maps.json"))) .WillRepeatedly(Return(new Oddlib::Stream(StringToVector(resourceMapsJson)))); ResourceMapper mapper(fs, "resource_maps.json"); const ResourceMapper::AnimMapping* r0 = mapper.Find("I don't exist"); ASSERT_EQ(nullptr, r0); const ResourceMapper::AnimMapping* r1 = mapper.Find("SLIGZ.BND_417_1"); ASSERT_NE(nullptr, r1); ASSERT_EQ("SLIGZ.BND", r1->mFile); ASSERT_EQ(417u, r1->mId); ASSERT_EQ(1u, r1->mBlendingMode); const ResourceMapper::AnimMapping* r2 = mapper.Find("SLIGZ.BND_417_2"); ASSERT_NE(nullptr, r2); ASSERT_EQ("SLIGZ.BND", r2->mFile); ASSERT_EQ(417u, r2->mId); ASSERT_EQ(1u, r2->mBlendingMode); } TEST(ResourceLocator, LocateAnimation) { GameDefinition aePc; /* aePc.mAuthor = "Oddworld Inhabitants"; aePc.mDescription = "The original PC version of Oddworld Abe's Exoddus"; aePc.mName = "Oddworld Abe's Exoddus PC"; */ MockFileSystem fs; EXPECT_CALL(fs, OpenProxy(StrEq("C:\\dataset_location1\\SLIGZ.BND"))) .WillRepeatedly(Return(nullptr)); EXPECT_CALL(fs, OpenProxy(StrEq("C:\\dataset_location2\\SLIGZ.BND"))) .Times(1) .WillOnce(Return(new Oddlib::Stream(StringToVector("test")))); // For SLIGZ.BND_417_1, 2nd call should be cached ResourceMapper mapper; mapper.AddAnimMapping("SLIGZ.BND_417_1", { "SLIGZ.BND", 417, 1 }); mapper.AddAnimMapping("SLIGZ.BND_417_2", { "SLIGZ.BND", 417, 1 }); ResourceLocator locator(fs, aePc, std::move(mapper)); locator.AddDataPath("C:\\dataset_location2", 2); locator.AddDataPath("C:\\dataset_location1", 1); Resource<Animation> resMapped1 = locator.Locate<Animation>("SLIGZ.BND_417_1"); resMapped1.Reload(); Resource<Animation> resMapped2 = locator.Locate<Animation>("SLIGZ.BND_417_1"); resMapped2.Reload(); // Can explicitly set the dataset to obtain it from a known location Resource<Animation> resDirect = locator.Locate<Animation>("SLIGZ.BND_417_1", "AEPCCD1"); resDirect.Reload(); } TEST(ResourceLocator, LocateFmv) { // TODO } TEST(ResourceLocator, LocateSound) { // TODO } TEST(ResourceLocator, LocateMusic) { // TODO } TEST(ResourceLocator, LocateCamera) { // TODO } TEST(ResourceLocator, LocatePath) { // TODO } <commit_msg>strongly type the data set type<commit_after>#include <gmock/gmock.h> #include <set> #include "oddlib/stream.hpp" #include <jsonxx/jsonxx.h> #include "logger.hpp" using namespace ::testing; size_t StringHash(const char* s) { // FNV hasher size_t result = 2166136261U; while (*s) { result = (16777619 * result) ^ static_cast<unsigned char>(*s); s++; } return result; } size_t StringHash(const std::string& s) { return StringHash(s.c_str()); } std::vector<Uint8> StringToVector(const std::string& str) { return std::vector<Uint8>(str.begin(), str.end()); } class IFileSystem { public: virtual ~IFileSystem() = default; virtual std::unique_ptr<Oddlib::IStream> Open(const char* fileName) = 0; // TODO impl this and other required helpers //virtual std::string UserSettingsDirectory() = 0; }; class FileSystem : public IFileSystem { public: virtual std::unique_ptr<Oddlib::IStream> Open(const char* fileName) override { // TODO std::ignore = fileName; return nullptr; } }; class MockFileSystem : public IFileSystem { public: virtual std::unique_ptr<Oddlib::IStream> Open(const char* fileName) override { // Can't mock unique_ptr return, so mock raw one which the unique_ptr one will call return std::unique_ptr<Oddlib::IStream>(OpenProxy(fileName)); } MOCK_METHOD1(OpenProxy, Oddlib::IStream*(const char*)); }; // AOPC, AOPSX, FoosMod etc class GameDefinition { public: GameDefinition(IFileSystem& fileSystem, const char* gameDefinitionFile) { // TODO std::ignore = fileSystem; std::ignore = gameDefinitionFile; } GameDefinition() = default; private: std::string mName; std::string mDescription; std::string mAuthor; // TODO: initial level, how maps connect, etc. // Depends on DataSets }; class ResourceMapper { public: ResourceMapper() = default; ResourceMapper(ResourceMapper&& rhs) { *this = std::move(rhs); } ResourceMapper& operator = (ResourceMapper&& rhs) { if (this != &rhs) { mAnimMaps = std::move(rhs.mAnimMaps); } return *this; } ResourceMapper(IFileSystem& fileSystem, const char* resourceMapFile) { auto stream = fileSystem.Open(resourceMapFile); assert(stream != nullptr); const auto jsonData = stream->LoadAllToString(); Parse(jsonData); } struct AnimMapping { std::string mFile; Uint32 mId; Uint32 mBlendingMode; }; const AnimMapping* Find(const char* resourceName) const { auto it = mAnimMaps.find(resourceName); if (it != std::end(mAnimMaps)) { return &it->second; } return nullptr; } void AddAnimMapping(const std::string& resourceName, const AnimMapping& mapping) { mAnimMaps[resourceName] = mapping; } private: std::map<std::string, AnimMapping> mAnimMaps; void Parse(const std::string& json) { jsonxx::Object root; root.parse(json); if (root.has<jsonxx::Array>("anims")) { const jsonxx::Array& anims = root.get<jsonxx::Array>("anims"); const auto& file = root.get<jsonxx::String>("file"); const auto id = static_cast<Uint32>(root.get<jsonxx::Number>("id")); for (size_t i = 0; i < anims.size(); i++) { AnimMapping mapping; mapping.mFile = file; mapping.mId = static_cast<Uint32>(id); const jsonxx::Object& animRecord = anims.get<jsonxx::Object>(static_cast<Uint32>(i)); const auto& name = animRecord.get<jsonxx::String>("name"); const auto blendMode = animRecord.get<jsonxx::Number>("blend_mode"); mapping.mBlendingMode = static_cast<Uint32>(blendMode); AddAnimMapping(name, mapping); } } } }; class ResourceBase { public: virtual ~ResourceBase() = default; virtual void Reload() = 0; }; class Animation : public ResourceBase { public: virtual void Reload() override { // TODO } }; // TODO: Handle resources that have been loaded via explicit dataset name class ResourceCache { public: void Add(size_t resourceHash, std::shared_ptr<ResourceBase> resource) { mCache[resourceHash] = resource; } void Remove(size_t resourceHash) { auto it = mCache.find(resourceHash); if (it != std::end(mCache)) { auto sPtr = it->second.lock(); if (!sPtr) { mCache.erase(it); } } } template<class T> std::shared_ptr<T> Find(size_t resourceHash) { auto it = mCache.find(resourceHash); if (it != std::end(mCache)) { auto sPtr = it->second.lock(); if (!sPtr) { mCache.erase(it); return nullptr; } return std::static_pointer_cast<T>(sPtr); } return nullptr; } private: std::map<size_t, std::weak_ptr<ResourceBase>> mCache; }; template<class T> class Resource { public: Resource(ResourceCache& cache, std::shared_ptr<T> ptr) : mCache(cache) { mPtr = ptr; } Resource(const Resource& rhs) : mCache(rhs.mCache) { *this = rhs; } Resource& operator = (const Resource& rhs) { if (this != &rhs) { mResourceNameHash = rhs.mResourceNameHash; mPtr = rhs.mPtr; } return *this; } Resource(size_t resourceNameHash, ResourceCache& cache, std::unique_ptr<Oddlib::IStream>) : mResourceNameHash(resourceNameHash), mCache(cache) { mPtr = std::make_shared<T>(); // TODO: Pass in stream mCache.Add(mResourceNameHash, mPtr); } ~Resource() { mCache.Remove(mResourceNameHash); } void Reload() { mPtr->Reload(); } T* Ptr() { return mPtr.get(); } private: std::shared_ptr<T> mPtr; size_t mResourceNameHash; ResourceCache& mCache; }; enum class DataTypes { eAoPc, eAoPcDemo, eAoPsx, eAoPsxDemo, eAePc, eAePcDemo, eAePsxCd1, eAePsxCd2, eAePsxDemo }; const char* ToString(DataTypes type) { switch (type) { case DataTypes::eAoPc: return "eAoPc"; case DataTypes::eAoPcDemo: return "eAoPcDemo"; case DataTypes::eAoPsx: return "eAoPsx"; case DataTypes::eAoPsxDemo: return "eAoPsxDemo"; case DataTypes::eAePc: return "eAePc"; case DataTypes::eAePcDemo: return "eAePcDemo"; case DataTypes::eAePsxCd1: return "eAePsxCd1"; case DataTypes::eAePsxCd2: return "eAePsxCd2"; case DataTypes::eAePsxDemo: return "eAePsxDemo"; default: abort(); } } class DataPaths { public: DataPaths(const DataPaths&) = delete; DataPaths& operator = (const DataPaths&) = delete; DataPaths(IFileSystem& fs) :mFs(fs) { } std::unique_ptr<Oddlib::IStream> Open(const std::string& fileName) { for (auto& path : mDataPaths) { // TODO: We need to search in each LVL that the animMapping->mFile could be in // within each path.mPath, however if the data path is a path to a mod then apply // the override rules such as looking for PNGs instead. auto stream = mFs.Open((path.mPath + "\\" + fileName).c_str()); if (stream) { return stream; } } return nullptr; } void Add(const char* dataPath, Sint32 priority) { mDataPaths.insert({ dataPath, priority }); } private: struct DataPath { std::string mPath; Sint32 mPriority; // Sort such that the lowest priority number is first. bool operator < (const DataPath& rhs) const { return mPriority < rhs.mPriority; } }; std::set<DataPath> mDataPaths; IFileSystem& mFs; }; class ResourceLocator { public: ResourceLocator(const ResourceLocator&) = delete; ResourceLocator& operator =(const ResourceLocator&) = delete; ResourceLocator(IFileSystem& fileSystem, GameDefinition& game, ResourceMapper&& resourceMapper) : mDataPaths(fileSystem), mResMapper(std::move(resourceMapper)) { std::ignore = game; } void AddDataPath(const char* dataPath, Sint32 priority) { mDataPaths.Add(dataPath, priority); } template<typename T> Resource<T> Locate(const char* resourceName) { const size_t resNameHash = StringHash(resourceName); // Check if the resource is cached std::shared_ptr<T> cachedRes = mResourceCache.Find<T>(resNameHash); if (cachedRes) { return Resource<T>(mResourceCache, cachedRes); } // For each data set attempt to find resourceName by mapping // to a LVL/file/chunk. Or in the case of a mod dataset something else. const ResourceMapper::AnimMapping* animMapping = mResMapper.Find(resourceName); if (animMapping) { const auto& lvlFileToFind = animMapping->mFile; auto stream = mDataPaths.Open(lvlFileToFind); if (stream) { return Resource<T>(resNameHash, mResourceCache, std::move(stream)); } } // TODO return Resource<T>(StringHash(""), mResourceCache, nullptr); } // This method should be used for debugging only - i.e so we can compare what resource X looks like // in dataset A and B. template<typename T> Resource<T> Locate(const char* resourceName, DataTypes dataSetName) { const std::string uniqueName = std::string(resourceName) + ToString(dataSetName); const size_t resNameHash = StringHash(uniqueName); // Check if the resource is cached std::shared_ptr<T> cachedRes = mResourceCache.Find<T>(resNameHash); if (cachedRes) { return Resource<T>(mResourceCache, cachedRes); } const ResourceMapper::AnimMapping* animMapping = mResMapper.Find(resourceName); if (animMapping) { // TODO: Find resource in specific data set //const auto& lvlFileToFind = animMapping->mFile; //auto stream = mDataPaths.Open(lvlFileToFind, dataSetName); } // TODO return Resource<T>(StringHash(""), mResourceCache, nullptr); } private: DataPaths mDataPaths; ResourceMapper mResMapper; ResourceCache mResourceCache; }; TEST(DataPaths, Open) { MockFileSystem fs; DataPaths paths(fs); EXPECT_CALL(fs, OpenProxy(StrEq("C:\\dataset_location1\\SLIGZ.BND"))) .WillRepeatedly(Return(nullptr)); EXPECT_CALL(fs, OpenProxy(StrEq("C:\\dataset_location2\\SLIGZ.BND"))) .Times(1) .WillOnce(Return(new Oddlib::Stream(StringToVector("test")))); auto stream = paths.Open("SLIGZ.BND"); ASSERT_NE(nullptr, stream); const auto str = stream->LoadAllToString(); ASSERT_EQ(str, "test"); } TEST(ResourceLocator, Cache) { ResourceCache cache; const size_t resNameHash = StringHash("foo"); ASSERT_EQ(nullptr, cache.Find<Animation>(resNameHash)); { Resource<Animation> res1(resNameHash, cache, nullptr); std::shared_ptr<Animation> cached = cache.Find<Animation>(resNameHash); ASSERT_NE(nullptr, cached); ASSERT_EQ(cached.get(), res1.Ptr()); } ASSERT_EQ(nullptr, cache.Find<Animation>(resNameHash)); } TEST(ResourceLocator, ParseResourceMap) { const std::string resourceMapsJson = R"({"anims":[{"blend_mode":1,"name":"SLIGZ.BND_417_1"},{"blend_mode":1,"name":"SLIGZ.BND_417_2"}],"file":"SLIGZ.BND","id":417})"; MockFileSystem fs; EXPECT_CALL(fs, OpenProxy(StrEq("resource_maps.json"))) .WillRepeatedly(Return(new Oddlib::Stream(StringToVector(resourceMapsJson)))); ResourceMapper mapper(fs, "resource_maps.json"); const ResourceMapper::AnimMapping* r0 = mapper.Find("I don't exist"); ASSERT_EQ(nullptr, r0); const ResourceMapper::AnimMapping* r1 = mapper.Find("SLIGZ.BND_417_1"); ASSERT_NE(nullptr, r1); ASSERT_EQ("SLIGZ.BND", r1->mFile); ASSERT_EQ(417u, r1->mId); ASSERT_EQ(1u, r1->mBlendingMode); const ResourceMapper::AnimMapping* r2 = mapper.Find("SLIGZ.BND_417_2"); ASSERT_NE(nullptr, r2); ASSERT_EQ("SLIGZ.BND", r2->mFile); ASSERT_EQ(417u, r2->mId); ASSERT_EQ(1u, r2->mBlendingMode); } TEST(ResourceLocator, LocateAnimation) { GameDefinition aePc; /* aePc.mAuthor = "Oddworld Inhabitants"; aePc.mDescription = "The original PC version of Oddworld Abe's Exoddus"; aePc.mName = "Oddworld Abe's Exoddus PC"; */ MockFileSystem fs; EXPECT_CALL(fs, OpenProxy(StrEq("C:\\dataset_location1\\SLIGZ.BND"))) .WillRepeatedly(Return(nullptr)); EXPECT_CALL(fs, OpenProxy(StrEq("C:\\dataset_location2\\SLIGZ.BND"))) .Times(1) .WillOnce(Return(new Oddlib::Stream(StringToVector("test")))); // For SLIGZ.BND_417_1, 2nd call should be cached ResourceMapper mapper; mapper.AddAnimMapping("SLIGZ.BND_417_1", { "SLIGZ.BND", 417, 1 }); mapper.AddAnimMapping("SLIGZ.BND_417_2", { "SLIGZ.BND", 417, 1 }); ResourceLocator locator(fs, aePc, std::move(mapper)); locator.AddDataPath("C:\\dataset_location2", 2); locator.AddDataPath("C:\\dataset_location1", 1); Resource<Animation> resMapped1 = locator.Locate<Animation>("SLIGZ.BND_417_1"); resMapped1.Reload(); Resource<Animation> resMapped2 = locator.Locate<Animation>("SLIGZ.BND_417_1"); resMapped2.Reload(); // Can explicitly set the dataset to obtain it from a known location Resource<Animation> resDirect = locator.Locate<Animation>("SLIGZ.BND_417_1", DataTypes::eAePsxCd1); resDirect.Reload(); } TEST(ResourceLocator, LocateFmv) { // TODO } TEST(ResourceLocator, LocateSound) { // TODO } TEST(ResourceLocator, LocateMusic) { // TODO } TEST(ResourceLocator, LocateCamera) { // TODO } TEST(ResourceLocator, LocatePath) { // TODO } <|endoftext|>
<commit_before>#include "tileset.h" #include "romfile.h" #include "compress.h" const romaddr_t ptrTilesetL = {0x12, 0x8a4f}; const romaddr_t ptrTilesetH = {0x12, 0x8a1e}; const romaddr_t ptrTilesetB = {0x12, 0x89ed}; const romaddr_t tileSubVals = {0x12, 0x9c5f}; metatile_t tilesets[NUM_TILESETS][0x100]; uint8_t tileSubtract[NUM_TILESETS]; void loadTilesets(ROMFile& rom) { uint8_t tileset[DATA_SIZE]; uint8_t *palettes = tileset + 0x400; uint8_t *behavior = tileset + 0x440; for (uint set = 0; set < NUM_TILESETS; set++) { rom.readFromPointer(ptrTilesetL, ptrTilesetH, ptrTilesetB, 0, tileset, set); for (uint tile = 0; tile < 0x100; tile++) { tilesets[set][tile].ul = tileset[tile*4 + 0]; tilesets[set][tile].ur = tileset[tile*4 + 1]; tilesets[set][tile].ll = tileset[tile*4 + 2]; tilesets[set][tile].lr = tileset[tile*4 + 3]; tilesets[set][tile].palette = (palettes[tile / 4] >> (3 - tile%4)*2) & 3; tilesets[set][tile].action = behavior[tile]; } tileSubtract[set] = rom.readByte(tileSubVals + set); } } DataChunk packTileset(uint num) { uint8_t buf[DATA_SIZE] = {0}; uint8_t *palettes = buf + 0x400; uint8_t *behavior = buf + 0x440; for (uint tile = 0; tile < 0x100; tile++) { buf[tile*4 + 0] = tilesets[num][tile].ul; buf[tile*4 + 1] = tilesets[num][tile].ur; buf[tile*4 + 2] = tilesets[num][tile].ll; buf[tile*4 + 3] = tilesets[num][tile].lr; palettes[tile/4] |= tilesets[num][tile].palette << (3 - tile%4)*2; behavior[tile] = tilesets[num][tile].action; } return DataChunk(buf, 0x540, DataChunk::tileset, num); } void saveTileset(ROMFile& file, const DataChunk &chunk, romaddr_t addr) { //data banks mapped to A000-BFFF addr.addr %= BANK_SIZE; addr.addr += 0xA000; // save compressed data chunk, update pointer table uint num = chunk.num; file.writeToPointer(ptrTilesetL, ptrTilesetH, ptrTilesetB, addr, chunk.size, chunk.data, num); } <commit_msg>use hardcoded tile subtraction values for now<commit_after>#include "tileset.h" #include "romfile.h" #include "compress.h" const romaddr_t ptrTilesetL = {0x12, 0x8a4f}; const romaddr_t ptrTilesetH = {0x12, 0x8a1e}; const romaddr_t ptrTilesetB = {0x12, 0x89ed}; const romaddr_t tileSubVals = {0x12, 0x9c5f}; metatile_t tilesets[NUM_TILESETS][0x100]; uint8_t tileSubtract[NUM_TILESETS]; void loadTilesets(ROMFile& rom) { uint8_t tileset[DATA_SIZE]; uint8_t *palettes = tileset + 0x400; uint8_t *behavior = tileset + 0x440; for (uint set = 0; set < NUM_TILESETS; set++) { rom.readFromPointer(ptrTilesetL, ptrTilesetH, ptrTilesetB, 0, tileset, set); for (uint tile = 0; tile < 0x100; tile++) { tilesets[set][tile].ul = tileset[tile*4 + 0]; tilesets[set][tile].ur = tileset[tile*4 + 1]; tilesets[set][tile].ll = tileset[tile*4 + 2]; tilesets[set][tile].lr = tileset[tile*4 + 3]; tilesets[set][tile].palette = (palettes[tile / 4] >> (3 - tile%4)*2) & 3; tilesets[set][tile].action = behavior[tile]; } // for now, use the default value, because this may have been corrupted // by a bug in the previous release (and it can't be changed in the editor right now anyway) tileSubtract[set] = 0x08; // tileSubtract[set] = rom.readByte(tileSubVals + set); } } DataChunk packTileset(uint num) { uint8_t buf[DATA_SIZE] = {0}; uint8_t *palettes = buf + 0x400; uint8_t *behavior = buf + 0x440; for (uint tile = 0; tile < 0x100; tile++) { buf[tile*4 + 0] = tilesets[num][tile].ul; buf[tile*4 + 1] = tilesets[num][tile].ur; buf[tile*4 + 2] = tilesets[num][tile].ll; buf[tile*4 + 3] = tilesets[num][tile].lr; palettes[tile/4] |= tilesets[num][tile].palette << (3 - tile%4)*2; behavior[tile] = tilesets[num][tile].action; } return DataChunk(buf, 0x540, DataChunk::tileset, num); } void saveTileset(ROMFile& file, const DataChunk &chunk, romaddr_t addr) { //data banks mapped to A000-BFFF addr.addr %= BANK_SIZE; addr.addr += 0xA000; // save compressed data chunk, update pointer table uint num = chunk.num; file.writeToPointer(ptrTilesetL, ptrTilesetH, ptrTilesetB, addr, chunk.size, chunk.data, num); // save destroyable value file.writeByte(tileSubVals + num, tileSubtract[num]); } <|endoftext|>
<commit_before>/* Cycript - Optimizing JavaScript Compiler/Runtime * Copyright (C) 2009-2013 Jay Freeman (saurik) */ /* GNU General Public License, Version 3 {{{ */ /* * Cycript 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 3 of the License, * or (at your option) any later version. * * Cycript 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 Cycript. If not, see <http://www.gnu.org/licenses/>. **/ /* }}} */ #include <complex> #include <sstream> #ifdef HAVE_READLINE_H #include <readline.h> #else #include <readline/readline.h> #endif #if RL_READLINE_VERSION >= 0x0600 #include <sys/ioctl.h> #include "Highlight.hpp" #include <term.h> typedef std::complex<int> CYCursor; extern "C" int rl_display_fixed; extern "C" int _rl_vis_botlin; extern "C" int _rl_last_c_pos; extern "C" int _rl_last_v_pos; CYCursor current_; int width_; size_t point_; unsigned CYDisplayWidth() { struct winsize info; if (ioctl(1, TIOCGWINSZ, &info) != -1) return info.ws_col; return tgetnum(const_cast<char *>("co")); } void CYDisplayOutput_(int (*put)(int), const char *&data) { for (;; ++data) { char next(*data); if (next == '\0' || next == CYIgnoreEnd) return; if (put != NULL) put(next); } } CYCursor CYDisplayOutput(int (*put)(int), int width, const char *data, ssize_t offset = 0) { CYCursor point(current_); for (;;) { if (offset-- == 0) point = current_; char next(*data++); switch (next) { case '\0': return point; break; case CYIgnoreStart: CYDisplayOutput_(put, data); case CYIgnoreEnd: ++offset; break; default: current_ += CYCursor(0, 1); if (current_.imag() == width) case '\n': current_ = CYCursor(current_.real() + 1, 0); if (put != NULL) put(next); break; } } } void CYDisplayMove_(char *negative, char *positive, int offset) { if (offset < 0) putp(tparm(negative, -offset)); else if (offset > 0) putp(tparm(positive, offset)); } void CYDisplayMove(CYCursor target) { CYCursor offset(target - current_); CYDisplayMove_(parm_up_cursor, parm_down_cursor, offset.real()); if (char *parm = tparm(column_address, target.imag())) putp(parm); else CYDisplayMove_(parm_left_cursor, parm_right_cursor, offset.imag()); current_ = target; } void CYDisplayStart(int meta) { rl_prep_terminal(meta); current_ = CYCursor(); } void CYDisplayUpdate() { rl_display_fixed = 1; rl_redisplay(); #if RL_READLINE_VERSION >= 0x0600 const char *prompt(rl_display_prompt); #else const char *prompt(rl_prompt); #endif std::ostringstream stream; CYLexerHighlight(rl_line_buffer, rl_end, stream, true); std::string string(stream.str()); const char *buffer(string.c_str()); int width(CYDisplayWidth()); if (width_ != width) { current_ = CYCursor(); CYDisplayOutput(NULL, width, prompt); current_ = CYDisplayOutput(NULL, width, buffer, point_); } CYDisplayMove(CYCursor()); CYDisplayOutput(putchar, width, prompt); CYCursor target(CYDisplayOutput(putchar, width, stream.str().c_str(), rl_point)); _rl_vis_botlin = current_.real(); _rl_last_c_pos = current_.imag(); _rl_last_v_pos = target.real(); if (current_.imag() == 0) CYDisplayOutput(putchar, width, " "); putp(clr_eos); CYDisplayMove(target); fflush(stdout); width_ = width; point_ = rl_point; } void CYDisplayFinish() { rl_deprep_terminal(); } #endif <commit_msg>Sometimes readline forced the display to update.<commit_after>/* Cycript - Optimizing JavaScript Compiler/Runtime * Copyright (C) 2009-2013 Jay Freeman (saurik) */ /* GNU General Public License, Version 3 {{{ */ /* * Cycript 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 3 of the License, * or (at your option) any later version. * * Cycript 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 Cycript. If not, see <http://www.gnu.org/licenses/>. **/ /* }}} */ #include <complex> #include <sstream> #ifdef HAVE_READLINE_H #include <readline.h> #else #include <readline/readline.h> #endif #if RL_READLINE_VERSION >= 0x0600 #include <sys/ioctl.h> #include "Highlight.hpp" #include <term.h> typedef std::complex<int> CYCursor; extern "C" int rl_display_fixed; extern "C" int _rl_vis_botlin; extern "C" int _rl_last_c_pos; extern "C" int _rl_last_v_pos; CYCursor current_; int width_; size_t point_; unsigned CYDisplayWidth() { struct winsize info; if (ioctl(1, TIOCGWINSZ, &info) != -1) return info.ws_col; return tgetnum(const_cast<char *>("co")); } void CYDisplayOutput_(int (*put)(int), const char *&data) { for (;; ++data) { char next(*data); if (next == '\0' || next == CYIgnoreEnd) return; if (put != NULL) put(next); } } CYCursor CYDisplayOutput(int (*put)(int), int width, const char *data, ssize_t offset = 0) { CYCursor point(current_); for (;;) { if (offset-- == 0) point = current_; char next(*data++); switch (next) { case '\0': return point; break; case CYIgnoreStart: CYDisplayOutput_(put, data); case CYIgnoreEnd: ++offset; break; default: current_ += CYCursor(0, 1); if (current_.imag() == width) case '\n': current_ = CYCursor(current_.real() + 1, 0); if (put != NULL) put(next); break; } } } void CYDisplayMove_(char *negative, char *positive, int offset) { if (offset < 0) putp(tparm(negative, -offset)); else if (offset > 0) putp(tparm(positive, offset)); } void CYDisplayMove(CYCursor target) { CYCursor offset(target - current_); CYDisplayMove_(parm_up_cursor, parm_down_cursor, offset.real()); if (char *parm = tparm(column_address, target.imag())) putp(parm); else CYDisplayMove_(parm_left_cursor, parm_right_cursor, offset.imag()); current_ = target; } void CYDisplayStart(int meta) { rl_prep_terminal(meta); current_ = CYCursor(); } void CYDisplayUpdate() { rl_display_fixed = 1; rl_redisplay(); current_ = CYCursor(_rl_last_v_pos, _rl_last_c_pos); #if RL_READLINE_VERSION >= 0x0600 const char *prompt(rl_display_prompt); #else const char *prompt(rl_prompt); #endif std::ostringstream stream; CYLexerHighlight(rl_line_buffer, rl_end, stream, true); std::string string(stream.str()); const char *buffer(string.c_str()); int width(CYDisplayWidth()); if (width_ != width) { current_ = CYCursor(); CYDisplayOutput(NULL, width, prompt); current_ = CYDisplayOutput(NULL, width, buffer, point_); } CYDisplayMove(CYCursor()); CYDisplayOutput(putchar, width, prompt); CYCursor target(CYDisplayOutput(putchar, width, stream.str().c_str(), rl_point)); _rl_vis_botlin = current_.real(); if (current_.imag() == 0) CYDisplayOutput(putchar, width, " "); putp(clr_eos); CYDisplayMove(target); fflush(stdout); _rl_last_v_pos = current_.real(); _rl_last_c_pos = current_.imag(); width_ = width; point_ = rl_point; } void CYDisplayFinish() { rl_deprep_terminal(); } #endif <|endoftext|>
<commit_before>// ReaderWriterSPT.cxx -- Provide a paged database for flightgear scenery. // // Copyright (C) 2010 - 2013 Mathias Froehlich // // 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. // #ifdef HAVE_CONFIG_H # include <simgear_config.h> #endif #include "ReaderWriterSPT.hxx" #include <cassert> #include <osg/CullFace> #include <osg/PagedLOD> #include <osg/MatrixTransform> #include <osg/Texture2D> #include <osgDB/FileNameUtils> #include <osgDB/FileUtils> #include <osgDB/ReadFile> #include <simgear/scene/util/OsgMath.hxx> #include "BucketBox.hxx" namespace simgear { // Cull away tiles that we watch from downside struct ReaderWriterSPT::CullCallback : public osg::NodeCallback { virtual ~CullCallback() { } virtual void operator()(osg::Node* node, osg::NodeVisitor* nv) { const osg::BoundingSphere& nodeBound = node->getBound(); // If the bounding sphere of the node is empty, there is nothing to do if (!nodeBound.valid()) return; // Culling away tiles that we look at from the downside. // This is done by computing the maximum distance we can // see something from the current eyepoint. If the sphere // that is defined by this radius does no intersects the // nodes sphere, then this tile is culled away. // Computing this radius happens by two rectangular triangles: // Let r be the view point. rmin is the minimum radius we find // a ground surface we need to look above. rmax is the // maximum object radius we expect any object. // // d1 d2 // x----x----x // r\ rmin /rmax // \ | / // \ | / // \|/ // // The distance from the eyepoint to the point // where the line of sight is perpandicular to // the radius vector with minimal height is // d1 = sqrt(r^2 - rmin^2). // The distance from the point where the line of sight // is perpandicular to the radius vector with minimal height // to the highest possible object on earth with radius rmax is // d2 = sqrt(rmax^2 - rmin^2). // So the maximum distance we can see something on the earth // from a viewpoint r is // d = d1 + d2 // This is the equatorial earth radius minus 450m, // little lower than Dead Sea. float rmin = 6378137 - 450; float rmin2 = rmin*rmin; // This is the equatorial earth radius plus 9000m, // little higher than Mount Everest. float rmax = 6378137 + 9000; float rmax2 = rmax*rmax; // Check if we are looking from below any ground osg::Vec3 viewPoint = nv->getViewPoint(); // blow the viewpoint up to a spherical earth with equatorial radius: osg::Vec3 sphericViewPoint = viewPoint; sphericViewPoint[2] *= 1.0033641; float r2 = sphericViewPoint.length2(); if (r2 <= rmin2) return; // Due to this line of sight computation, the visible tiles // are limited to be within a sphere with radius d1 + d2. float d1 = sqrtf(r2 - rmin2); float d2 = sqrtf(rmax2 - rmin2); // Note that we again base the sphere around elliptic view point, // but use the radius from the spherical computation. if (!nodeBound.intersects(osg::BoundingSphere(viewPoint, d1 + d2))) return; traverse(node, nv); } }; ReaderWriterSPT::ReaderWriterSPT() { supportsExtension("spt", "SimGear paged terrain meta database."); } ReaderWriterSPT::~ReaderWriterSPT() { } const char* ReaderWriterSPT::className() const { return "simgear::ReaderWriterSPT"; } osgDB::ReaderWriter::ReadResult ReaderWriterSPT::readObject(const std::string& fileName, const osgDB::Options* options) const { // We get called with different extensions. To make sure search continues, // we need to return FILE_NOT_HANDLED in this case. if (osgDB::getLowerCaseFileExtension(fileName) != "spt") return ReadResult(ReadResult::FILE_NOT_HANDLED); if (fileName != "state.spt") return ReadResult(ReadResult::FILE_NOT_FOUND); osg::StateSet* stateSet = new osg::StateSet; stateSet->setAttributeAndModes(new osg::CullFace); std::string imageFileName = options->getPluginStringData("SimGear::FG_WORLD_TEXTURE"); if (imageFileName.empty()) { imageFileName = options->getPluginStringData("SimGear::FG_ROOT"); imageFileName = osgDB::concatPaths(imageFileName, "Textures"); imageFileName = osgDB::concatPaths(imageFileName, "Globe"); imageFileName = osgDB::concatPaths(imageFileName, "world.topo.bathy.200407.3x4096x2048.png"); } if (osg::Image* image = osgDB::readImageFile(imageFileName, options)) { osg::Texture2D* texture = new osg::Texture2D; texture->setImage(image); texture->setWrap(osg::Texture2D::WRAP_S, osg::Texture2D::REPEAT); texture->setWrap(osg::Texture2D::WRAP_T, osg::Texture2D::CLAMP); stateSet->setTextureAttributeAndModes(0, texture); } return stateSet; } osgDB::ReaderWriter::ReadResult ReaderWriterSPT::readNode(const std::string& fileName, const osgDB::Options* options) const { // The file name without path and without the spt extension std::string strippedFileName = osgDB::getStrippedName(fileName); if (strippedFileName == "earth") return ReadResult(createTree(BucketBox(-180, -90, 360, 180), options, true)); std::stringstream ss(strippedFileName); BucketBox bucketBox; ss >> bucketBox; if (ss.fail()) return ReadResult::FILE_NOT_FOUND; BucketBox bucketBoxList[2]; unsigned bucketBoxListSize = bucketBox.periodicSplit(bucketBoxList); if (bucketBoxListSize == 0) return ReadResult::FILE_NOT_FOUND; if (bucketBoxListSize == 1) return ReadResult(createTree(bucketBoxList[0], options, true)); assert(bucketBoxListSize == 2); osg::ref_ptr<osg::Group> group = new osg::Group; group->addChild(createTree(bucketBoxList[0], options, true)); group->addChild(createTree(bucketBoxList[1], options, true)); return ReadResult(group); } osg::ref_ptr<osg::Node> ReaderWriterSPT::createTree(const BucketBox& bucketBox, const osgDB::Options* options, bool topLevel) const { if (bucketBox.getIsBucketSize()) { std::string fileName; fileName = bucketBox.getBucket().gen_index_str() + std::string(".stg"); return osgDB::readRefNodeFile(fileName, options); } else if (!topLevel && bucketBox.getStartLevel() == 3) { // We want an other level of indirection for paging // Here we get about 12x12 deg tiles return createPagedLOD(bucketBox, options); } else if (!topLevel && bucketBox.getStartLevel() == 5) { // We want an other level of indirection for paging // Here we get about 2x2 deg tiles return createPagedLOD(bucketBox, options); } else if (!topLevel && bucketBox.getStartLevel() == 7) { // We want an other level of indirection for paging // Here we get about 0.5x0.5 deg tiles return createPagedLOD(bucketBox, options); } else { BucketBox bucketBoxList[100]; unsigned numTiles = bucketBox.getSubDivision(bucketBoxList, 100); if (numTiles == 0) return 0; if (numTiles == 1) return createTree(bucketBoxList[0], options, false); osg::ref_ptr<osg::Group> group = new osg::Group; for (unsigned i = 0; i < numTiles; ++i) { osg::ref_ptr<osg::Node> node = createTree(bucketBoxList[i], options, false); if (!node.valid()) continue; group->addChild(node.get()); } if (!group->getNumChildren()) return 0; return group; } } osg::ref_ptr<osg::Node> ReaderWriterSPT::createPagedLOD(const BucketBox& bucketBox, const osgDB::Options* options) const { osg::PagedLOD* pagedLOD = new osg::PagedLOD; pagedLOD->setCenterMode(osg::PagedLOD::USER_DEFINED_CENTER); SGSpheref sphere = bucketBox.getBoundingSphere(); pagedLOD->setCenter(toOsg(sphere.getCenter())); pagedLOD->setRadius(sphere.getRadius()); pagedLOD->setCullCallback(new CullCallback); osg::ref_ptr<osgDB::Options> localOptions; localOptions = static_cast<osgDB::Options*>(options->clone(osg::CopyOp())); // FIXME: // The particle systems have nodes with culling disabled. // PagedLOD nodes with childnodes like this will never expire. // So, for now switch them off. localOptions->setPluginStringData("SimGear::PARTICLESYSTEM", "OFF"); pagedLOD->setDatabaseOptions(localOptions.get()); float range = 3*sphere.getRadius(); // Add the static sea level textured shell osg::ref_ptr<osg::Node> tile = createSeaLevelTile(bucketBox, options); if (tile.valid()) pagedLOD->addChild(tile.get(), range, std::numeric_limits<float>::max()); // Add the paged file name that creates the subtrees on demand if (bucketBox.getIsBucketSize()) { std::string fileName; fileName = bucketBox.getBucket().gen_index_str() + std::string(".stg"); pagedLOD->setFileName(pagedLOD->getNumChildren(), fileName); } else { std::stringstream ss; ss << bucketBox << ".spt"; pagedLOD->setFileName(pagedLOD->getNumChildren(), ss.str()); } pagedLOD->setRange(pagedLOD->getNumChildren(), 0.0, range); return pagedLOD; } osg::ref_ptr<osg::Node> ReaderWriterSPT::createSeaLevelTile(const BucketBox& bucketBox, const osgDB::Options* options) const { if (options->getPluginStringData("SimGear::FG_EARTH") != "ON") return 0; SGSpheref sphere = bucketBox.getBoundingSphere(); osg::Matrixd transform; transform.makeTranslate(toOsg(-sphere.getCenter())); osg::Vec3Array* vertices = new osg::Vec3Array; osg::Vec3Array* normals = new osg::Vec3Array; osg::Vec2Array* texCoords = new osg::Vec2Array; unsigned widthLevel = bucketBox.getWidthLevel(); unsigned heightLevel = bucketBox.getHeightLevel(); unsigned incx = bucketBox.getWidthIncrement(widthLevel + 2); incx = std::min(incx, bucketBox.getSize(0)); for (unsigned i = 0; incx != 0;) { unsigned incy = bucketBox.getHeightIncrement(heightLevel + 2); incy = std::min(incy, bucketBox.getSize(1)); for (unsigned j = 0; incy != 0;) { SGVec3f v[6], n[6]; SGVec2f t[6]; unsigned num = bucketBox.getTileTriangles(i, j, incx, incy, v, n, t); for (unsigned k = 0; k < num; ++k) { vertices->push_back(transform.preMult(toOsg(v[k]))); normals->push_back(toOsg(n[k])); texCoords->push_back(toOsg(t[k])); } j += incy; incy = std::min(incy, bucketBox.getSize(1) - j); } i += incx; incx = std::min(incx, bucketBox.getSize(0) - i); } osg::Vec4Array* colors = new osg::Vec4Array; colors->push_back(osg::Vec4(1, 1, 1, 1)); osg::Geometry* geometry = new osg::Geometry; geometry->setVertexArray(vertices); geometry->setNormalArray(normals); geometry->setNormalBinding(osg::Geometry::BIND_PER_VERTEX); geometry->setColorArray(colors); geometry->setColorBinding(osg::Geometry::BIND_OVERALL); geometry->setTexCoordArray(0, texCoords); osg::DrawArrays* drawArrays = new osg::DrawArrays(osg::DrawArrays::TRIANGLES, 0, vertices->size()); drawArrays->setDataVariance(osg::Object::STATIC); geometry->addPrimitiveSet(drawArrays); osg::Geode* geode = new osg::Geode; geode->setDataVariance(osg::Object::STATIC); geode->addDrawable(geometry); osg::ref_ptr<osg::StateSet> stateSet = getLowLODStateSet(options); geode->setStateSet(stateSet.get()); transform.makeTranslate(toOsg(sphere.getCenter())); osg::MatrixTransform* matrixTransform = new osg::MatrixTransform(transform); matrixTransform->setDataVariance(osg::Object::STATIC); matrixTransform->addChild(geode); return matrixTransform; } osg::ref_ptr<osg::StateSet> ReaderWriterSPT::getLowLODStateSet(const osgDB::Options* options) const { osg::ref_ptr<osgDB::Options> localOptions; localOptions = static_cast<osgDB::Options*>(options->clone(osg::CopyOp())); localOptions->setObjectCacheHint(osgDB::Options::CACHE_ALL); osg::ref_ptr<osg::Object> object = osgDB::readRefObjectFile("state.spt", localOptions.get()); if (!dynamic_cast<osg::StateSet*>(object.get())) return 0; return static_cast<osg::StateSet*>(object.get()); } } // namespace simgear <commit_msg>spt: The bucket size case is already handled above.<commit_after>// ReaderWriterSPT.cxx -- Provide a paged database for flightgear scenery. // // Copyright (C) 2010 - 2013 Mathias Froehlich // // 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. // #ifdef HAVE_CONFIG_H # include <simgear_config.h> #endif #include "ReaderWriterSPT.hxx" #include <cassert> #include <osg/CullFace> #include <osg/PagedLOD> #include <osg/MatrixTransform> #include <osg/Texture2D> #include <osgDB/FileNameUtils> #include <osgDB/FileUtils> #include <osgDB/ReadFile> #include <simgear/scene/util/OsgMath.hxx> #include "BucketBox.hxx" namespace simgear { // Cull away tiles that we watch from downside struct ReaderWriterSPT::CullCallback : public osg::NodeCallback { virtual ~CullCallback() { } virtual void operator()(osg::Node* node, osg::NodeVisitor* nv) { const osg::BoundingSphere& nodeBound = node->getBound(); // If the bounding sphere of the node is empty, there is nothing to do if (!nodeBound.valid()) return; // Culling away tiles that we look at from the downside. // This is done by computing the maximum distance we can // see something from the current eyepoint. If the sphere // that is defined by this radius does no intersects the // nodes sphere, then this tile is culled away. // Computing this radius happens by two rectangular triangles: // Let r be the view point. rmin is the minimum radius we find // a ground surface we need to look above. rmax is the // maximum object radius we expect any object. // // d1 d2 // x----x----x // r\ rmin /rmax // \ | / // \ | / // \|/ // // The distance from the eyepoint to the point // where the line of sight is perpandicular to // the radius vector with minimal height is // d1 = sqrt(r^2 - rmin^2). // The distance from the point where the line of sight // is perpandicular to the radius vector with minimal height // to the highest possible object on earth with radius rmax is // d2 = sqrt(rmax^2 - rmin^2). // So the maximum distance we can see something on the earth // from a viewpoint r is // d = d1 + d2 // This is the equatorial earth radius minus 450m, // little lower than Dead Sea. float rmin = 6378137 - 450; float rmin2 = rmin*rmin; // This is the equatorial earth radius plus 9000m, // little higher than Mount Everest. float rmax = 6378137 + 9000; float rmax2 = rmax*rmax; // Check if we are looking from below any ground osg::Vec3 viewPoint = nv->getViewPoint(); // blow the viewpoint up to a spherical earth with equatorial radius: osg::Vec3 sphericViewPoint = viewPoint; sphericViewPoint[2] *= 1.0033641; float r2 = sphericViewPoint.length2(); if (r2 <= rmin2) return; // Due to this line of sight computation, the visible tiles // are limited to be within a sphere with radius d1 + d2. float d1 = sqrtf(r2 - rmin2); float d2 = sqrtf(rmax2 - rmin2); // Note that we again base the sphere around elliptic view point, // but use the radius from the spherical computation. if (!nodeBound.intersects(osg::BoundingSphere(viewPoint, d1 + d2))) return; traverse(node, nv); } }; ReaderWriterSPT::ReaderWriterSPT() { supportsExtension("spt", "SimGear paged terrain meta database."); } ReaderWriterSPT::~ReaderWriterSPT() { } const char* ReaderWriterSPT::className() const { return "simgear::ReaderWriterSPT"; } osgDB::ReaderWriter::ReadResult ReaderWriterSPT::readObject(const std::string& fileName, const osgDB::Options* options) const { // We get called with different extensions. To make sure search continues, // we need to return FILE_NOT_HANDLED in this case. if (osgDB::getLowerCaseFileExtension(fileName) != "spt") return ReadResult(ReadResult::FILE_NOT_HANDLED); if (fileName != "state.spt") return ReadResult(ReadResult::FILE_NOT_FOUND); osg::StateSet* stateSet = new osg::StateSet; stateSet->setAttributeAndModes(new osg::CullFace); std::string imageFileName = options->getPluginStringData("SimGear::FG_WORLD_TEXTURE"); if (imageFileName.empty()) { imageFileName = options->getPluginStringData("SimGear::FG_ROOT"); imageFileName = osgDB::concatPaths(imageFileName, "Textures"); imageFileName = osgDB::concatPaths(imageFileName, "Globe"); imageFileName = osgDB::concatPaths(imageFileName, "world.topo.bathy.200407.3x4096x2048.png"); } if (osg::Image* image = osgDB::readImageFile(imageFileName, options)) { osg::Texture2D* texture = new osg::Texture2D; texture->setImage(image); texture->setWrap(osg::Texture2D::WRAP_S, osg::Texture2D::REPEAT); texture->setWrap(osg::Texture2D::WRAP_T, osg::Texture2D::CLAMP); stateSet->setTextureAttributeAndModes(0, texture); } return stateSet; } osgDB::ReaderWriter::ReadResult ReaderWriterSPT::readNode(const std::string& fileName, const osgDB::Options* options) const { // The file name without path and without the spt extension std::string strippedFileName = osgDB::getStrippedName(fileName); if (strippedFileName == "earth") return ReadResult(createTree(BucketBox(-180, -90, 360, 180), options, true)); std::stringstream ss(strippedFileName); BucketBox bucketBox; ss >> bucketBox; if (ss.fail()) return ReadResult::FILE_NOT_FOUND; BucketBox bucketBoxList[2]; unsigned bucketBoxListSize = bucketBox.periodicSplit(bucketBoxList); if (bucketBoxListSize == 0) return ReadResult::FILE_NOT_FOUND; if (bucketBoxListSize == 1) return ReadResult(createTree(bucketBoxList[0], options, true)); assert(bucketBoxListSize == 2); osg::ref_ptr<osg::Group> group = new osg::Group; group->addChild(createTree(bucketBoxList[0], options, true)); group->addChild(createTree(bucketBoxList[1], options, true)); return ReadResult(group); } osg::ref_ptr<osg::Node> ReaderWriterSPT::createTree(const BucketBox& bucketBox, const osgDB::Options* options, bool topLevel) const { if (bucketBox.getIsBucketSize()) { std::string fileName; fileName = bucketBox.getBucket().gen_index_str() + std::string(".stg"); return osgDB::readRefNodeFile(fileName, options); } else if (!topLevel && bucketBox.getStartLevel() == 3) { // We want an other level of indirection for paging // Here we get about 12x12 deg tiles return createPagedLOD(bucketBox, options); } else if (!topLevel && bucketBox.getStartLevel() == 5) { // We want an other level of indirection for paging // Here we get about 2x2 deg tiles return createPagedLOD(bucketBox, options); } else if (!topLevel && bucketBox.getStartLevel() == 7) { // We want an other level of indirection for paging // Here we get about 0.5x0.5 deg tiles return createPagedLOD(bucketBox, options); } else { BucketBox bucketBoxList[100]; unsigned numTiles = bucketBox.getSubDivision(bucketBoxList, 100); if (numTiles == 0) return 0; if (numTiles == 1) return createTree(bucketBoxList[0], options, false); osg::ref_ptr<osg::Group> group = new osg::Group; for (unsigned i = 0; i < numTiles; ++i) { osg::ref_ptr<osg::Node> node = createTree(bucketBoxList[i], options, false); if (!node.valid()) continue; group->addChild(node.get()); } if (!group->getNumChildren()) return 0; return group; } } osg::ref_ptr<osg::Node> ReaderWriterSPT::createPagedLOD(const BucketBox& bucketBox, const osgDB::Options* options) const { osg::PagedLOD* pagedLOD = new osg::PagedLOD; pagedLOD->setCenterMode(osg::PagedLOD::USER_DEFINED_CENTER); SGSpheref sphere = bucketBox.getBoundingSphere(); pagedLOD->setCenter(toOsg(sphere.getCenter())); pagedLOD->setRadius(sphere.getRadius()); pagedLOD->setCullCallback(new CullCallback); osg::ref_ptr<osgDB::Options> localOptions; localOptions = static_cast<osgDB::Options*>(options->clone(osg::CopyOp())); // FIXME: // The particle systems have nodes with culling disabled. // PagedLOD nodes with childnodes like this will never expire. // So, for now switch them off. localOptions->setPluginStringData("SimGear::PARTICLESYSTEM", "OFF"); pagedLOD->setDatabaseOptions(localOptions.get()); float range = 3*sphere.getRadius(); // Add the static sea level textured shell osg::ref_ptr<osg::Node> tile = createSeaLevelTile(bucketBox, options); if (tile.valid()) pagedLOD->addChild(tile.get(), range, std::numeric_limits<float>::max()); // Add the paged file name that creates the subtrees on demand std::stringstream ss; ss << bucketBox << ".spt"; pagedLOD->setFileName(pagedLOD->getNumChildren(), ss.str()); pagedLOD->setRange(pagedLOD->getNumChildren(), 0.0, range); return pagedLOD; } osg::ref_ptr<osg::Node> ReaderWriterSPT::createSeaLevelTile(const BucketBox& bucketBox, const osgDB::Options* options) const { if (options->getPluginStringData("SimGear::FG_EARTH") != "ON") return 0; SGSpheref sphere = bucketBox.getBoundingSphere(); osg::Matrixd transform; transform.makeTranslate(toOsg(-sphere.getCenter())); osg::Vec3Array* vertices = new osg::Vec3Array; osg::Vec3Array* normals = new osg::Vec3Array; osg::Vec2Array* texCoords = new osg::Vec2Array; unsigned widthLevel = bucketBox.getWidthLevel(); unsigned heightLevel = bucketBox.getHeightLevel(); unsigned incx = bucketBox.getWidthIncrement(widthLevel + 2); incx = std::min(incx, bucketBox.getSize(0)); for (unsigned i = 0; incx != 0;) { unsigned incy = bucketBox.getHeightIncrement(heightLevel + 2); incy = std::min(incy, bucketBox.getSize(1)); for (unsigned j = 0; incy != 0;) { SGVec3f v[6], n[6]; SGVec2f t[6]; unsigned num = bucketBox.getTileTriangles(i, j, incx, incy, v, n, t); for (unsigned k = 0; k < num; ++k) { vertices->push_back(transform.preMult(toOsg(v[k]))); normals->push_back(toOsg(n[k])); texCoords->push_back(toOsg(t[k])); } j += incy; incy = std::min(incy, bucketBox.getSize(1) - j); } i += incx; incx = std::min(incx, bucketBox.getSize(0) - i); } osg::Vec4Array* colors = new osg::Vec4Array; colors->push_back(osg::Vec4(1, 1, 1, 1)); osg::Geometry* geometry = new osg::Geometry; geometry->setVertexArray(vertices); geometry->setNormalArray(normals); geometry->setNormalBinding(osg::Geometry::BIND_PER_VERTEX); geometry->setColorArray(colors); geometry->setColorBinding(osg::Geometry::BIND_OVERALL); geometry->setTexCoordArray(0, texCoords); osg::DrawArrays* drawArrays = new osg::DrawArrays(osg::DrawArrays::TRIANGLES, 0, vertices->size()); drawArrays->setDataVariance(osg::Object::STATIC); geometry->addPrimitiveSet(drawArrays); osg::Geode* geode = new osg::Geode; geode->setDataVariance(osg::Object::STATIC); geode->addDrawable(geometry); osg::ref_ptr<osg::StateSet> stateSet = getLowLODStateSet(options); geode->setStateSet(stateSet.get()); transform.makeTranslate(toOsg(sphere.getCenter())); osg::MatrixTransform* matrixTransform = new osg::MatrixTransform(transform); matrixTransform->setDataVariance(osg::Object::STATIC); matrixTransform->addChild(geode); return matrixTransform; } osg::ref_ptr<osg::StateSet> ReaderWriterSPT::getLowLODStateSet(const osgDB::Options* options) const { osg::ref_ptr<osgDB::Options> localOptions; localOptions = static_cast<osgDB::Options*>(options->clone(osg::CopyOp())); localOptions->setObjectCacheHint(osgDB::Options::CACHE_ALL); osg::ref_ptr<osg::Object> object = osgDB::readRefObjectFile("state.spt", localOptions.get()); if (!dynamic_cast<osg::StateSet*>(object.get())) return 0; return static_cast<osg::StateSet*>(object.get()); } } // namespace simgear <|endoftext|>
<commit_before>#include <cerrno> #include <cstdlib> #include <cstdio> #include <cstring> #include <csignal> #include <cassert> #include <sys/types.h> #include <sys/wait.h> #include <sys/time.h> #include <sys/resource.h> #include <fcntl.h> #include <unistd.h> #define NOFD -1 int report_fd, walltimelimit; volatile bool validator_first = false; volatile int val_pid = -1, user_pid = -1; volatile int user_status = -1, val_status = -1; volatile static rusage user_ru; volatile static rusage val_ru; double runtime(volatile rusage *ru) { if(ru == NULL) return 0; struct timeval tv; tv.tv_sec = ru->ru_utime.tv_sec + ru->ru_stime.tv_sec; tv.tv_usec = ru->ru_utime.tv_usec + ru->ru_stime.tv_usec; return (double)tv.tv_sec + (double)tv.tv_usec / 1000000.0; } void report(int val_status, double val_time, int user_status, double user_time) { FILE * fp = fdopen(report_fd, "w"); fprintf(fp, "%d %.6lf %d %.6lf %s", val_status, val_time, user_status, user_time, validator_first ? "validator" : "submission"); fclose(fp); } void walltime_handler(int) { // TODO: make this race-free and signal safe. Right now there's a race // between wait returning in main and the pid variables being set to -1, // and we call non-signal safe functions... // This is likely fine for problemtools, but not for real contest systems. // The easiest way to fix this would probably be to kill(-1, SIGKILL) in // this handler, set some sig_atomic_t variable, and let main() deal with // the aftermath. int u_stat = user_status, v_stat = val_status; double u_time = 0; // Check if validator has already quit while we were waiting for submission if (val_pid != -1 && wait4(val_pid, &v_stat, WNOHANG, (rusage*)&val_ru) != val_pid) { kill(val_pid, SIGTERM); } // Check submission resource usage and then kill it if (user_pid != -1 && wait4(user_pid, &u_stat, WNOHANG, (rusage*)&user_ru) != user_pid) { kill(user_pid, SIGKILL); } u_time = runtime(&user_ru); if (u_stat == -1) { u_stat = SIGUSR1; u_time = walltimelimit; } // If validator didn't yet give us something, assume WA if (v_stat == -1) v_stat = 43 << 8; report(v_stat, runtime(&val_ru), u_stat, u_time); exit(0); } /** Sets the FD_CLOEXEC flag on file descriptor fd to cloexec * * N.B. Will exit() on failure */ void set_cloexec(int fd, int cloexec) { int flags; /* Clear the FD_CLOEXEC flag on stdin */ flags = fcntl(fd, F_GETFD, 0); if(flags < 0) { perror("fcntl failed"); exit(EXIT_FAILURE); } if(cloexec) { flags |= FD_CLOEXEC; } else { flags &= ~FD_CLOEXEC; } if(fcntl(fd, F_SETFD, flags) == -1) { perror("fcntl failed"); exit(EXIT_FAILURE); } } /* execute returns PID of child process * * Forks and has the child execute args[0] with args as argument vector (so it * must follow the format for execvp, i.e. be NULL-terminated - you can use * args.c to handle it). The child process will have fd[0] for STDIN and fd[1] * for STDOUT. If the child should be left with default STDIN/STDOUT, set fd[0] * or fd[1] respectivly to NOFD. * * Will ulimit core to 0, will ulimit CPU time to cputime, or leave it * untouched if negative. * * NB: Will exit() on failure. */ int execute(char **args, int fdin, int fdout) { int pid; pid = fork(); if(pid == 0) { if(fdin != NOFD) { /* * In the unlikely event that fd[1] is STDIN, we have to move it * before we copy fdin to STDIN. */ if(fdout == STDIN_FILENO) { int temp; temp = dup(fdout); if(temp < 0) { perror("dup failed"); exit(EXIT_FAILURE); } fdout = temp; /* Don't need to close, will be over-dup2:ed */ } if(fdin != STDIN_FILENO) { if(dup2(fdin, STDIN_FILENO) != STDIN_FILENO) { perror("dup2 failed"); exit(EXIT_FAILURE); } if(close(fdin)) { perror("close failed"); exit(EXIT_FAILURE); } } set_cloexec(STDIN_FILENO, 0); } if(fdout != NOFD) { if(fdout != STDOUT_FILENO) { if(dup2(fdout, STDOUT_FILENO) != STDOUT_FILENO) { perror("dup2 failed"); exit(EXIT_FAILURE); } if(close(fdout)) { perror("close failed"); exit(EXIT_FAILURE); } } set_cloexec(STDOUT_FILENO, 0); } if(execvp(args[0], args) == -1) { perror("execvp failed"); exit(EXIT_FAILURE); } } else if(pid < 0) { perror("fork failed"); exit(EXIT_FAILURE); } else { return pid; } /* Unreachable */ assert(!"Unreachable code"); return 0; } /* makepipe * * Creates a pipe and assigns the filedescriptors to fd[0] and fd[1] and then * sets close-on-exec on both ends of the pipe. * * NB: will exit() on failure. */ void makepipe(int fd[2]) { int i; if(pipe(fd)) { perror("pipe failed"); exit(EXIT_FAILURE); } /* * It's extremely unlikely by now, but just in case someone is crazy enough * to extend GET_FD and SET_FD with more flags it's good to handle it. A bit * more sloppy would be to just do F_SETFD with FD_CLOEXEC but that could * potentially clear some new flag. */ for(i = 0; i < 2; i++) { set_cloexec(fd[i], 1); } } int main(int argc, char **argv) { if(argc < 2 || sscanf(argv[1], "%d", &report_fd) != 1 || report_fd < 0) { fprintf(stderr, "Bad first argument, expected file descriptor\n"); exit(EXIT_FAILURE); } if(argc < 3 || sscanf(argv[2], "%d", &walltimelimit) != 1 || walltimelimit < 0) { fprintf(stderr, "Bad second argument, expected wall time limit (0 to disable)\n"); exit(EXIT_FAILURE); } char **val_argv = new char*[argc], **user_argv = new char*[argc]; int val_argc = 0, user_argc = 0; for(int i = 3; i < argc && strcmp(argv[i], ";") != 0; ++i) val_argv[val_argc++] = argv[i]; val_argv[val_argc] = NULL; for(int i = 3 + val_argc + 1; i < argc; ++i) { user_argv[user_argc++] = argv[i]; } user_argv[user_argc] = NULL; if(val_argc == 0 || user_argc == 0) { fprintf(stderr, "Empty validator or user argument list\n"); exit(EXIT_FAILURE); } int fromval[2], fromuser[2]; makepipe(fromval); makepipe(fromuser); set_cloexec(report_fd, 1); val_pid = execute(val_argv, fromuser[0], fromval[1]); user_pid = execute(user_argv, fromval[0], fromuser[1]); if(walltimelimit) { signal(SIGALRM, walltime_handler); alarm(walltimelimit); } close(fromval[0]); close(fromuser[0]); /* * We intentionally wait with closing the write ends of the pipes until * the process that owns them stops, to be more sure about which process * terminates first. If we didn't, SIGPIPEs might make both processes * die almost simultaneously. */ int remaining = 2; while (remaining > 0) { int status; struct rusage ru; int r = wait4(-1, &status, 0, &ru); if (r == -1) { perror("wait failed"); exit(1); } if (r == val_pid) { if (remaining == 2) validator_first = true; val_status = status; memcpy((void*)&val_ru, &ru, sizeof(rusage)); val_pid = -1; remaining--; close(fromval[1]); } if (r == user_pid) { // In case of broken pipes, let validator decide user_status = (WIFSIGNALED(status) && WTERMSIG(status) == SIGPIPE ? 0 : status); memcpy((void*)&val_ru, &ru, sizeof(rusage)); user_pid = -1; remaining--; close(fromuser[1]); } } report(val_status, runtime(&val_ru), user_status, runtime(&user_ru)); return 0; } <commit_msg>Avoid validator->submission SIGPIPEs<commit_after>#include <cerrno> #include <cstdlib> #include <cstdio> #include <cstring> #include <csignal> #include <cassert> #include <sys/types.h> #include <sys/wait.h> #include <sys/time.h> #include <sys/resource.h> #include <fcntl.h> #include <unistd.h> #define NOFD -1 int report_fd, walltimelimit; volatile bool validator_first = false; volatile int val_pid = -1, user_pid = -1; volatile int user_status = -1, val_status = -1; volatile static rusage user_ru; volatile static rusage val_ru; double runtime(volatile rusage *ru) { if(ru == NULL) return 0; struct timeval tv; tv.tv_sec = ru->ru_utime.tv_sec + ru->ru_stime.tv_sec; tv.tv_usec = ru->ru_utime.tv_usec + ru->ru_stime.tv_usec; return (double)tv.tv_sec + (double)tv.tv_usec / 1000000.0; } void report(int val_status, double val_time, int user_status, double user_time) { FILE * fp = fdopen(report_fd, "w"); fprintf(fp, "%d %.6lf %d %.6lf %s", val_status, val_time, user_status, user_time, validator_first ? "validator" : "submission"); fclose(fp); } void walltime_handler(int) { // TODO: make this race-free and signal safe. Right now there's a race // between wait returning in main and the pid variables being set to -1, // and we call non-signal safe functions... // This is likely fine for problemtools, but not for real contest systems. // The easiest way to fix this would probably be to kill(-1, SIGKILL) in // this handler, set some sig_atomic_t variable, and let main() deal with // the aftermath. int u_stat = user_status, v_stat = val_status; double u_time = 0; // Check if validator has already quit while we were waiting for submission if (val_pid != -1 && wait4(val_pid, &v_stat, WNOHANG, (rusage*)&val_ru) != val_pid) { kill(val_pid, SIGTERM); } // Check submission resource usage and then kill it if (user_pid != -1 && wait4(user_pid, &u_stat, WNOHANG, (rusage*)&user_ru) != user_pid) { kill(user_pid, SIGKILL); } u_time = runtime(&user_ru); if (u_stat == -1) { u_stat = SIGUSR1; u_time = walltimelimit; } // If validator didn't yet give us something, assume WA if (v_stat == -1) v_stat = 43 << 8; report(v_stat, runtime(&val_ru), u_stat, u_time); exit(0); } /** Sets the FD_CLOEXEC flag on file descriptor fd to cloexec * * N.B. Will exit() on failure */ void set_cloexec(int fd, int cloexec) { int flags; /* Clear the FD_CLOEXEC flag on stdin */ flags = fcntl(fd, F_GETFD, 0); if(flags < 0) { perror("fcntl failed"); exit(EXIT_FAILURE); } if(cloexec) { flags |= FD_CLOEXEC; } else { flags &= ~FD_CLOEXEC; } if(fcntl(fd, F_SETFD, flags) == -1) { perror("fcntl failed"); exit(EXIT_FAILURE); } } /* execute returns PID of child process * * Forks and has the child execute args[0] with args as argument vector (so it * must follow the format for execvp, i.e. be NULL-terminated - you can use * args.c to handle it). The child process will have fd[0] for STDIN and fd[1] * for STDOUT. If the child should be left with default STDIN/STDOUT, set fd[0] * or fd[1] respectivly to NOFD. * * Will ulimit core to 0, will ulimit CPU time to cputime, or leave it * untouched if negative. * * NB: Will exit() on failure. */ int execute(char **args, int fdin, int fdout) { int pid; pid = fork(); if(pid == 0) { if(fdin != NOFD) { /* * In the unlikely event that fd[1] is STDIN, we have to move it * before we copy fdin to STDIN. */ if(fdout == STDIN_FILENO) { int temp; temp = dup(fdout); if(temp < 0) { perror("dup failed"); exit(EXIT_FAILURE); } fdout = temp; /* Don't need to close, will be over-dup2:ed */ } if(fdin != STDIN_FILENO) { if(dup2(fdin, STDIN_FILENO) != STDIN_FILENO) { perror("dup2 failed"); exit(EXIT_FAILURE); } if(close(fdin)) { perror("close failed"); exit(EXIT_FAILURE); } } set_cloexec(STDIN_FILENO, 0); } if(fdout != NOFD) { if(fdout != STDOUT_FILENO) { if(dup2(fdout, STDOUT_FILENO) != STDOUT_FILENO) { perror("dup2 failed"); exit(EXIT_FAILURE); } if(close(fdout)) { perror("close failed"); exit(EXIT_FAILURE); } } set_cloexec(STDOUT_FILENO, 0); } if(execvp(args[0], args) == -1) { perror("execvp failed"); exit(EXIT_FAILURE); } } else if(pid < 0) { perror("fork failed"); exit(EXIT_FAILURE); } else { return pid; } /* Unreachable */ assert(!"Unreachable code"); return 0; } /* makepipe * * Creates a pipe and assigns the filedescriptors to fd[0] and fd[1] and then * sets close-on-exec on both ends of the pipe. * * NB: will exit() on failure. */ void makepipe(int fd[2]) { int i; if(pipe(fd)) { perror("pipe failed"); exit(EXIT_FAILURE); } /* * It's extremely unlikely by now, but just in case someone is crazy enough * to extend GET_FD and SET_FD with more flags it's good to handle it. A bit * more sloppy would be to just do F_SETFD with FD_CLOEXEC but that could * potentially clear some new flag. */ for(i = 0; i < 2; i++) { set_cloexec(fd[i], 1); } } int main(int argc, char **argv) { if(argc < 2 || sscanf(argv[1], "%d", &report_fd) != 1 || report_fd < 0) { fprintf(stderr, "Bad first argument, expected file descriptor\n"); exit(EXIT_FAILURE); } if(argc < 3 || sscanf(argv[2], "%d", &walltimelimit) != 1 || walltimelimit < 0) { fprintf(stderr, "Bad second argument, expected wall time limit (0 to disable)\n"); exit(EXIT_FAILURE); } char **val_argv = new char*[argc], **user_argv = new char*[argc]; int val_argc = 0, user_argc = 0; for(int i = 3; i < argc && strcmp(argv[i], ";") != 0; ++i) val_argv[val_argc++] = argv[i]; val_argv[val_argc] = NULL; for(int i = 3 + val_argc + 1; i < argc; ++i) { user_argv[user_argc++] = argv[i]; } user_argv[user_argc] = NULL; if(val_argc == 0 || user_argc == 0) { fprintf(stderr, "Empty validator or user argument list\n"); exit(EXIT_FAILURE); } int fromval[2], fromuser[2]; makepipe(fromval); makepipe(fromuser); set_cloexec(report_fd, 1); val_pid = execute(val_argv, fromuser[0], fromval[1]); user_pid = execute(user_argv, fromval[0], fromuser[1]); if(walltimelimit) { signal(SIGALRM, walltime_handler); alarm(walltimelimit); } /* * We intentionally wait with closing the write ends of the fromuser/ * fromval pipes until the process that owns them stops, to be more sure * about which process terminates first. If we don't, and process A exits * while process B is (erroneously) trying to read, process B might read * EOF and crash/terminate almost simultaneously as A, and wait(2) might * then return process B's PID instead of A's. * * (We do eventually want B to EOF/crash/terminate rather than waiting * for the wall-time limit, just to finish things earlier, we just don't * want it race with the other process. This holds doubly if B is the * grader, which is expected to deal nicely with EOFs.) * * We never close the read end of the validator -> user channel -- it only * serves to give the grader Judge Error if it doesn't setup up a signal * handler for SIGPIPE, and we do want submissions that exit early to be * accepted. * * The read end of the user -> validator channel we do close, to trigger * SIGPIPEs when the user writes to a validator which has exited. * (Currently we treat that the same as exiting with code 0, though it * would also make sense to make it an error.) */ close(fromuser[0]); int remaining = 2; while (remaining > 0) { int status; struct rusage ru; int r = wait4(-1, &status, 0, &ru); if (r == -1) { perror("wait failed"); exit(1); } if (r == val_pid) { if (remaining == 2) validator_first = true; val_status = status; memcpy((void*)&val_ru, &ru, sizeof(rusage)); val_pid = -1; remaining--; close(fromval[1]); } if (r == user_pid) { // In case of broken pipes, let validator decide user_status = (WIFSIGNALED(status) && WTERMSIG(status) == SIGPIPE ? 0 : status); memcpy((void*)&val_ru, &ru, sizeof(rusage)); user_pid = -1; remaining--; close(fromuser[1]); } } report(val_status, runtime(&val_ru), user_status, runtime(&user_ru)); return 0; } <|endoftext|>
<commit_before>/******************************************************************************/ /* */ /* b b c p . C */ /* */ /* (c) 2010 by the Board of Trustees of the Leland Stanford, Jr., University */ /* All Rights Reserved. See bbcp_Version.C for complete License Terms */ /* Produced by Andrew Hanushevsky for Stanford University under contract */ /* DE-AC03-76-SFO0515 with the Department of Energy */ /******************************************************************************/ /* bbcp provides a secure fast parallel copy utility. See bbcp_Config.C for the actual list of options. The general syntax is: bbcp [options] inspec outspec */ /******************************************************************************/ /* i n c l u d e f i l e s */ /******************************************************************************/ #include <unistd.h> #include <ctype.h> #include <errno.h> #include <stdlib.h> #include <string.h> #include <strings.h> #include <stdio.h> #include <sys/param.h> #include "bbcp_Args.h" #include "bbcp_Config.h" #include "bbcp_Debug.h" #include "bbcp_FileSpec.h" #include "bbcp_Headers.h" #include "bbcp_LogFile.h" #include "bbcp_Node.h" #include "bbcp_ProcMon.h" #include "bbcp_Protocol.h" #include "bbcp_System.h" #include "bbcp_Timer.h" /******************************************************************************/ /* L O C A L D E F I N I T I O N S */ /******************************************************************************/ #define Same(s1, s2) (s1 == s2 || (s1 && s2 && !strcmp(s1, s2))) /******************************************************************************/ /* G l o b a l V a r i a b l e s */ /******************************************************************************/ extern bbcp_Config bbcp_Config; extern bbcp_BuffPool bbcp_BuffPool; extern bbcp_System bbcp_OS; /******************************************************************************/ /* m a i n */ /******************************************************************************/ main(int argc, char *argv[], char *envp[]) { bbcp_Node *Source, *Sink; bbcp_Protocol Protocol; bbcp_FileSpec *fsp, *psp, *sfs, *tfs; int retc; int TotFiles = 0; long long TotBytes = 0; double xRate; bbcp_Timer Elapsed_Timer; const char *xType; // Process configuration file // bbcp_OS.EnvP = envp; if (bbcp_Config.ConfigInit(argc, argv)) exit(1); // Process the arguments // bbcp_Config.Arguments(argc, argv); // Process final source/sink actions here // if (bbcp_Config.Options & (bbcp_SRC | bbcp_SNK)) {int retc; bbcp_ProcMon theAgent; theAgent.Start(bbcp_OS.getGrandP()); {bbcp_Node SS_Node; retc = (bbcp_Config.Options & bbcp_SRC ? Protocol.Process(&SS_Node) : Protocol.Request(&SS_Node)); } exit(retc); } // Do some debugging here // Elapsed_Timer.Start(); if (bbcp_Debug.Trace > 2) bbcp_Config.Display(); // Allocate the source and sink node and common protocol // Source = new bbcp_Node; Sink = new bbcp_Node; tfs = bbcp_Config.snkSpec; // Allocate the log file // if (bbcp_Config.Logfn) {bbcp_Config.MLog = new bbcp_LogFile(); if (bbcp_Config.MLog->Open(bbcp_Config.Logfn)) exit(5); } // Grab all source files for each particular user/host and copy them // retc = 0; while(!retc && (psp = bbcp_Config.srcSpec)) {fsp = psp->next; while(fsp && Same(fsp->username, psp->username) && Same(fsp->hostname, psp->hostname)) {psp = fsp; fsp = fsp->next;} psp->next = 0; sfs = bbcp_Config.srcSpec; bbcp_Config.srcSpec = fsp; if (bbcp_Config.Options & bbcp_CON2SRC) retc = Protocol.Schedule(Source, sfs, (char *)bbcp_Config.SrcXeq, (char *)bbcp_Config.SrcArg, Sink, tfs, (char *)bbcp_Config.SnkXeq, (char *)bbcp_Config.SnkArg, Sink); else retc = Protocol.Schedule(Sink, tfs, (char *)bbcp_Config.SnkXeq, (char *)bbcp_Config.SnkArg, Source, sfs, (char *)bbcp_Config.SrcXeq, (char *)bbcp_Config.SrcArg, Sink); TotFiles += Sink->TotFiles; TotBytes += Sink->TotBytes; } // All done // delete Source; delete Sink; // Report final statistics if wanted // DEBUG("Ending; rc=" <<retc <<" files=" <<TotFiles <<" bytes=" <<TotBytes); if (bbcp_Config.Options & bbcp_VERBOSE && !retc && TotFiles && TotBytes) {double ttime; char buff[128]; Elapsed_Timer.Stop(); Elapsed_Timer.Report(ttime); xRate = ((double)TotBytes)/ttime*1000.0; xType = bbcp_Config::Scale(xRate); sprintf(buff, "%.1f %sB/s", xRate, xType); cerr <<TotFiles <<(TotFiles != 1 ? " files" : " file"); cerr <<" copied at effectively " <<buff <<endl; } if (bbcp_Config.MLog) delete bbcp_Config.MLog; exit(retc); } <commit_msg>Add missing return type specifier to main<commit_after>/******************************************************************************/ /* */ /* b b c p . C */ /* */ /* (c) 2010 by the Board of Trustees of the Leland Stanford, Jr., University */ /* All Rights Reserved. See bbcp_Version.C for complete License Terms */ /* Produced by Andrew Hanushevsky for Stanford University under contract */ /* DE-AC03-76-SFO0515 with the Department of Energy */ /******************************************************************************/ /* bbcp provides a secure fast parallel copy utility. See bbcp_Config.C for the actual list of options. The general syntax is: bbcp [options] inspec outspec */ /******************************************************************************/ /* i n c l u d e f i l e s */ /******************************************************************************/ #include <unistd.h> #include <ctype.h> #include <errno.h> #include <stdlib.h> #include <string.h> #include <strings.h> #include <stdio.h> #include <sys/param.h> #include "bbcp_Args.h" #include "bbcp_Config.h" #include "bbcp_Debug.h" #include "bbcp_FileSpec.h" #include "bbcp_Headers.h" #include "bbcp_LogFile.h" #include "bbcp_Node.h" #include "bbcp_ProcMon.h" #include "bbcp_Protocol.h" #include "bbcp_System.h" #include "bbcp_Timer.h" /******************************************************************************/ /* L O C A L D E F I N I T I O N S */ /******************************************************************************/ #define Same(s1, s2) (s1 == s2 || (s1 && s2 && !strcmp(s1, s2))) /******************************************************************************/ /* G l o b a l V a r i a b l e s */ /******************************************************************************/ extern bbcp_Config bbcp_Config; extern bbcp_BuffPool bbcp_BuffPool; extern bbcp_System bbcp_OS; /******************************************************************************/ /* m a i n */ /******************************************************************************/ int main(int argc, char *argv[], char *envp[]) { bbcp_Node *Source, *Sink; bbcp_Protocol Protocol; bbcp_FileSpec *fsp, *psp, *sfs, *tfs; int retc; int TotFiles = 0; long long TotBytes = 0; double xRate; bbcp_Timer Elapsed_Timer; const char *xType; // Process configuration file // bbcp_OS.EnvP = envp; if (bbcp_Config.ConfigInit(argc, argv)) exit(1); // Process the arguments // bbcp_Config.Arguments(argc, argv); // Process final source/sink actions here // if (bbcp_Config.Options & (bbcp_SRC | bbcp_SNK)) {int retc; bbcp_ProcMon theAgent; theAgent.Start(bbcp_OS.getGrandP()); {bbcp_Node SS_Node; retc = (bbcp_Config.Options & bbcp_SRC ? Protocol.Process(&SS_Node) : Protocol.Request(&SS_Node)); } exit(retc); } // Do some debugging here // Elapsed_Timer.Start(); if (bbcp_Debug.Trace > 2) bbcp_Config.Display(); // Allocate the source and sink node and common protocol // Source = new bbcp_Node; Sink = new bbcp_Node; tfs = bbcp_Config.snkSpec; // Allocate the log file // if (bbcp_Config.Logfn) {bbcp_Config.MLog = new bbcp_LogFile(); if (bbcp_Config.MLog->Open(bbcp_Config.Logfn)) exit(5); } // Grab all source files for each particular user/host and copy them // retc = 0; while(!retc && (psp = bbcp_Config.srcSpec)) {fsp = psp->next; while(fsp && Same(fsp->username, psp->username) && Same(fsp->hostname, psp->hostname)) {psp = fsp; fsp = fsp->next;} psp->next = 0; sfs = bbcp_Config.srcSpec; bbcp_Config.srcSpec = fsp; if (bbcp_Config.Options & bbcp_CON2SRC) retc = Protocol.Schedule(Source, sfs, (char *)bbcp_Config.SrcXeq, (char *)bbcp_Config.SrcArg, Sink, tfs, (char *)bbcp_Config.SnkXeq, (char *)bbcp_Config.SnkArg, Sink); else retc = Protocol.Schedule(Sink, tfs, (char *)bbcp_Config.SnkXeq, (char *)bbcp_Config.SnkArg, Source, sfs, (char *)bbcp_Config.SrcXeq, (char *)bbcp_Config.SrcArg, Sink); TotFiles += Sink->TotFiles; TotBytes += Sink->TotBytes; } // All done // delete Source; delete Sink; // Report final statistics if wanted // DEBUG("Ending; rc=" <<retc <<" files=" <<TotFiles <<" bytes=" <<TotBytes); if (bbcp_Config.Options & bbcp_VERBOSE && !retc && TotFiles && TotBytes) {double ttime; char buff[128]; Elapsed_Timer.Stop(); Elapsed_Timer.Report(ttime); xRate = ((double)TotBytes)/ttime*1000.0; xType = bbcp_Config::Scale(xRate); sprintf(buff, "%.1f %sB/s", xRate, xType); cerr <<TotFiles <<(TotFiles != 1 ? " files" : " file"); cerr <<" copied at effectively " <<buff <<endl; } if (bbcp_Config.MLog) delete bbcp_Config.MLog; exit(retc); } <|endoftext|>
<commit_before>/*************************************************************************** * Copyright (c) 2016, Johan Mabille, Sylvain Corlay and Wolf Vollprecht * * * * Distributed under the terms of the BSD 3-Clause License. * * * * The full license is in the file LICENSE, distributed with this software. * ****************************************************************************/ #include "gtest/gtest.h" #include "xtensor/xarray.hpp" #include "xtensor/xcomplex.hpp" #include "xtensor/xfunctor_view.hpp" #include "xtensor/xio.hpp" #include "xtensor/xnoalias.hpp" namespace xt { using namespace std::complex_literals; template <class T> struct nooblean_proxy { nooblean_proxy(T& ref) : m_ref(ref) { } operator bool() { return !m_ref; }; nooblean_proxy& operator=(bool rhs) { m_ref = !rhs; return *this; } T& m_ref; }; template <class T> struct xproxy_inner_types<nooblean_proxy<T>> { // T is used for constness deduction using proxy = nooblean_proxy<T>; using reference = nooblean_proxy<T>; using pointer = nooblean_proxy<T>; }; struct nooblean { using value_type = bool; using reference = nooblean_proxy<bool>; using const_reference = nooblean_proxy<const bool>; using pointer = bool*; using const_pointer = bool*; template <class value_type, class requested_type> using simd_return_type = xsimd::simd_return_type<value_type, requested_type>; const_reference operator()(const bool& in) const { return in; } reference operator()(bool& in) { return in; } /** cant implement yet -- need to figure out bool loading in xsimd **/ // template <class align, class requested_type, std::size_t N, class E> // auto proxy_simd_load(const E& expr, std::size_t n) const // { // using simd_value_type = xsimd::simd_type<value_type>; // return !expr.template load_simd<align, requested_type, N>(n); // } }; TEST(xfunctor_adaptor, basic) { using nooblean_adaptor = xt::xfunctor_adaptor<nooblean, xarray<bool>&>; xarray<bool> vals = {{1, 1, 1, 0, 0}, {1, 0, 1, 0, 1}}; xarray<bool> xvals = !vals; nooblean_adaptor aptvals(vals); EXPECT_EQ(aptvals, xvals); auto begin = aptvals.storage_begin(); *begin = true; EXPECT_EQ(bool(*begin), true); EXPECT_EQ(vals(0, 0), false); aptvals(0, 0) = false; EXPECT_EQ(vals(0, 0), true); EXPECT_EQ(bool(aptvals(0, 0)), false); bool execd = false; if (aptvals(0, 0) == false) { execd = true; } EXPECT_TRUE(execd); auto rhs1 = xt::xarray<bool>({true, false, true}); aptvals = rhs1; EXPECT_EQ(rhs1, aptvals); EXPECT_EQ(!rhs1, vals); } TEST(xfunctor_adaptor, iterator) { using nooblean_adaptor = xt::xfunctor_adaptor<nooblean, xarray<bool>&>; xarray<bool> vals = {{1, 1, 1, 0, 0}, {1, 0, 1, 0, 1}}; xarray<bool> xvals = !vals; nooblean_adaptor aptvals(vals); auto it_adapt = aptvals.begin(); auto it_ref = xvals.begin(); for (; it_adapt != aptvals.end(); ++it_adapt, ++it_ref) { EXPECT_EQ(static_cast<bool>(*it_adapt), *it_ref); } } TEST(xfunctor_adaptor, lhs_assignment) { using container_type = xarray<std::complex<double>>; container_type e = {{3.0 , 1.0 + 1.0i}, {1.0 - 1.0i, 2.0 }}; // Assigning to a xfunctor_adaptor, which has a container semantics, resizes // the underlying container. auto radaptor = xt::xoffset_adaptor<container_type&, double, 0>(e); xt::xtensor<double, 1> rhs = {4.0, 5.0}; radaptor = rhs; EXPECT_EQ(e.dimension(), 1u); EXPECT_EQ(xtl::real(e(0)), 4.0); EXPECT_EQ(xtl::real(e(1)), 5.0); } #if defined(XTENSOR_USE_XSIMD) && XSIMD_X86_INSTR_SET >= XSIMD_X86_AVX_VERSION TEST(xfunctor_adaptor, simd) { xarray<std::complex<double>> e = {{3.0 , 1.0 + 1.0i}, {1.0 - 1.0i, 2.0 }}; auto iview = xt::imag(e); auto loaded_batch = iview.template load_simd<xsimd::aligned_mode, double, 4>(0); EXPECT_TRUE(xsimd::all(xsimd::batch<double, 4>(0, 1, -1, 0) == loaded_batch)); auto newbatch = loaded_batch + 5; iview.template store_simd<xsimd::aligned_mode>(0, newbatch); xarray<std::complex<double>> exp1 = {{3.0 + 5.0i, 1.0 + 6.0i}, {1.0 + 4.0i, 2.0 + 5.0i }}; EXPECT_EQ(exp1, e); auto rview = xt::real(e); auto loaded_batch2 = rview.template load_simd<xsimd::aligned_mode, double, 4>(0); EXPECT_TRUE(xsimd::all(xsimd::batch<double, 4>(3, 1, 1, 2) == loaded_batch2)); newbatch = loaded_batch2 + 5; rview.template store_simd<xsimd::aligned_mode>(0, newbatch); xarray<std::complex<double>> exp2 = {{8.0 + 5.0i, 6.0 + 6.0i}, {6.0 + 4.0i, 7.0 + 5.0i }}; EXPECT_EQ(exp2, e); auto f = xt::sin(xt::imag(e)); auto b = f.load_simd<xsimd::aligned_mode>(0); static_cast<void>(b); using assign_to_view = xassign_traits<decltype(iview), decltype(f)>; EXPECT_TRUE(assign_to_view::convertible_types()); EXPECT_TRUE(assign_to_view::simd_size()); EXPECT_FALSE(assign_to_view::forbid_simd()); EXPECT_TRUE(assign_to_view::simd_assign()); } #endif } <commit_msg>fix test on avx512<commit_after>/*************************************************************************** * Copyright (c) 2016, Johan Mabille, Sylvain Corlay and Wolf Vollprecht * * * * Distributed under the terms of the BSD 3-Clause License. * * * * The full license is in the file LICENSE, distributed with this software. * ****************************************************************************/ #include "gtest/gtest.h" #include "xtensor/xarray.hpp" #include "xtensor/xcomplex.hpp" #include "xtensor/xfunctor_view.hpp" #include "xtensor/xio.hpp" #include "xtensor/xnoalias.hpp" namespace xt { using namespace std::complex_literals; template <class T> struct nooblean_proxy { nooblean_proxy(T& ref) : m_ref(ref) { } operator bool() { return !m_ref; }; nooblean_proxy& operator=(bool rhs) { m_ref = !rhs; return *this; } T& m_ref; }; template <class T> struct xproxy_inner_types<nooblean_proxy<T>> { // T is used for constness deduction using proxy = nooblean_proxy<T>; using reference = nooblean_proxy<T>; using pointer = nooblean_proxy<T>; }; struct nooblean { using value_type = bool; using reference = nooblean_proxy<bool>; using const_reference = nooblean_proxy<const bool>; using pointer = bool*; using const_pointer = bool*; template <class value_type, class requested_type> using simd_return_type = xsimd::simd_return_type<value_type, requested_type>; const_reference operator()(const bool& in) const { return in; } reference operator()(bool& in) { return in; } /** cant implement yet -- need to figure out bool loading in xsimd **/ // template <class align, class requested_type, std::size_t N, class E> // auto proxy_simd_load(const E& expr, std::size_t n) const // { // using simd_value_type = xsimd::simd_type<value_type>; // return !expr.template load_simd<align, requested_type, N>(n); // } }; TEST(xfunctor_adaptor, basic) { using nooblean_adaptor = xt::xfunctor_adaptor<nooblean, xarray<bool>&>; xarray<bool> vals = {{1, 1, 1, 0, 0}, {1, 0, 1, 0, 1}}; xarray<bool> xvals = !vals; nooblean_adaptor aptvals(vals); EXPECT_EQ(aptvals, xvals); auto begin = aptvals.storage_begin(); *begin = true; EXPECT_EQ(bool(*begin), true); EXPECT_EQ(vals(0, 0), false); aptvals(0, 0) = false; EXPECT_EQ(vals(0, 0), true); EXPECT_EQ(bool(aptvals(0, 0)), false); bool execd = false; if (aptvals(0, 0) == false) { execd = true; } EXPECT_TRUE(execd); auto rhs1 = xt::xarray<bool>({true, false, true}); aptvals = rhs1; EXPECT_EQ(rhs1, aptvals); EXPECT_EQ(!rhs1, vals); } TEST(xfunctor_adaptor, iterator) { using nooblean_adaptor = xt::xfunctor_adaptor<nooblean, xarray<bool>&>; xarray<bool> vals = {{1, 1, 1, 0, 0}, {1, 0, 1, 0, 1}}; xarray<bool> xvals = !vals; nooblean_adaptor aptvals(vals); auto it_adapt = aptvals.begin(); auto it_ref = xvals.begin(); for (; it_adapt != aptvals.end(); ++it_adapt, ++it_ref) { EXPECT_EQ(static_cast<bool>(*it_adapt), *it_ref); } } TEST(xfunctor_adaptor, lhs_assignment) { using container_type = xarray<std::complex<double>>; container_type e = {{3.0 , 1.0 + 1.0i}, {1.0 - 1.0i, 2.0 }}; // Assigning to a xfunctor_adaptor, which has a container semantics, resizes // the underlying container. auto radaptor = xt::xoffset_adaptor<container_type&, double, 0>(e); xt::xtensor<double, 1> rhs = {4.0, 5.0}; radaptor = rhs; EXPECT_EQ(e.dimension(), 1u); EXPECT_EQ(xtl::real(e(0)), 4.0); EXPECT_EQ(xtl::real(e(1)), 5.0); } #if defined(XTENSOR_USE_XSIMD) && XSIMD_X86_INSTR_SET >= XSIMD_X86_AVX_VERSION && XSIMD_X86_INSTR_SET < XSIMD_X86_AVX512_VERSION TEST(xfunctor_adaptor, simd) { xarray<std::complex<double>> e = {{3.0 , 1.0 + 1.0i}, {1.0 - 1.0i, 2.0 }}; auto iview = xt::imag(e); auto loaded_batch = iview.template load_simd<xsimd::aligned_mode, double, 4>(0); EXPECT_TRUE(xsimd::all(xsimd::batch<double, 4>(0, 1, -1, 0) == loaded_batch)); auto newbatch = loaded_batch + 5; iview.template store_simd<xsimd::aligned_mode>(0, newbatch); xarray<std::complex<double>> exp1 = {{3.0 + 5.0i, 1.0 + 6.0i}, {1.0 + 4.0i, 2.0 + 5.0i }}; EXPECT_EQ(exp1, e); auto rview = xt::real(e); auto loaded_batch2 = rview.template load_simd<xsimd::aligned_mode, double, 4>(0); EXPECT_TRUE(xsimd::all(xsimd::batch<double, 4>(3, 1, 1, 2) == loaded_batch2)); newbatch = loaded_batch2 + 5; rview.template store_simd<xsimd::aligned_mode>(0, newbatch); xarray<std::complex<double>> exp2 = {{8.0 + 5.0i, 6.0 + 6.0i}, {6.0 + 4.0i, 7.0 + 5.0i }}; EXPECT_EQ(exp2, e); auto f = xt::sin(xt::imag(e)); auto b = f.load_simd<xsimd::aligned_mode>(0); static_cast<void>(b); using assign_to_view = xassign_traits<decltype(iview), decltype(f)>; EXPECT_TRUE(assign_to_view::convertible_types()); EXPECT_TRUE(assign_to_view::simd_size()); EXPECT_FALSE(assign_to_view::forbid_simd()); EXPECT_TRUE(assign_to_view::simd_assign()); } #endif } <|endoftext|>
<commit_before>#ifndef __INCLUDED_NET11_UTIL_HPP__ #define __INCLUDED_NET11_UTIL_HPP__ #pragma once #include <stdint.h> #include <functional> #ifdef _MSC_VER #include <windows.h> #else #include <unistd.h> #endif namespace net11 { // a sink is a data receiver class sink; // buffer is a utility class built to pass along data as a memory fifo class buffer; // a utility sink that reads a full line class line_parser_sink; // a utility sink that parses RFC 822 headers class header_parser_sink; // utility functions to create producers from a string or vector template<typename T> std::function<bool(buffer &)> make_data_producer(T * in_data); template<typename T> std::function<bool(buffer &)> make_data_producer(T &in_data); // a utility function to give up a slice of cpu time void yield(); class buffer { int m_cap; // the total number of bytes in this buffer int m_bottom; // the bottom index, ie the first used data element int m_top; // the top index, the first unused data element char *m_data; // the actual data public: buffer(int capacity) { m_cap=capacity; m_bottom=0; m_top=0; m_data=new char[capacity]; } ~buffer() { delete m_data; } // returns the number of bytes corrently in the buffer inline int usage() { return m_top-m_bottom; } // returns the number of bytes available to produce as a flat array int direct_avail() { return m_cap-m_top; } // returns the total number of bytes available to produce int total_avail() { return (m_cap-m_top)+(m_bottom); } // compacts the buffer to maximize the flatly available bytes int compact() { if (m_bottom==0) return direct_avail(); int sz=usage(); std::memmove(m_data,m_data+m_bottom,sz); m_bottom=0; m_top=sz; return direct_avail(); } // consumes one byte from the currently available bytes inline char consume() { if (m_bottom>=m_top) throw std::out_of_range("no bytes to consume in buffer"); return m_data[m_bottom++]; } // returns the pointer to a number of bytes to consume directly. const char* to_consume() { return m_data+m_bottom; } // tells the buffer how many bytes was consumed void consumed(int amount) { if (usage()<amount || amount<0) throw std::invalid_argument("underflow"); m_bottom+=amount; } // adds a byte to the buffer inline void produce(char c) { if (direct_avail()<1) { if (compact()<1) { throw std::out_of_range("no bytes available in buffer"); } } m_data[m_top++]=c; } // adds as many bytes as possible from the source to this buffer void produce(buffer &source) { // how much do we want to copy if possible? int to_copy=source.usage(); // now check the actual number of bytes we can copy if (to_copy>total_avail()) to_copy=total_avail(); produce(source,to_copy); } // copy the number of bytes from the source void produce(buffer &source,int to_copy) { // if we can fit it straight away copy it directly if (direct_avail()<to_copy) { // we can't copy it directly, then compact first before copy if (compact()<to_copy) { // still not enough space, fault here! throw std::invalid_argument("not enough space to take the copied bytes"); } } // now copy the amount we can take std::memcpy(to_produce(),source.to_consume(),to_copy); produced(to_copy); source.consumed(to_copy); } // returns a the pointer to the free bytes to be written char* to_produce() { return m_data+m_top; } // tell the buffer how many bytes were actually written void produced(int amount) { if (direct_avail()<amount) throw std::invalid_argument("overflow"); m_top+=amount; } // convert the buffer contents to a string std::string to_string() { std::string out; for (int i=m_bottom;i<m_top;i++) { out.push_back(m_data[i]); } return out; } }; template<typename T> std::function<bool(buffer &)> make_data_producer(T * in_data) { std::shared_ptr<int> off(new int); std::shared_ptr<T> data(in_data); *off=0; // return the actual producer function that writes out the contents on request return [data,off](buffer &ob){ int dataleft=data->size()-*off; // dl is how much we have left to send int outleft=ob.compact(); int to_copy=dataleft<outleft?dataleft:outleft; std::memcpy(ob.to_produce(),data->data()+*off,to_copy); ob.produced(to_copy); *off+=to_copy; return *off!=data->size(); }; } template<typename T> std::function<bool(buffer &)> make_data_producer(T &in_data) { return make_data_producer(new T(in_data)); } class sink { public: // implement this function to make a working sink virtual bool drain(buffer &buf)=0; }; class line_parser_sink : public sink { std::string out; // the output string const char *term; // the line terminator int tl; // length of the terminator string int szmax; // the maximum number of bytes in a line std::function<bool(std::string&)> on_line; public: line_parser_sink( const char *in_term, int in_max, std::function<bool(std::string&)> in_on_line ): term(in_term), szmax(in_max), on_line(in_on_line) { tl=strlen(term); } virtual bool drain(buffer &buf) { size_t sz=out.size(); while(buf.usage()) { if (sz>=szmax) { return false; } //std::cout<<"Pre:["<<out<<"]["<<buf.to_string()<<"]\n"; out.push_back(buf.consume()); //std::cout<<"Post:["<<out<<"]["<<buf.to_string()<<"]\n"; sz++; if (sz>tl) { if (!memcmp(out.data()+sz-tl,term,tl)) { out.resize(sz-tl); //std::cout<<"Line:"<<out<<":\n"; bool rv=on_line(out); out.resize(0); return rv; } } } return true; } }; class header_parser_sink : public sink { enum headerstate { firstlinestart=0, linestart, testemptyline, inkey, postkeyskip, invalue, postvalue }; headerstate state; std::string k; std::string v; int count; int maxsz; int (*filter)(int c); std::function<bool(std::string&,std::string&)> on_header; std::function<bool(const char *err)> on_fin; public: header_parser_sink( int in_maxsz, int (*in_filter)(int c), std::function<bool(std::string&,std::string&)> in_on_header, std::function<bool(const char *err)> in_on_fin ): state(firstlinestart), count(0), maxsz(in_maxsz), filter(in_filter), on_header(in_on_header), on_fin(in_on_fin) {} virtual bool drain(buffer &buf) { // pre-existing error condition, just return. if (count==-1) return false; while(buf.usage()) { if (count>=maxsz) { on_fin("Error, headers too large"); count=-1; return false; } char c=buf.consume(); count++; switch(state) { case firstlinestart : case linestart : if (c==13) { if (state!=firstlinestart) { on_header(k,v); k.clear(); v.clear(); } // empty line in progress state=testemptyline; continue; } else if (c==10) { on_fin("spurios LF"); count=-1; return false; } if (state!=firstlinestart) { if (isspace(c)) { state=invalue; v.push_back(c); continue; } on_header(k,v); k.clear(); v.clear(); } if (isspace(c)) continue; state=inkey; if (filter) c = filter(c); k.push_back(c); continue; case testemptyline : if (c==10) { // empty line encountered, we're finished with the data bool rv=on_fin(nullptr); k.clear(); v.clear(); state=firstlinestart; count=0; return rv; } else { on_fin("cr but no lf in empty headerline"); count=-1; return false; } case inkey : if (c==':') { state=postkeyskip; continue; } else { if (filter) c=filter(c); k.push_back(c); continue; } case postkeyskip : if (isspace(c)) { continue; } else { state=invalue; v.push_back(c); continue; } case invalue : if (c==13) { state=postvalue; continue; } else { v.push_back(c); continue; } case postvalue : if (c==10) { state=linestart; continue; } else { on_fin("cr but no lf in headerline"); count=-1; return false; } default: printf("headerparser unhandled state:%d\n",state); exit(-1); } } return true; } }; void yield() { // TODO: IOCP/KEVENT... #ifdef _MSC_VER Sleep(1); #else usleep(10000); #endif } } #endif // __INCLUDED_NET11_UTIL_HPP__ <commit_msg>Added an event scheduler to net11/util.hpp<commit_after>#ifndef __INCLUDED_NET11_UTIL_HPP__ #define __INCLUDED_NET11_UTIL_HPP__ #pragma once #include <stdint.h> #include <functional> #include <time.h> #ifdef _MSC_VER #include <windows.h> #else #include <unistd.h> #include <sys/time.h> #endif namespace net11 { // a sink is a data receiver class sink; // buffer is a utility class built to pass along data as a memory fifo class buffer; // a utility sink that reads a full line class line_parser_sink; // a utility sink that parses RFC 822 headers class header_parser_sink; // utility functions to create producers from a string or vector template<typename T> std::function<bool(buffer &)> make_data_producer(T * in_data); template<typename T> std::function<bool(buffer &)> make_data_producer(T &in_data); // a utility function to give up a slice of cpu time void yield(); class buffer { int m_cap; // the total number of bytes in this buffer int m_bottom; // the bottom index, ie the first used data element int m_top; // the top index, the first unused data element char *m_data; // the actual data public: buffer(int capacity) { m_cap=capacity; m_bottom=0; m_top=0; m_data=new char[capacity]; } ~buffer() { delete m_data; } // returns the number of bytes corrently in the buffer inline int usage() { return m_top-m_bottom; } // returns the number of bytes available to produce as a flat array int direct_avail() { return m_cap-m_top; } // returns the total number of bytes available to produce int total_avail() { return (m_cap-m_top)+(m_bottom); } // compacts the buffer to maximize the flatly available bytes int compact() { if (m_bottom==0) return direct_avail(); int sz=usage(); std::memmove(m_data,m_data+m_bottom,sz); m_bottom=0; m_top=sz; return direct_avail(); } // consumes one byte from the currently available bytes inline char consume() { if (m_bottom>=m_top) throw std::out_of_range("no bytes to consume in buffer"); return m_data[m_bottom++]; } // returns the pointer to a number of bytes to consume directly. const char* to_consume() { return m_data+m_bottom; } // tells the buffer how many bytes was consumed void consumed(int amount) { if (usage()<amount || amount<0) throw std::invalid_argument("underflow"); m_bottom+=amount; } // adds a byte to the buffer inline void produce(char c) { if (direct_avail()<1) { if (compact()<1) { throw std::out_of_range("no bytes available in buffer"); } } m_data[m_top++]=c; } // adds as many bytes as possible from the source to this buffer void produce(buffer &source) { // how much do we want to copy if possible? int to_copy=source.usage(); // now check the actual number of bytes we can copy if (to_copy>total_avail()) to_copy=total_avail(); produce(source,to_copy); } // copy the number of bytes from the source void produce(buffer &source,int to_copy) { // if we can fit it straight away copy it directly if (direct_avail()<to_copy) { // we can't copy it directly, then compact first before copy if (compact()<to_copy) { // still not enough space, fault here! throw std::invalid_argument("not enough space to take the copied bytes"); } } // now copy the amount we can take std::memcpy(to_produce(),source.to_consume(),to_copy); produced(to_copy); source.consumed(to_copy); } // returns a the pointer to the free bytes to be written char* to_produce() { return m_data+m_top; } // tell the buffer how many bytes were actually written void produced(int amount) { if (direct_avail()<amount) throw std::invalid_argument("overflow"); m_top+=amount; } // convert the buffer contents to a string std::string to_string() { std::string out; for (int i=m_bottom;i<m_top;i++) { out.push_back(m_data[i]); } return out; } }; template<typename T> std::function<bool(buffer &)> make_data_producer(T * in_data) { std::shared_ptr<int> off(new int); std::shared_ptr<T> data(in_data); *off=0; // return the actual producer function that writes out the contents on request return [data,off](buffer &ob){ int dataleft=data->size()-*off; // dl is how much we have left to send int outleft=ob.compact(); int to_copy=dataleft<outleft?dataleft:outleft; std::memcpy(ob.to_produce(),data->data()+*off,to_copy); ob.produced(to_copy); *off+=to_copy; return *off!=data->size(); }; } template<typename T> std::function<bool(buffer &)> make_data_producer(T &in_data) { return make_data_producer(new T(in_data)); } class sink { public: // implement this function to make a working sink virtual bool drain(buffer &buf)=0; }; class line_parser_sink : public sink { std::string out; // the output string const char *term; // the line terminator int tl; // length of the terminator string int szmax; // the maximum number of bytes in a line std::function<bool(std::string&)> on_line; public: line_parser_sink( const char *in_term, int in_max, std::function<bool(std::string&)> in_on_line ): term(in_term), szmax(in_max), on_line(in_on_line) { tl=strlen(term); } virtual bool drain(buffer &buf) { size_t sz=out.size(); while(buf.usage()) { if (sz>=szmax) { return false; } //std::cout<<"Pre:["<<out<<"]["<<buf.to_string()<<"]\n"; out.push_back(buf.consume()); //std::cout<<"Post:["<<out<<"]["<<buf.to_string()<<"]\n"; sz++; if (sz>tl) { if (!memcmp(out.data()+sz-tl,term,tl)) { out.resize(sz-tl); //std::cout<<"Line:"<<out<<":\n"; bool rv=on_line(out); out.resize(0); return rv; } } } return true; } }; class header_parser_sink : public sink { enum headerstate { firstlinestart=0, linestart, testemptyline, inkey, postkeyskip, invalue, postvalue }; headerstate state; std::string k; std::string v; int count; int maxsz; int (*filter)(int c); std::function<bool(std::string&,std::string&)> on_header; std::function<bool(const char *err)> on_fin; public: header_parser_sink( int in_maxsz, int (*in_filter)(int c), std::function<bool(std::string&,std::string&)> in_on_header, std::function<bool(const char *err)> in_on_fin ): state(firstlinestart), count(0), maxsz(in_maxsz), filter(in_filter), on_header(in_on_header), on_fin(in_on_fin) {} virtual bool drain(buffer &buf) { // pre-existing error condition, just return. if (count==-1) return false; while(buf.usage()) { if (count>=maxsz) { on_fin("Error, headers too large"); count=-1; return false; } char c=buf.consume(); count++; switch(state) { case firstlinestart : case linestart : if (c==13) { if (state!=firstlinestart) { on_header(k,v); k.clear(); v.clear(); } // empty line in progress state=testemptyline; continue; } else if (c==10) { on_fin("spurios LF"); count=-1; return false; } if (state!=firstlinestart) { if (isspace(c)) { state=invalue; v.push_back(c); continue; } on_header(k,v); k.clear(); v.clear(); } if (isspace(c)) continue; state=inkey; if (filter) c = filter(c); k.push_back(c); continue; case testemptyline : if (c==10) { // empty line encountered, we're finished with the data bool rv=on_fin(nullptr); k.clear(); v.clear(); state=firstlinestart; count=0; return rv; } else { on_fin("cr but no lf in empty headerline"); count=-1; return false; } case inkey : if (c==':') { state=postkeyskip; continue; } else { if (filter) c=filter(c); k.push_back(c); continue; } case postkeyskip : if (isspace(c)) { continue; } else { state=invalue; v.push_back(c); continue; } case invalue : if (c==13) { state=postvalue; continue; } else { v.push_back(c); continue; } case postvalue : if (c==10) { state=linestart; continue; } else { on_fin("cr but no lf in headerline"); count=-1; return false; } default: printf("headerparser unhandled state:%d\n",state); exit(-1); } } return true; } }; void yield() { // TODO: IOCP/KEVENT... #ifdef _MSC_VER Sleep(1); #else usleep(10000); #endif } uint64_t current_time_millis() { #ifdef _MSC_VER SYSTEMTIME st; GetSystemTime(&st); return st.wMilliseconds+(1000*(uint64_t)time(0)); #else struct timeval tv; gettimeofday(&tv,NULL); return (tv.tv_usec/1000)+(1000*(uint64_t)time(0)); #endif } class scheduler { struct event { //uint64_t next; uint64_t period; // for recurring events std::function<void()> once; std::function<bool()> recurring; event(std::function<void()> f):period(0),once(f) {} event(uint64_t in_period,std::function<bool()> f):period(in_period),recurring(f) {} }; std::multimap<uint64_t,event> events; public: void timeout(uint64_t timeout,std::function<void()> f) { uint64_t event_time=current_time_millis()+timeout; events.emplace(event_time,event(f)); } void interval(uint64_t timeout,uint64_t period,std::function<bool()> f) { uint64_t event_time=current_time_millis()+timeout; events.emplace(event_time,event(period,f)); } void poll() { uint64_t now=current_time_millis(); while(!events.empty()) { auto bi=events.begin(); if (bi->first>now) break; if (bi->second.period) { if (bi->second.recurring()) { uint64_t next=bi->first+bi->second.period; events.emplace(next,event(bi->second.period,bi->second.recurring)); bi=events.begin(); } } else { bi->second.once(); } events.erase(bi); } } }; } #endif // __INCLUDED_NET11_UTIL_HPP__ <|endoftext|>
<commit_before><commit_msg>bug fixes<commit_after><|endoftext|>
<commit_before>/* * RandomNumber.cc * * Copyright (C) 2015 Linas Vepstas * * Author: Linas Vepstas <linasvepstas@gmail.com> January 2009 * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License v3 as * published by the Free Software Foundation and including the * exceptions * at http://opencog.org/wiki/Licenses * * 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 Affero General Public * License * along with this program; if not, write to: * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <opencog/util/mt19937ar.h> #include <opencog/atomspace/AtomSpace.h> #include <opencog/atoms/NumberNode.h> #include "RandomNumber.h" using namespace opencog; static MT19937RandGen randy(616432); void RandomNumberLink::init() { if (_outgoing.size() != 2) throw SyntaxException(TRACE_INFO, "Expecting a numerical min ad max"); } RandomNumberLink::RandomNumberLink(const HandleSeq& oset, TruthValuePtr tv, AttentionValuePtr av) : FunctionLink(RANDOM_NUMBER_LINK, oset, tv, av) { init(); } RandomNumberLink::RandomNumberLink(Link &l) : FunctionLink(l) { // Type must be as expected Type tscope = l.getType(); if (not classserver().isA(tscope, RANDOM_NUMBER_LINK)) { const std::string& tname = classserver().getTypeName(tscope); throw InvalidParamException(TRACE_INFO, "Expecting an RandomNumberLink, got %s", tname.c_str()); } init(); } // --------------------------------------------------------------- // Pattern matching hack. The pattern matcher returns sets of atoms; // if that set contains numbers or something numeric, then unwrap it. static NumberNodePtr unwrap_set(Handle h) { if (SET_LINK == h->getType()) { LinkPtr lp(LinkCast(h)); if (1 != lp->getArity()) throw SyntaxException(TRACE_INFO, "Don't know how to do arithmetic with this: %s", h->toString().c_str()); h = lp->getOutgoingAtom(0); } NumberNodePtr na(NumberNodeCast(h)); if (nullptr == na) throw SyntaxException(TRACE_INFO, "Don't know how to do arithmetic with this: %s", h->toString().c_str()); return na; } Handle RandomNumberLink::execute(AtomSpace * as) const { NumberNodePtr nmin(unwrap_set(_outgoing[0])); NumberNodePtr nmax(unwrap_set(_outgoing[1])); double cept = nmin->get_value(); double slope = nmax->get_value() - cept; double ary = slope * randy.randdouble() + cept; // XXX This is probably wrong ... if the as is null, we should // probably use the atomspace that this link is in, right? // We need to make a decision here and in many other places... if (NULL == as) return Handle(createNumberNode(ary)); return as->add_atom(createNumberNode(ary)); } /* ===================== END OF FILE ===================== */ <commit_msg>Make message more informative<commit_after>/* * RandomNumber.cc * * Copyright (C) 2015 Linas Vepstas * * Author: Linas Vepstas <linasvepstas@gmail.com> January 2009 * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License v3 as * published by the Free Software Foundation and including the * exceptions * at http://opencog.org/wiki/Licenses * * 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 Affero General Public * License * along with this program; if not, write to: * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <opencog/util/mt19937ar.h> #include <opencog/atomspace/AtomSpace.h> #include <opencog/atoms/NumberNode.h> #include "RandomNumber.h" using namespace opencog; static MT19937RandGen randy(616432); void RandomNumberLink::init() { if (_outgoing.size() != 2) throw SyntaxException(TRACE_INFO, "Expecting a numerical min and max; got %s", toString().c_str()); } RandomNumberLink::RandomNumberLink(const HandleSeq& oset, TruthValuePtr tv, AttentionValuePtr av) : FunctionLink(RANDOM_NUMBER_LINK, oset, tv, av) { init(); } RandomNumberLink::RandomNumberLink(Link &l) : FunctionLink(l) { // Type must be as expected Type tscope = l.getType(); if (not classserver().isA(tscope, RANDOM_NUMBER_LINK)) { const std::string& tname = classserver().getTypeName(tscope); throw InvalidParamException(TRACE_INFO, "Expecting an RandomNumberLink, got %s", tname.c_str()); } init(); } // --------------------------------------------------------------- // Pattern matching hack. The pattern matcher returns sets of atoms; // if that set contains numbers or something numeric, then unwrap it. static NumberNodePtr unwrap_set(Handle h) { if (SET_LINK == h->getType()) { LinkPtr lp(LinkCast(h)); if (1 != lp->getArity()) throw SyntaxException(TRACE_INFO, "Don't know how to do arithmetic with this: %s", h->toString().c_str()); h = lp->getOutgoingAtom(0); } NumberNodePtr na(NumberNodeCast(h)); if (nullptr == na) throw SyntaxException(TRACE_INFO, "Don't know how to do arithmetic with this: %s", h->toString().c_str()); return na; } Handle RandomNumberLink::execute(AtomSpace * as) const { NumberNodePtr nmin(unwrap_set(_outgoing[0])); NumberNodePtr nmax(unwrap_set(_outgoing[1])); double cept = nmin->get_value(); double slope = nmax->get_value() - cept; double ary = slope * randy.randdouble() + cept; // XXX This is probably wrong ... if the as is null, we should // probably use the atomspace that this link is in, right? // We need to make a decision here and in many other places... if (NULL == as) return Handle(createNumberNode(ary)); return as->add_atom(createNumberNode(ary)); } /* ===================== END OF FILE ===================== */ <|endoftext|>
<commit_before>#include "features.h" #include <fstream> // Variables for features computation #define HIST_SIZE 100 Features &Features::getInstance() { static Features instance; return instance; } Features::Features() : sizeElementArray(0) { sizeElementArray += 3*HIST_SIZE; // Histogram size sizeElementArray += NB_MAJOR_COLORS_EXTRACT*3; // Major colors loadMachineLearning(); } float Features::computeDistance(const FeaturesElement &elem1, const FeaturesElement &elem2) { return 0.0; } void Features::extractArray(const float *array, const size_t sizeArray, vector<FeaturesElement> &listFeatures) { // No offset if(array == nullptr) { return; } size_t currentId = 0; // No offset for(size_t numberElem = (sizeArray - currentId) / sizeElementArray ; // No offset currently numberElem > 0 ; --numberElem) { listFeatures.push_back(FeaturesElement()); FeaturesElement &currentElem = listFeatures.back(); // Histogram for(size_t channelId = 0 ; channelId < 3 ; ++channelId) { currentElem.histogramChannels.at(channelId).create(1,100,CV_32FC3); // TODO: Check order x,y !!!!!!! for(size_t i = 0 ; i < HIST_SIZE ; ++i) { currentElem.histogramChannels.at(channelId).at<float>(i) = array[currentId]; ++currentId; } } // Major colors for(size_t i = 0 ; i < NB_MAJOR_COLORS_EXTRACT ; ++i) { for(size_t j = 0 ; j < 3 ; ++j)// Channel number { currentElem.majorColors.at(i).color[j] = array[currentId]; ++currentId; } } } cout << listFeatures.size() << endl; } void Features::loadMachineLearning() { // Loading file FileStorage fileTraining("../../Data/Received/training.yml", FileStorage::READ); if(!fileTraining.isOpened()) { cout << "Error: cannot open the training file" << endl; exit(0); } Mat trainingData; Mat trainingClasses; fileTraining["trainingData"] >> trainingData; fileTraining["trainingClasses"] >> trainingClasses; fileTraining.release(); // Training CvSVMParams param = CvSVMParams(); param.svm_type = CvSVM::C_SVC; param.kernel_type = CvSVM::RBF; //CvSVM::RBF, CvSVM::LINEAR ... param.degree = 0; // for poly param.gamma = 20; // for poly/rbf/sigmoid param.coef0 = 0; // for poly/sigmoid param.C = 7; // for CV_SVM_C_SVC, CV_SVM_EPS_SVR and CV_SVM_NU_SVR param.nu = 0.0; // for CV_SVM_NU_SVC, CV_SVM_ONE_CLASS, and CV_SVM_NU_SVR param.p = 0.0; // for CV_SVM_EPS_SVR param.class_weights = NULL; // for CV_SVM_C_SVC param.term_crit.type = CV_TERMCRIT_ITER + CV_TERMCRIT_EPS; param.term_crit.max_iter = 1000; param.term_crit.epsilon = 1e-6; svm.train_auto(trainingData, trainingClasses, cv::Mat(), cv::Mat(), param); cout << "Training complete." << endl; } <commit_msg>Bug correction: Wrong histogram channel dimention Feature distance computation<commit_after>#include "features.h" #include <fstream> // Variables for features computation #define HIST_SIZE 100 Features &Features::getInstance() { static Features instance; return instance; } Features::Features() : sizeElementArray(0) { sizeElementArray += 3*HIST_SIZE; // Histogram size sizeElementArray += NB_MAJOR_COLORS_EXTRACT*3; // Major colors loadMachineLearning(); } float Features::computeDistance(const FeaturesElement &elem1, const FeaturesElement &elem2) { const int dimentionFeatureVector = 3 // Histogram + NB_MAJOR_COLORS_KEEP; // Major colors Mat rowFeatureVector = cv::Mat::ones(1, dimentionFeatureVector, CV_32FC1); int currentIndexFeature = 0;// Usefull if I change the order or remove a feature (don't need to change all the index) // Histogram rowFeatureVector.at<float>(0, currentIndexFeature+0) = compareHist(elem1.histogramChannels.at(0), elem2.histogramChannels.at(0), CV_COMP_BHATTACHARYYA); rowFeatureVector.at<float>(0, currentIndexFeature+1) = compareHist(elem1.histogramChannels.at(1), elem2.histogramChannels.at(1), CV_COMP_BHATTACHARYYA); rowFeatureVector.at<float>(0, currentIndexFeature+2) = compareHist(elem1.histogramChannels.at(2), elem2.histogramChannels.at(2), CV_COMP_BHATTACHARYYA); currentIndexFeature += 3; // Major Colors // Compute only with the most weigthed on for (size_t i = 0; i < NB_MAJOR_COLORS_KEEP; ++i) { float minDist = norm(elem1.majorColors.at(i).color - elem2.majorColors.front().color); float dist = 0.0; for (size_t j = 0; j < NB_MAJOR_COLORS_KEEP; ++j) { dist = norm(elem1.majorColors.at(i).color - elem2.majorColors.at(j).color); if(dist < minDist) { minDist = dist; } } rowFeatureVector.at<float>(0,currentIndexFeature) = minDist; currentIndexFeature++; } // TODO: Add feature: camera id ; Add feature: time // Feature Scaling return svm.predict(rowFeatureVector); } void Features::extractArray(const float *array, const size_t sizeArray, vector<FeaturesElement> &listFeatures) { // No offset if(array == nullptr) { return; } size_t currentId = 0; // No offset for(size_t numberElem = (sizeArray - currentId) / sizeElementArray ; // No offset currently numberElem > 0 ; --numberElem) { listFeatures.push_back(FeaturesElement()); FeaturesElement &currentElem = listFeatures.back(); // Histogram for(size_t channelId = 0 ; channelId < 3 ; ++channelId) { currentElem.histogramChannels.at(channelId).create(1,100,CV_32F); // TODO: Check order x,y !!!!!!! for(size_t i = 0 ; i < HIST_SIZE ; ++i) { currentElem.histogramChannels.at(channelId).at<float>(i) = array[currentId]; ++currentId; } } // Major colors for(size_t i = 0 ; i < NB_MAJOR_COLORS_EXTRACT ; ++i) { for(size_t j = 0 ; j < 3 ; ++j)// Channel number { currentElem.majorColors.at(i).color[j] = array[currentId]; ++currentId; } } } cout << listFeatures.size() << endl; } void Features::loadMachineLearning() { // Loading file FileStorage fileTraining("../../Data/Received/training.yml", FileStorage::READ); if(!fileTraining.isOpened()) { cout << "Error: cannot open the training file" << endl; exit(0); } Mat trainingData; Mat trainingClasses; fileTraining["trainingData"] >> trainingData; fileTraining["trainingClasses"] >> trainingClasses; fileTraining.release(); // Training CvSVMParams param = CvSVMParams(); param.svm_type = CvSVM::C_SVC; param.kernel_type = CvSVM::RBF; //CvSVM::RBF, CvSVM::LINEAR ... param.degree = 0; // for poly param.gamma = 20; // for poly/rbf/sigmoid param.coef0 = 0; // for poly/sigmoid param.C = 7; // for CV_SVM_C_SVC, CV_SVM_EPS_SVR and CV_SVM_NU_SVR param.nu = 0.0; // for CV_SVM_NU_SVC, CV_SVM_ONE_CLASS, and CV_SVM_NU_SVR param.p = 0.0; // for CV_SVM_EPS_SVR param.class_weights = NULL; // for CV_SVM_C_SVC param.term_crit.type = CV_TERMCRIT_ITER + CV_TERMCRIT_EPS; param.term_crit.max_iter = 1000; param.term_crit.epsilon = 1e-6; svm.train_auto(trainingData, trainingClasses, cv::Mat(), cv::Mat(), param); cout << "Training complete." << endl; } <|endoftext|>
<commit_before>#define BOOST_TEST_MODULE VizTest #include <boost/test/included/unit_test.hpp> #include <Eigen/Geometry> #include "StandaloneVisualizer.hpp" #include <maps/grid/MLSMap.hpp> #include "../tools/GeneratePointclouds.hpp" using namespace ::maps::grid; BOOST_AUTO_TEST_CASE(mls_simulate_LIDAR) { // GridConfig conf(150, 150, 0.1, 0.1, -7.5, -7.5); Eigen::Vector2d res(0.125, 0.125); Vector2ui numCells(200, 200); MLSConfig mls_config; mls_config.updateModel = MLSConfig::SLOPE; // mls_config.updateModel = MLSConfig::KALMAN; mls_config.gapSize = 0.125f; mls_config.useNegativeInformation = true; MLSMapSloped *mls = new MLSMapSloped(numCells, res, mls_config); /** Translate the local frame (offset) **/ mls->getLocalFrame().translation() << 0.5*mls->getSize(), 0; /** Equivalent to translate the grid in opposite direction **/ //Eigen::Vector3d offset_grid; //offset_grid << -0.5*mls->getSize(), 0.00; //mls->translate(offset_grid); typedef Eigen::Hyperplane<double, 3> Plane; maps::LIDARSimulator lidar(Eigen::VectorXd::LinSpaced(32, -16*M_PI/180, +16*M_PI/180), Eigen::VectorXd::LinSpaced(360, -M_PI, +M_PI)); // maps::LIDARSimulator lidar(Eigen::VectorXd::Constant(2, 0.0), Eigen::VectorXd::LinSpaced(30, -M_PI, +M_PI)); std::vector<Plane> scene; { Eigen::Quaterniond q; q.coeffs().setRandom(); q.normalize(); for(int i=0; i<3; ++i) { scene.push_back(Plane(q * Eigen::Vector3d::Unit(i), -2.0)); scene.push_back(Plane(q * Eigen::Vector3d::Unit(i), 2.0)); } } StandaloneVisualizer app; Eigen::ArrayXXd ranges; PointCloud pointcloud; Eigen::Affine3d trafo; trafo.setIdentity(); int loop = 0; while (app.wait(1000)) { if(++loop & 1023) continue; trafo.translation().setRandom(); Eigen::Quaterniond q; q.coeffs().setRandom(); q.normalize(); trafo.linear() = q.toRotationMatrix(); // std::cout << trafo.matrix() << std::endl; lidar.getRanges(ranges, scene, trafo, &pointcloud); mls->mergePointCloud(pointcloud, trafo, false); app.updateData(*mls); } } <commit_msg>measure timing of mergePointCloud in unit test<commit_after>#define BOOST_TEST_MODULE VizTest #include <boost/test/included/unit_test.hpp> #include <Eigen/Geometry> #include "StandaloneVisualizer.hpp" #include <maps/grid/MLSMap.hpp> #include "../tools/GeneratePointclouds.hpp" using namespace ::maps::grid; #include <base/TimeMark.hpp> BOOST_AUTO_TEST_CASE(mls_simulate_LIDAR) { // GridConfig conf(150, 150, 0.1, 0.1, -7.5, -7.5); Eigen::Vector2d res(0.125, 0.125); Vector2ui numCells(200, 200); MLSConfig mls_config; mls_config.updateModel = MLSConfig::SLOPE; // mls_config.updateModel = MLSConfig::KALMAN; mls_config.gapSize = 0.125f; mls_config.useNegativeInformation = true; MLSMapSloped *mls = new MLSMapSloped(numCells, res, mls_config); /** Translate the local frame (offset) **/ mls->getLocalFrame().translation() << 0.5*mls->getSize(), 0; /** Equivalent to translate the grid in opposite direction **/ //Eigen::Vector3d offset_grid; //offset_grid << -0.5*mls->getSize(), 0.00; //mls->translate(offset_grid); typedef Eigen::Hyperplane<double, 3> Plane; maps::LIDARSimulator lidar(Eigen::VectorXd::LinSpaced(32, -16*M_PI/180, +16*M_PI/180), Eigen::VectorXd::LinSpaced(360, -M_PI, +M_PI)); // maps::LIDARSimulator lidar(Eigen::VectorXd::Constant(2, 0.0), Eigen::VectorXd::LinSpaced(30, -M_PI, +M_PI)); std::vector<Plane> scene; { Eigen::Quaterniond q; q.coeffs().setRandom(); q.normalize(); for(int i=0; i<3; ++i) { scene.push_back(Plane(q * Eigen::Vector3d::Unit(i), -2.0)); scene.push_back(Plane(q * Eigen::Vector3d::Unit(i), 2.0)); } } StandaloneVisualizer app; Eigen::ArrayXXd ranges; PointCloud pointcloud; Eigen::Affine3d trafo; trafo.setIdentity(); int loop = 0; while (app.wait(1000)) { if(++loop & 1023) continue; trafo.translation().setRandom(); Eigen::Quaterniond q; q.coeffs().setRandom(); q.normalize(); trafo.linear() = q.toRotationMatrix(); // std::cout << trafo.matrix() << std::endl; lidar.getRanges(ranges, scene, trafo, &pointcloud); base::TimeMark timer("mls->mergePointCloud"); mls->mergePointCloud(pointcloud, trafo, false); std::cout << timer << std::endl; app.updateData(*mls); } } <|endoftext|>
<commit_before>#include "libadb.h" #include "adb_prot.h" #include "rxx.h" str dbrec_to_str (ptr<dbrec> dbr, int i) { //we aren't storing a null terminator. // add it here or the conversion grabs trailing garbage char buf[128]; int ncpy = (dbr->len > 127) ? 127 : dbr->len; memcpy (buf, dbr->value, dbr->len); buf[ncpy] = 0; // cache:abc03313ff rxx m("^([^!]+)!([0-9a-f]+)", "m"); m.search (buf); assert (m.success ()); return m[i]; } chordID dbrec_to_id (ptr<dbrec> dbr) { str id = dbrec_to_str (dbr, 2); chordID ret (id, 16); return ret; } str dbrec_to_name (ptr<dbrec> dbr) { str name = dbrec_to_str(dbr, 1); return name; } ptr<dbrec> id_to_dbrec (chordID key, str name_space) { //pad out all keys to 20 bytes so that they sort correctly str keystr = strbuf () << key; while (keystr.len () < 20) keystr = strbuf () << "0" << keystr; str c = strbuf () << name_space << "!" << keystr; return New refcounted<dbrec> (c.cstr (), c.len ()); } adb::adb (str sock_name, str name) : name_space (name) { int fd = unixsocket_connect (sock_name); if (fd < 0) { fatal ("adb_connect: Error connecting to %s: %s\n", sock_name.cstr (), strerror (errno)); } c = aclnt::alloc (axprt_unix::alloc (fd, 1024*1025), adb_program_1); } void adb::store (chordID key, str data, cbi cb) { adb_storearg arg; arg.key = key; arg.name = name_space; arg.data.setsize (data.len ()); memcpy (arg.data.base (), data.cstr (), data.len ()); adb_status *res = New adb_status (); c->call (ADBPROC_STORE, &arg, res, wrap (this, &adb::store_cb, res, cb)); return; } void adb::store_cb (adb_status *res, cbi cb, clnt_stat err) { if (cb) if (err || !res) cb (err); else cb (*res); delete res; } void adb::fetch (chordID key, cb_fetch cb) { adb_fetcharg arg; arg.key = key; arg.name = name_space; adb_fetchres *res = New adb_fetchres (ADB_OK); c->call (ADBPROC_FETCH, &arg, res, wrap (this, &adb::fetch_cb, res, key, cb)); } void adb::fetch_cb (adb_fetchres *res, chordID key, cb_fetch cb, clnt_stat err) { if (err || (res && res->status)) { str nodata = ""; cb (ADB_ERR, key, nodata); } else { assert (key == res->resok->key); str data (res->resok->data.base (), res->resok->data.size ()); cb (ADB_OK, res->resok->key, data); } delete res; return; } void adb::getkeys (chordID start, cb_getkeys cb) { adb_getkeysarg arg; arg.start = start; arg.name = name_space; adb_getkeysres *res = New adb_getkeysres (); c->call (ADBPROC_GETKEYS, &arg, res, wrap (this, &adb::getkeys_cb, res, cb)); } void adb::getkeys_cb (adb_getkeysres *res, cb_getkeys cb, clnt_stat err) { if (err || (res && res->status)) { vec<chordID> nokeys; cb (ADB_ERR, nokeys); } else { vec<chordID> keys; for (unsigned int i = 0; i < res->resok->keys.size (); i++) keys.push_back (res->resok->keys[i]); adb_status ret = (res->resok->complete) ? ADB_COMPLETE : ADB_OK; cb (ret, keys); } } void adb::remove (chordID key, cbi cb) { adb_storearg arg; arg.name = name_space; arg.key = key; adb_status *stat = New adb_status (); c->call (ADBPROC_DELETE, &arg, stat, wrap (this, &adb::delete_cb, stat, cb)); } void adb::delete_cb (adb_status *stat, cbi cb, clnt_stat err) { if (err) cb (err); else cb (*stat); delete stat; } <commit_msg>Fix a memory leak in adb::getkeys_cb.<commit_after>#include "libadb.h" #include "adb_prot.h" #include "rxx.h" str dbrec_to_str (ptr<dbrec> dbr, int i) { //we aren't storing a null terminator. // add it here or the conversion grabs trailing garbage char buf[128]; int ncpy = (dbr->len > 127) ? 127 : dbr->len; memcpy (buf, dbr->value, dbr->len); buf[ncpy] = 0; // cache:abc03313ff rxx m("^([^!]+)!([0-9a-f]+)", "m"); m.search (buf); assert (m.success ()); return m[i]; } chordID dbrec_to_id (ptr<dbrec> dbr) { str id = dbrec_to_str (dbr, 2); chordID ret (id, 16); return ret; } str dbrec_to_name (ptr<dbrec> dbr) { str name = dbrec_to_str(dbr, 1); return name; } ptr<dbrec> id_to_dbrec (chordID key, str name_space) { //pad out all keys to 20 bytes so that they sort correctly str keystr = strbuf () << key; while (keystr.len () < 20) keystr = strbuf () << "0" << keystr; str c = strbuf () << name_space << "!" << keystr; return New refcounted<dbrec> (c.cstr (), c.len ()); } adb::adb (str sock_name, str name) : name_space (name) { int fd = unixsocket_connect (sock_name); if (fd < 0) { fatal ("adb_connect: Error connecting to %s: %s\n", sock_name.cstr (), strerror (errno)); } c = aclnt::alloc (axprt_unix::alloc (fd, 1024*1025), adb_program_1); } void adb::store (chordID key, str data, cbi cb) { adb_storearg arg; arg.key = key; arg.name = name_space; arg.data.setsize (data.len ()); memcpy (arg.data.base (), data.cstr (), data.len ()); adb_status *res = New adb_status (); c->call (ADBPROC_STORE, &arg, res, wrap (this, &adb::store_cb, res, cb)); return; } void adb::store_cb (adb_status *res, cbi cb, clnt_stat err) { if (cb) if (err || !res) cb (err); else cb (*res); delete res; } void adb::fetch (chordID key, cb_fetch cb) { adb_fetcharg arg; arg.key = key; arg.name = name_space; adb_fetchres *res = New adb_fetchres (ADB_OK); c->call (ADBPROC_FETCH, &arg, res, wrap (this, &adb::fetch_cb, res, key, cb)); } void adb::fetch_cb (adb_fetchres *res, chordID key, cb_fetch cb, clnt_stat err) { if (err || (res && res->status)) { str nodata = ""; cb (ADB_ERR, key, nodata); } else { assert (key == res->resok->key); str data (res->resok->data.base (), res->resok->data.size ()); cb (ADB_OK, res->resok->key, data); } delete res; return; } void adb::getkeys (chordID start, cb_getkeys cb) { adb_getkeysarg arg; arg.start = start; arg.name = name_space; adb_getkeysres *res = New adb_getkeysres (); c->call (ADBPROC_GETKEYS, &arg, res, wrap (this, &adb::getkeys_cb, res, cb)); } void adb::getkeys_cb (adb_getkeysres *res, cb_getkeys cb, clnt_stat err) { if (err || (res && res->status)) { vec<chordID> nokeys; cb (ADB_ERR, nokeys); } else { vec<chordID> keys; for (unsigned int i = 0; i < res->resok->keys.size (); i++) keys.push_back (res->resok->keys[i]); adb_status ret = (res->resok->complete) ? ADB_COMPLETE : ADB_OK; cb (ret, keys); } delete res; } void adb::remove (chordID key, cbi cb) { adb_storearg arg; arg.name = name_space; arg.key = key; adb_status *stat = New adb_status (); c->call (ADBPROC_DELETE, &arg, stat, wrap (this, &adb::delete_cb, stat, cb)); } void adb::delete_cb (adb_status *stat, cbi cb, clnt_stat err) { if (err) cb (err); else cb (*stat); delete stat; } <|endoftext|>
<commit_before>/* * opencog/atomspace/AttentionBank.cc * * Copyright (C) 2013 Linas Vepstas <linasvepstas@gmail.com> * All Rights Reserved * * Written by Joel Pitt * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License v3 as * published by the Free Software Foundation and including the exceptions * at http://opencog.org/wiki/Licenses * * 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 Affero General Public License * along with this program; if not, write to: * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <boost/bind.hpp> #include <opencog/atoms/base/Handle.h> #include "AttentionBank.h" #include "AtomTable.h" using namespace opencog; AttentionBank::AttentionBank(AtomTable& atab, bool transient) { /* Do not boether with initialization, if this is transient */ if (transient) { _zombie = true; return; } _zombie = false; #if 0 startingFundsSTI = fundsSTI = config().get_int("STARTING_STI_FUNDS"); startingFundsLTI = fundsLTI = config().get_int("STARTING_LTI_FUNDS"); stiFundsBuffer = config().get_int("STI_FUNDS_BUFFER"); ltiFundsBuffer = config().get_int("LTI_FUNDS_BUFFER"); targetLTI = config().get_int("TARGET_LTI_FUNDS"); targetSTI = config().get_int("TARGET_STI_FUNDS"); STIAtomWage = config().get_int("ECAN_STARTING_ATOM_STI_WAGE"); LTIAtomWage = config().get_int("ECAN_STARTING_ATOM_LTI_WAGE"); #endif attentionalFocusBoundary = 1; AVChangedConnection = atab.AVChangedSignal().connect( boost::bind(&AttentionBank::AVChanged, this, _1, _2, _3)); } /// This must be called before the AtomTable is destroyed. Which /// means that it cannot be in the destructor (since the AtomTable /// is probably gone by then, leading to a crash. XXX FIXME yes this /// is a tacky hack to fix a design bug. void AttentionBank::shutdown(void) { if (_zombie) return; /* no-op, if a zombie */ AVChangedConnection.disconnect(); } AttentionBank::~AttentionBank() {} void AttentionBank::AVChanged(Handle h, AttentionValuePtr old_av, AttentionValuePtr new_av) { // Add the old attention values to the AtomSpace funds and // subtract the new attention values from the AtomSpace funds updateSTIFunds(old_av->getSTI() - new_av->getSTI()); updateLTIFunds(old_av->getLTI() - new_av->getLTI()); logger().fine("AVChanged: fundsSTI = %d, old_av: %d, new_av: %d", fundsSTI, old_av->getSTI(), new_av->getSTI()); // Check if the atom crossed into or out of the AttentionalFocus // and notify any interested parties if (old_av->getSTI() < attentionalFocusBoundary and new_av->getSTI() >= attentionalFocusBoundary) { AFCHSigl& afch = AddAFSignal(); afch(h, old_av, new_av); } else if (new_av->getSTI() < attentionalFocusBoundary and old_av->getSTI() >= attentionalFocusBoundary) { AFCHSigl& afch = RemoveAFSignal(); afch(h, old_av, new_av); } } long AttentionBank::getTotalSTI() const { std::lock_guard<std::mutex> lock(lock_funds); return startingFundsSTI - fundsSTI; } long AttentionBank::getTotalLTI() const { std::lock_guard<std::mutex> lock(lock_funds); return startingFundsLTI - fundsLTI; } long AttentionBank::getSTIFunds() const { std::lock_guard<std::mutex> lock(lock_funds); return fundsSTI; } long AttentionBank::getLTIFunds() const { std::lock_guard<std::mutex> lock(lock_funds); return fundsLTI; } long AttentionBank::updateSTIFunds(AttentionValue::sti_t diff) { std::lock_guard<std::mutex> lock(lock_funds); fundsSTI += diff; return fundsSTI; } long AttentionBank::updateLTIFunds(AttentionValue::lti_t diff) { std::lock_guard<std::mutex> lock(lock_funds); fundsLTI += diff; return fundsLTI; } void AttentionBank::updateMaxSTI(AttentionValue::sti_t m) { std::lock_guard<std::mutex> lock(lock_maxSTI); maxSTI.update(m); } void AttentionBank::updateMinSTI(AttentionValue::sti_t m) { std::lock_guard<std::mutex> lock(lock_minSTI); minSTI.update(m); } AttentionValue::sti_t AttentionBank::getMaxSTI(bool average) const { std::lock_guard<std::mutex> lock(lock_maxSTI); if (average) { return (AttentionValue::sti_t) maxSTI.recent; } else { return maxSTI.val; } } AttentionValue::sti_t AttentionBank::getMinSTI(bool average) const { std::lock_guard<std::mutex> lock(lock_minSTI); if (average) { return (AttentionValue::sti_t) minSTI.recent; } else { return minSTI.val; } } AttentionValue::sti_t AttentionBank::calculateSTIWage() { long funds = getSTIFunds(); float diff = funds - targetSTI; float ndiff = diff / stiFundsBuffer; ndiff = std::min(ndiff,1.0f); ndiff = std::max(ndiff,-1.0f); return STIAtomWage + (STIAtomWage * ndiff); } AttentionValue::lti_t AttentionBank::calculateLTIWage() { long funds = getLTIFunds(); float diff = funds - targetLTI; float ndiff = diff / ltiFundsBuffer; ndiff = std::min(ndiff,1.0f); ndiff = std::max(ndiff,-1.0f); return LTIAtomWage + (LTIAtomWage * ndiff); } AttentionValue::sti_t AttentionBank::getAttentionalFocusBoundary() const { return attentionalFocusBoundary; } AttentionValue::sti_t AttentionBank::setAttentionalFocusBoundary(AttentionValue::sti_t boundary) { attentionalFocusBoundary = boundary; return boundary; } float AttentionBank::getNormalisedSTI(AttentionValuePtr av, bool average, bool clip) const { // get normalizer (maxSTI - attention boundary) int normaliser; float val; AttentionValue::sti_t s = av->getSTI(); if (s > getAttentionalFocusBoundary()) { normaliser = (int) getMaxSTI(average) - getAttentionalFocusBoundary(); if (normaliser == 0) { return 0.0f; } val = (s - getAttentionalFocusBoundary()) / (float) normaliser; } else { normaliser = -((int) getMinSTI(average) + getAttentionalFocusBoundary()); if (normaliser == 0) { return 0.0f; } val = (s + getAttentionalFocusBoundary()) / (float) normaliser; } if (clip) { return std::max(-1.0f, std::min(val,1.0f)); } else { return val; } } float AttentionBank::getNormalisedSTI(AttentionValuePtr av) const { AttentionValue::sti_t s = av->getSTI(); auto normaliser = s > getAttentionalFocusBoundary() ? getMaxSTI() : getMinSTI(); return (s / normaliser); } float AttentionBank::getNormalisedZeroToOneSTI(AttentionValuePtr av, bool average, bool clip) const { int normaliser; float val; AttentionValue::sti_t s = av->getSTI(); normaliser = getMaxSTI(average) - getMinSTI(average); if (normaliser == 0) { return 0.0f; } val = (s - getMinSTI(average)) / (float) normaliser; if (clip) { return std::max(0.0f, std::min(val,1.0f)); } else { return val; } } <commit_msg>ReAdded Loading from Config for AttentionBank with Defaults<commit_after>/* * opencog/atomspace/AttentionBank.cc * * Copyright (C) 2013 Linas Vepstas <linasvepstas@gmail.com> * All Rights Reserved * * Written by Joel Pitt * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License v3 as * published by the Free Software Foundation and including the exceptions * at http://opencog.org/wiki/Licenses * * 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 Affero General Public License * along with this program; if not, write to: * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <boost/bind.hpp> #include <opencog/atoms/base/Handle.h> #include "AttentionBank.h" #include "AtomTable.h" #include <opencog/util/Config.h> using namespace opencog; AttentionBank::AttentionBank(AtomTable& atab, bool transient) { /* Do not boether with initialization, if this is transient */ if (transient) { _zombie = true; return; } _zombie = false; startingFundsSTI = fundsSTI = config().get_int("STARTING_STI_FUNDS",100000); startingFundsLTI = fundsLTI = config().get_int("STARTING_LTI_FUNDS",100000); stiFundsBuffer = config().get_int("STI_FUNDS_BUFFER",10000); ltiFundsBuffer = config().get_int("LTI_FUNDS_BUFFER",10000); targetLTI = config().get_int("TARGET_LTI_FUNDS",10000); targetSTI = config().get_int("TARGET_STI_FUNDS",10000); STIAtomWage = config().get_int("ECAN_STARTING_ATOM_STI_WAGE",10); LTIAtomWage = config().get_int("ECAN_STARTING_ATOM_LTI_WAGE",10); attentionalFocusBoundary = 1; AVChangedConnection = atab.AVChangedSignal().connect( boost::bind(&AttentionBank::AVChanged, this, _1, _2, _3)); } /// This must be called before the AtomTable is destroyed. Which /// means that it cannot be in the destructor (since the AtomTable /// is probably gone by then, leading to a crash. XXX FIXME yes this /// is a tacky hack to fix a design bug. void AttentionBank::shutdown(void) { if (_zombie) return; /* no-op, if a zombie */ AVChangedConnection.disconnect(); } AttentionBank::~AttentionBank() {} void AttentionBank::AVChanged(Handle h, AttentionValuePtr old_av, AttentionValuePtr new_av) { // Add the old attention values to the AtomSpace funds and // subtract the new attention values from the AtomSpace funds updateSTIFunds(old_av->getSTI() - new_av->getSTI()); updateLTIFunds(old_av->getLTI() - new_av->getLTI()); logger().fine("AVChanged: fundsSTI = %d, old_av: %d, new_av: %d", fundsSTI, old_av->getSTI(), new_av->getSTI()); // Check if the atom crossed into or out of the AttentionalFocus // and notify any interested parties if (old_av->getSTI() < attentionalFocusBoundary and new_av->getSTI() >= attentionalFocusBoundary) { AFCHSigl& afch = AddAFSignal(); afch(h, old_av, new_av); } else if (new_av->getSTI() < attentionalFocusBoundary and old_av->getSTI() >= attentionalFocusBoundary) { AFCHSigl& afch = RemoveAFSignal(); afch(h, old_av, new_av); } } long AttentionBank::getTotalSTI() const { std::lock_guard<std::mutex> lock(lock_funds); return startingFundsSTI - fundsSTI; } long AttentionBank::getTotalLTI() const { std::lock_guard<std::mutex> lock(lock_funds); return startingFundsLTI - fundsLTI; } long AttentionBank::getSTIFunds() const { std::lock_guard<std::mutex> lock(lock_funds); return fundsSTI; } long AttentionBank::getLTIFunds() const { std::lock_guard<std::mutex> lock(lock_funds); return fundsLTI; } long AttentionBank::updateSTIFunds(AttentionValue::sti_t diff) { std::lock_guard<std::mutex> lock(lock_funds); fundsSTI += diff; return fundsSTI; } long AttentionBank::updateLTIFunds(AttentionValue::lti_t diff) { std::lock_guard<std::mutex> lock(lock_funds); fundsLTI += diff; return fundsLTI; } void AttentionBank::updateMaxSTI(AttentionValue::sti_t m) { std::lock_guard<std::mutex> lock(lock_maxSTI); maxSTI.update(m); } void AttentionBank::updateMinSTI(AttentionValue::sti_t m) { std::lock_guard<std::mutex> lock(lock_minSTI); minSTI.update(m); } AttentionValue::sti_t AttentionBank::getMaxSTI(bool average) const { std::lock_guard<std::mutex> lock(lock_maxSTI); if (average) { return (AttentionValue::sti_t) maxSTI.recent; } else { return maxSTI.val; } } AttentionValue::sti_t AttentionBank::getMinSTI(bool average) const { std::lock_guard<std::mutex> lock(lock_minSTI); if (average) { return (AttentionValue::sti_t) minSTI.recent; } else { return minSTI.val; } } AttentionValue::sti_t AttentionBank::calculateSTIWage() { long funds = getSTIFunds(); float diff = funds - targetSTI; float ndiff = diff / stiFundsBuffer; ndiff = std::min(ndiff,1.0f); ndiff = std::max(ndiff,-1.0f); return STIAtomWage + (STIAtomWage * ndiff); } AttentionValue::lti_t AttentionBank::calculateLTIWage() { long funds = getLTIFunds(); float diff = funds - targetLTI; float ndiff = diff / ltiFundsBuffer; ndiff = std::min(ndiff,1.0f); ndiff = std::max(ndiff,-1.0f); return LTIAtomWage + (LTIAtomWage * ndiff); } AttentionValue::sti_t AttentionBank::getAttentionalFocusBoundary() const { return attentionalFocusBoundary; } AttentionValue::sti_t AttentionBank::setAttentionalFocusBoundary(AttentionValue::sti_t boundary) { attentionalFocusBoundary = boundary; return boundary; } float AttentionBank::getNormalisedSTI(AttentionValuePtr av, bool average, bool clip) const { // get normalizer (maxSTI - attention boundary) int normaliser; float val; AttentionValue::sti_t s = av->getSTI(); if (s > getAttentionalFocusBoundary()) { normaliser = (int) getMaxSTI(average) - getAttentionalFocusBoundary(); if (normaliser == 0) { return 0.0f; } val = (s - getAttentionalFocusBoundary()) / (float) normaliser; } else { normaliser = -((int) getMinSTI(average) + getAttentionalFocusBoundary()); if (normaliser == 0) { return 0.0f; } val = (s + getAttentionalFocusBoundary()) / (float) normaliser; } if (clip) { return std::max(-1.0f, std::min(val,1.0f)); } else { return val; } } float AttentionBank::getNormalisedSTI(AttentionValuePtr av) const { AttentionValue::sti_t s = av->getSTI(); auto normaliser = s > getAttentionalFocusBoundary() ? getMaxSTI() : getMinSTI(); return (s / normaliser); } float AttentionBank::getNormalisedZeroToOneSTI(AttentionValuePtr av, bool average, bool clip) const { int normaliser; float val; AttentionValue::sti_t s = av->getSTI(); normaliser = getMaxSTI(average) - getMinSTI(average); if (normaliser == 0) { return 0.0f; } val = (s - getMinSTI(average)) / (float) normaliser; if (clip) { return std::max(0.0f, std::min(val,1.0f)); } else { return val; } } <|endoftext|>
<commit_before>#include <stdio.h> #include "sound.h" #include "xcore/xcore.h" #include <iostream> #ifdef HAVESDL #include <SDL.h> #undef main #endif #ifdef _WIN32 #include <mmsystem.h> #endif #define SF_BUF 1 int sndFlag = 0; unsigned char sndBufA[0x10000]; unsigned char sndBufB[0x10000]; unsigned char* sndBuf = sndBufA; unsigned short ringPos = 0; unsigned short playPos = 0; int pass = 0; int smpCount = 0; long nsPerFrame; OutSys *sndOutput = NULL; int sndChunks = 882; int sndBufSize = 1764; int nsPerSample = 23143; int lev,levr,levl; unsigned char lastL,lastR; OutSys* findOutSys(const char*); #ifdef __linux__ int32_t ossHandle; // oss int32_t sndFormat; #ifdef HAVEALSA snd_pcm_t* alsaHandle = NULL; #endif #elif _WIN32 WAVEFORMATEX wf; WAVEHDR whdr; HWAVEOUT wout; HANDLE event; #endif // output // return 1 when buffer is full int sndSync(ZXComp* comp, int fast) { tapSync(comp->tape,comp->tapCount); comp->tapCount = 0; gsSync(comp->gs); tsSync(comp->ts,nsPerSample); saaSync(comp->saa,nsPerSample); if (!fast && (sndOutput != NULL)) { lev = comp->beeplev ? conf.snd.vol.beep : 0; if (comp->tape->levRec) lev += conf.snd.vol.tape; if (comp->tape->on && comp->tape->levPlay) { lev += conf.snd.vol.tape; } lev *= 0.16; levl = lev; levr = lev; sndPair svol = tsGetVolume(comp->ts); levl += svol.left * conf.snd.vol.ay / 100.0; levr += svol.right * conf.snd.vol.ay / 100.0; svol = gsGetVolume(comp->gs); levl += svol.left * conf.snd.vol.gs / 100.0; levr += svol.right * conf.snd.vol.gs / 100.0; svol = sdrvGetVolume(comp->sdrv); levl += svol.left * conf.snd.vol.beep / 100.0; levr += svol.right * conf.snd.vol.beep / 100.0; svol = saaGetVolume(comp->saa); // TODO : saa volume control levl += svol.left; levr += svol.right; if (levl > 0xff) levl = 0xff; if (levr > 0xff) levr = 0xff; lastL = levl & 0xff; lastR = levr & 0xff; } // if (smpCount >= sndChunks) return; // don't overfill buffer! sndBuf[ringPos++] = lastL; sndBuf[ringPos++] = lastR; smpCount++; return (smpCount < sndChunks) ? 0 : 1; } void sndFillToEnd() { while (smpCount < sndChunks) { sndBuf[ringPos++] = lastL; sndBuf[ringPos++] = lastR; smpCount++; } } void sndCalibrate() { sndChunks = conf.snd.rate / 50; // samples played at 1/50 sec 882 sndBufSize = conf.snd.chans * sndChunks; // buffer size for 1/50 sec play 1764 // nsPerSample = nsPerFrame / sndChunks; nsPerSample = 1e9 / conf.snd.rate; } std::string sndGetOutputName() { std::string res = "NULL"; if (sndOutput != NULL) { res = sndOutput->name; } return res; } void setOutput(const char* name) { if (sndOutput != NULL) { sndOutput->close(); } sndOutput = findOutSys(name); if (sndOutput == NULL) { printf("Can't find sound system '%s'. Reset to NULL\n",name); setOutput("NULL"); } if (!sndOutput->open()) { printf("Can't open sound system '%s'. Reset to NULL\n",name); setOutput("NULL"); } sndCalibrate(); } bool sndOpen() { if (sndOutput == NULL) return true; if (!sndOutput->open()) setOutput("NULL"); return true; } void sndPlay() { sndFillToEnd(); if (sndOutput != NULL) { sndOutput->play(); } smpCount = 0; } void sndPause(bool b) { smpCount = 0; sndFillToEnd(); } void sndClose() { if (sndOutput != NULL) sndOutput->close(); } std::string sndGetName() { std::string res = "NULL"; if (sndOutput != NULL) { res = sndOutput->name; } return res; } //------------------------ // Sound output //------------------------ void fillBuffer(int len) { int pos = 0; while (pos < len) { sndBufB[pos++] = sndBufA[playPos++]; } sndBuf = sndBufA; } void switchSndBuf() { sndBuf = (sndFlag & SF_BUF) ? sndBufA : sndBufB; sndFlag ^= SF_BUF; ringPos = 0; } bool null_open() {return true;} void null_play() {} void null_close() {} #ifdef HAVESDL void sdlPlayAudio(void*,Uint8* stream, int len) { if (pass < 2) { pass++; } else { int diff = ringPos - playPos; if (diff < 0) { diff = 0x10000 - diff; } if (diff >= len) fillBuffer(len); } SDL_MixAudio(stream, sndBufB, len, SDL_MIX_MAXVOLUME); // memcpy(stream,sndBufB,len); } bool sdlopen() { // printf("Open SDL audio device..."); SDL_AudioSpec asp; asp.freq = conf.snd.rate; asp.format = AUDIO_U8; asp.channels = 2; asp.samples = sndChunks + 1; asp.callback = &sdlPlayAudio; asp.userdata = NULL; if (SDL_OpenAudio(&asp, NULL) != 0) { printf("SDL audio device opening...failed\n"); return false; } SDL_PauseAudio(0); return true; } void sdlplay() { } void sdlclose() { SDL_CloseAudio(); } #endif #ifdef __linux__ bool oss_open() { // printf("Open OSS audio device\n"); ossHandle = open("/dev/dsp",O_WRONLY,0777); if (ossHandle < 0) return false; ioctl(ossHandle,SNDCTL_DSP_SETFMT,&sndFormat); ioctl(ossHandle,SNDCTL_DSP_CHANNELS,&conf.snd.chans); ioctl(ossHandle,SNDCTL_DSP_SPEED,&conf.snd.rate); return true; } void oss_play() { if (ossHandle < 0) return; // fillBuffer(sndBufSize); unsigned char* ptr = sndBuf; int fsz = sndBufSize; // smpCount * sndChans; int res; while (fsz > 0) { res = write(ossHandle,ptr,fsz); ptr += res; fsz -= res; } switchSndBuf(); // ringPos = 0; } void oss_close() { if (ossHandle < 0) return; // printf("Close OSS audio device\n"); close(ossHandle); } #ifdef HAVEALSA bool alsa_open() { int err; bool res = true; err = snd_pcm_open(&alsaHandle,"default",SND_PCM_STREAM_PLAYBACK,SND_PCM_NONBLOCK); if ((err < 0) || (alsaHandle == NULL)) { alsaHandle = NULL; res = false; } else { err = snd_pcm_set_params(alsaHandle,SND_PCM_FORMAT_U8,SND_PCM_ACCESS_RW_INTERLEAVED,conf.snd.chans,conf.snd.rate,1,100000); if (err != 0) { alsaHandle = NULL; res = false; } } return res; } void alsa_play() { if (alsaHandle == NULL) return; snd_pcm_sframes_t res; // fillBuffer(sndBufSize); unsigned char* ptr = sndBuf; int fsz = smpCount; while (fsz > 0) { res = snd_pcm_writei(alsaHandle, ptr, fsz); if (res < 0) res = snd_pcm_recover(alsaHandle, res, 1); if (res < 0) break; fsz -= res; ptr += res * conf.snd.chans; } switchSndBuf(); } void alsa_close() { if (alsaHandle == NULL) return; snd_pcm_close(alsaHandle); } #endif #elif _WIN32 // TODO: Windows sound output would be here... someday bool wave_open() { wf.wFormatTag = WAVE_FORMAT_PCM; wf.nChannels = sndChans; wf.nSamplesPerSec = conf.snd.rate; wf.wBitsPerSample = 8; wf.nBlockAlign = (sndChans * wf.wBitsPerSample) >> 3; wf.nAvgBytesPerSec = wf.nSamplesPerSec * wf.nBlockAlign; wf.cbSize = 0; whdr.dwBufferLength = sndBufSize; whdr.dwBytesRecorded = 0; whdr.dwUser = 0; whdr.dwLoops = 0; whdr.lpNext = NULL; whdr.reserved = 0; // event = CreateEvent(0, FALSE, FALSE, 0); MMRESULT res = waveOutOpen(&wout,WAVE_MAPPER,&wf,NULL,NULL,CALLBACK_NULL); // MMRESULT res = waveOutOpen(&wout,WAVE_MAPPER,&wf,DWORD_PTR(event),0,CALLBACK_EVENT | WAVE_FORMAT_DIRECT); return (res == MMSYSERR_NOERROR); } void wave_play() { whdr.lpData = (LPSTR)sndBuf; whdr.dwFlags = 0; whdr.dwBufferLength = sndBufSize; waveOutPrepareHeader(wout,&whdr,sizeof(WAVEHDR)); waveOutWrite(wout,&whdr,sizeof(WAVEHDR)); while (!(whdr.dwFlags & WHDR_DONE)) { WaitForSingleObject(event, INFINITE); } waveOutUnprepareHeader(wout,&whdr,sizeof(WAVEHDR)); switchSndBuf(); } void wave_close() { waveOutReset(wout); waveOutUnprepareHeader(wout,&whdr,sizeof(WAVEHDR)); waveOutClose(wout); CloseHandle(event); } #endif // init OutSys sndTab[] = { {SND_NULL,"NULL",&null_open,&null_play,&null_close}, #ifdef __linux__ {SND_OSS,"OSS",&oss_open,&oss_play,&oss_close}, #ifdef HAVEALSA {SND_ALSA,"ALSA",&alsa_open,&alsa_play,&alsa_close}, #endif #elif _WIN32 // {SND_WAVE,"WaveOut",&wave_open,&wave_play,&wave_close}, #endif #ifdef HAVESDL {SND_SDL,"SDL",&sdlopen,&sdlplay,&sdlclose}, #endif {0,NULL,NULL,NULL,NULL} }; OutSys* findOutSys(const char* name) { OutSys* res = NULL; int idx = 0; while (sndTab[idx].name != NULL) { if (strcmp(sndTab[idx].name,name) == 0) { res = &sndTab[idx]; break; } idx++; } return res; } void sndInit() { #ifdef __linux__ sndFormat = AFMT_U8; #endif conf.snd.rate = 44100; conf.snd.chans = 2; conf.snd.enabled = 1; conf.snd.mute = 1; sndOutput = NULL; conf.snd.vol.beep = 100; conf.snd.vol.tape = 100; conf.snd.vol.ay = 100; conf.snd.vol.gs = 100; initNoise(); // ay/ym } <commit_msg>build 20150927 [+] Fix 1st romset ignoring [+] Fix SDL sound (i think so)<commit_after>#include <stdio.h> #include "sound.h" #include "xcore/xcore.h" #include <iostream> #ifdef HAVESDL #include <SDL.h> #undef main #endif #ifdef _WIN32 #include <mmsystem.h> #endif #define SF_BUF 1 int sndFlag = 0; unsigned char sndBufA[0x10000]; unsigned char sndBufB[0x10000]; unsigned char* sndBuf = sndBufA; unsigned short ringPos = 0; unsigned short playPos = 0; int pass = 0; int smpCount = 0; long nsPerFrame; OutSys *sndOutput = NULL; int sndChunks = 882; int sndBufSize = 1764; int nsPerSample = 23143; int lev,levr,levl; unsigned char lastL,lastR; OutSys* findOutSys(const char*); #ifdef __linux__ int32_t ossHandle; // oss int32_t sndFormat; #ifdef HAVEALSA snd_pcm_t* alsaHandle = NULL; #endif #elif _WIN32 WAVEFORMATEX wf; WAVEHDR whdr; HWAVEOUT wout; HANDLE event; #endif // output // return 1 when buffer is full int sndSync(ZXComp* comp, int fast) { tapSync(comp->tape,comp->tapCount); comp->tapCount = 0; gsSync(comp->gs); tsSync(comp->ts,nsPerSample); saaSync(comp->saa,nsPerSample); if (!fast && (sndOutput != NULL)) { lev = comp->beeplev ? conf.snd.vol.beep : 0; if (comp->tape->levRec) lev += conf.snd.vol.tape; if (comp->tape->on && comp->tape->levPlay) { lev += conf.snd.vol.tape; } lev *= 0.16; levl = lev; levr = lev; sndPair svol = tsGetVolume(comp->ts); levl += svol.left * conf.snd.vol.ay / 100.0; levr += svol.right * conf.snd.vol.ay / 100.0; svol = gsGetVolume(comp->gs); levl += svol.left * conf.snd.vol.gs / 100.0; levr += svol.right * conf.snd.vol.gs / 100.0; svol = sdrvGetVolume(comp->sdrv); levl += svol.left * conf.snd.vol.beep / 100.0; levr += svol.right * conf.snd.vol.beep / 100.0; svol = saaGetVolume(comp->saa); // TODO : saa volume control levl += svol.left; levr += svol.right; if (levl > 0xff) levl = 0xff; if (levr > 0xff) levr = 0xff; lastL = levl & 0xff; lastR = levr & 0xff; } // if (smpCount >= sndChunks) return; // don't overfill buffer! sndBuf[ringPos++] = lastL; sndBuf[ringPos++] = lastR; smpCount++; return (smpCount < sndChunks) ? 0 : 1; } void sndFillToEnd() { while (smpCount < sndChunks) { sndBuf[ringPos++] = lastL; sndBuf[ringPos++] = lastR; smpCount++; } } void sndCalibrate() { sndChunks = conf.snd.rate / 50; // samples played at 1/50 sec 882 sndBufSize = conf.snd.chans * sndChunks; // buffer size for 1/50 sec play 1764 // nsPerSample = nsPerFrame / sndChunks; nsPerSample = 1e9 / conf.snd.rate; } std::string sndGetOutputName() { std::string res = "NULL"; if (sndOutput != NULL) { res = sndOutput->name; } return res; } void setOutput(const char* name) { if (sndOutput != NULL) { sndOutput->close(); } sndOutput = findOutSys(name); if (sndOutput == NULL) { printf("Can't find sound system '%s'. Reset to NULL\n",name); setOutput("NULL"); } if (!sndOutput->open()) { printf("Can't open sound system '%s'. Reset to NULL\n",name); setOutput("NULL"); } sndCalibrate(); } bool sndOpen() { if (sndOutput == NULL) return true; if (!sndOutput->open()) setOutput("NULL"); return true; } void sndPlay() { sndFillToEnd(); if (sndOutput != NULL) { sndOutput->play(); } smpCount = 0; } void sndPause(bool b) { smpCount = 0; sndFillToEnd(); } void sndClose() { if (sndOutput != NULL) sndOutput->close(); } std::string sndGetName() { std::string res = "NULL"; if (sndOutput != NULL) { res = sndOutput->name; } return res; } //------------------------ // Sound output //------------------------ void fillBuffer(int len) { int pos = 0; while (pos < len) { sndBufB[pos++] = sndBufA[playPos++]; } sndBuf = sndBufA; } void switchSndBuf() { sndBuf = (sndFlag & SF_BUF) ? sndBufA : sndBufB; sndFlag ^= SF_BUF; ringPos = 0; } bool null_open() {return true;} void null_play() {} void null_close() {} #ifdef HAVESDL void sdlPlayAudio(void*,Uint8* stream, int len) { if (pass < 2) { pass++; } else { int diff = ringPos - playPos; if (diff < 0) { diff = 0x10000 - diff; } if (diff >= len) fillBuffer(len); } SDL_MixAudio(stream, sndBufB, len, SDL_MIX_MAXVOLUME); // memcpy(stream,sndBufB,len); } bool sdlopen() { // printf("Open SDL audio device..."); SDL_AudioSpec asp; asp.freq = conf.snd.rate; asp.format = AUDIO_U8; asp.channels = 2; asp.samples = sndChunks + 1; asp.callback = &sdlPlayAudio; asp.userdata = NULL; if (SDL_OpenAudio(&asp, NULL) != 0) { printf("SDL audio device opening...failed\n"); return false; } SDL_PauseAudio(0); return true; } void sdlplay() { } void sdlclose() { SDL_CloseAudio(); } #endif #ifdef __linux__ bool oss_open() { // printf("Open OSS audio device\n"); ossHandle = open("/dev/dsp",O_WRONLY,0777); if (ossHandle < 0) return false; ioctl(ossHandle,SNDCTL_DSP_SETFMT,&sndFormat); ioctl(ossHandle,SNDCTL_DSP_CHANNELS,&conf.snd.chans); ioctl(ossHandle,SNDCTL_DSP_SPEED,&conf.snd.rate); return true; } void oss_play() { if (ossHandle < 0) return; // fillBuffer(sndBufSize); unsigned char* ptr = sndBuf; int fsz = sndBufSize; // smpCount * sndChans; int res; while (fsz > 0) { res = write(ossHandle,ptr,fsz); ptr += res; fsz -= res; } switchSndBuf(); // ringPos = 0; } void oss_close() { if (ossHandle < 0) return; // printf("Close OSS audio device\n"); close(ossHandle); } #ifdef HAVEALSA bool alsa_open() { int err; bool res = true; err = snd_pcm_open(&alsaHandle,"default",SND_PCM_STREAM_PLAYBACK,SND_PCM_NONBLOCK); if ((err < 0) || (alsaHandle == NULL)) { alsaHandle = NULL; res = false; } else { err = snd_pcm_set_params(alsaHandle,SND_PCM_FORMAT_U8,SND_PCM_ACCESS_RW_INTERLEAVED,conf.snd.chans,conf.snd.rate,1,100000); if (err != 0) { alsaHandle = NULL; res = false; } } return res; } void alsa_play() { if (alsaHandle == NULL) return; snd_pcm_sframes_t res; // fillBuffer(sndBufSize); unsigned char* ptr = sndBuf; int fsz = smpCount; while (fsz > 0) { res = snd_pcm_writei(alsaHandle, ptr, fsz); if (res < 0) res = snd_pcm_recover(alsaHandle, res, 1); if (res < 0) break; fsz -= res; ptr += res * conf.snd.chans; } switchSndBuf(); } void alsa_close() { if (alsaHandle == NULL) return; snd_pcm_close(alsaHandle); } #endif #elif _WIN32 // TODO: Windows sound output would be here... someday bool wave_open() { wf.wFormatTag = WAVE_FORMAT_PCM; wf.nChannels = conf.snd.chans; wf.nSamplesPerSec = conf.snd.rate; wf.wBitsPerSample = 8; wf.nBlockAlign = (conf.snd.chans * wf.wBitsPerSample) >> 3; wf.nAvgBytesPerSec = wf.nSamplesPerSec * wf.nBlockAlign; wf.cbSize = 0; whdr.dwBufferLength = sndBufSize; whdr.dwBytesRecorded = 0; whdr.dwUser = 0; whdr.dwLoops = 0; whdr.lpNext = NULL; whdr.reserved = 0; // event = CreateEvent(0, FALSE, FALSE, 0); MMRESULT res = waveOutOpen(&wout,WAVE_MAPPER,&wf,NULL,NULL,CALLBACK_NULL); // MMRESULT res = waveOutOpen(&wout,WAVE_MAPPER,&wf,DWORD_PTR(event),0,CALLBACK_EVENT | WAVE_FORMAT_DIRECT); return (res == MMSYSERR_NOERROR); } void wave_play() { whdr.lpData = (LPSTR)sndBuf; whdr.dwFlags = 0; whdr.dwBufferLength = sndBufSize; waveOutPrepareHeader(wout,&whdr,sizeof(WAVEHDR)); waveOutWrite(wout,&whdr,sizeof(WAVEHDR)); while (!(whdr.dwFlags & WHDR_DONE)) { WaitForSingleObject(event, INFINITE); } waveOutUnprepareHeader(wout,&whdr,sizeof(WAVEHDR)); switchSndBuf(); } void wave_close() { waveOutReset(wout); waveOutUnprepareHeader(wout,&whdr,sizeof(WAVEHDR)); waveOutClose(wout); CloseHandle(event); } #endif // init OutSys sndTab[] = { {SND_NULL,"NULL",&null_open,&null_play,&null_close}, #ifdef __linux__ {SND_OSS,"OSS",&oss_open,&oss_play,&oss_close}, #ifdef HAVEALSA {SND_ALSA,"ALSA",&alsa_open,&alsa_play,&alsa_close}, #endif #elif _WIN32 // {SND_WAVE,"WaveOut",&wave_open,&wave_play,&wave_close}, #endif #ifdef HAVESDL {SND_SDL,"SDL",&sdlopen,&sdlplay,&sdlclose}, #endif {0,NULL,NULL,NULL,NULL} }; OutSys* findOutSys(const char* name) { OutSys* res = NULL; int idx = 0; while (sndTab[idx].name != NULL) { if (strcmp(sndTab[idx].name,name) == 0) { res = &sndTab[idx]; break; } idx++; } return res; } void sndInit() { #ifdef __linux__ sndFormat = AFMT_U8; #endif conf.snd.rate = 44100; conf.snd.chans = 2; conf.snd.enabled = 1; conf.snd.mute = 1; sndOutput = NULL; conf.snd.vol.beep = 100; conf.snd.vol.tape = 100; conf.snd.vol.ay = 100; conf.snd.vol.gs = 100; initNoise(); // ay/ym } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: listener.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: obo $ $Date: 2006-09-17 15:19:02 $ * * 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_svtools.hxx" #ifndef GCC #endif #ifndef DEBUG_HXX #include <tools/debug.hxx> #endif #include "broadcast.hxx" #include "listener.hxx" #include "listenerbase.hxx" #include "listeneriter.hxx" //==================================================================== TYPEINIT0(SvtListener); //==================================================================== // simple ctor of class SvtListener SvtListener::SvtListener() : pBrdCastLst( 0 ) { } //-------------------------------------------------------------------- // copy ctor of class SvtListener SvtListener::SvtListener( const SvtListener &rListener ) : pBrdCastLst( 0 ) { SvtListenerBase* pLst = rListener.pBrdCastLst; while( pLst ) { new SvtListenerBase( *this, *pLst->GetBroadcaster() ); pLst = pLst->GetNext(); } } //-------------------------------------------------------------------- // unregisteres the SvtListener from its SvtBroadcasters SvtListener::~SvtListener() { EndListeningAll(); } //-------------------------------------------------------------------- // registeres at a specific SvtBroadcaster BOOL SvtListener::StartListening( SvtBroadcaster& rBroadcaster ) { const SvtListenerBase* pLst = pBrdCastLst; while( pLst ) { if( &rBroadcaster == pLst->GetBroadcaster() ) { // double, than return return FALSE; } pLst = pLst->GetNext(); } new SvtListenerBase( *this, rBroadcaster ); return TRUE; } //-------------------------------------------------------------------- // unregisteres at a specific SvtBroadcaster BOOL SvtListener::EndListening( SvtBroadcaster& rBroadcaster ) { SvtListenerBase *pLst = pBrdCastLst, *pPrev = pLst; while( pLst ) { if( &rBroadcaster == pLst->GetBroadcaster() ) { if( pBrdCastLst == pLst ) pBrdCastLst = pLst->GetNext(); else pPrev->SetNext( pLst->GetNext() ); delete pLst; return TRUE; } pPrev = pLst; pLst = pLst->GetNext(); } return FALSE; } //-------------------------------------------------------------------- // unregisteres all Broadcasters void SvtListener::EndListeningAll() { SvtListenerBase *pLst = pBrdCastLst; while( pLst ) { SvtListenerBase *pDel = pLst; pLst = pLst->GetNext(); delete pDel; } pBrdCastLst = 0; } //-------------------------------------------------------------------- BOOL SvtListener::IsListening( SvtBroadcaster& rBroadcaster ) const { const SvtListenerBase *pLst = pBrdCastLst; while( pLst ) { if( &rBroadcaster == pLst->GetBroadcaster() ) break; pLst = pLst->GetNext(); } return 0 != pLst; } //-------------------------------------------------------------------- // base implementation of notification handler void SvtListener::Notify( SvtBroadcaster& #ifdef DBG_UTIL rBC #endif , const SfxHint& ) { DBG_ASSERT( IsListening( rBC ), "notification from unregistered broadcaster" ); } <commit_msg>INTEGRATION: CWS changefileheader (1.5.450); FILE MERGED 2008/03/31 13:02:23 rt 1.5.450.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: listener.cxx,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. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_svtools.hxx" #ifndef GCC #endif #ifndef DEBUG_HXX #include <tools/debug.hxx> #endif #include "broadcast.hxx" #include "listener.hxx" #include "listenerbase.hxx" #include "listeneriter.hxx" //==================================================================== TYPEINIT0(SvtListener); //==================================================================== // simple ctor of class SvtListener SvtListener::SvtListener() : pBrdCastLst( 0 ) { } //-------------------------------------------------------------------- // copy ctor of class SvtListener SvtListener::SvtListener( const SvtListener &rListener ) : pBrdCastLst( 0 ) { SvtListenerBase* pLst = rListener.pBrdCastLst; while( pLst ) { new SvtListenerBase( *this, *pLst->GetBroadcaster() ); pLst = pLst->GetNext(); } } //-------------------------------------------------------------------- // unregisteres the SvtListener from its SvtBroadcasters SvtListener::~SvtListener() { EndListeningAll(); } //-------------------------------------------------------------------- // registeres at a specific SvtBroadcaster BOOL SvtListener::StartListening( SvtBroadcaster& rBroadcaster ) { const SvtListenerBase* pLst = pBrdCastLst; while( pLst ) { if( &rBroadcaster == pLst->GetBroadcaster() ) { // double, than return return FALSE; } pLst = pLst->GetNext(); } new SvtListenerBase( *this, rBroadcaster ); return TRUE; } //-------------------------------------------------------------------- // unregisteres at a specific SvtBroadcaster BOOL SvtListener::EndListening( SvtBroadcaster& rBroadcaster ) { SvtListenerBase *pLst = pBrdCastLst, *pPrev = pLst; while( pLst ) { if( &rBroadcaster == pLst->GetBroadcaster() ) { if( pBrdCastLst == pLst ) pBrdCastLst = pLst->GetNext(); else pPrev->SetNext( pLst->GetNext() ); delete pLst; return TRUE; } pPrev = pLst; pLst = pLst->GetNext(); } return FALSE; } //-------------------------------------------------------------------- // unregisteres all Broadcasters void SvtListener::EndListeningAll() { SvtListenerBase *pLst = pBrdCastLst; while( pLst ) { SvtListenerBase *pDel = pLst; pLst = pLst->GetNext(); delete pDel; } pBrdCastLst = 0; } //-------------------------------------------------------------------- BOOL SvtListener::IsListening( SvtBroadcaster& rBroadcaster ) const { const SvtListenerBase *pLst = pBrdCastLst; while( pLst ) { if( &rBroadcaster == pLst->GetBroadcaster() ) break; pLst = pLst->GetNext(); } return 0 != pLst; } //-------------------------------------------------------------------- // base implementation of notification handler void SvtListener::Notify( SvtBroadcaster& #ifdef DBG_UTIL rBC #endif , const SfxHint& ) { DBG_ASSERT( IsListening( rBC ), "notification from unregistered broadcaster" ); } <|endoftext|>
<commit_before><commit_msg>Added Test for tdf#74363 auto correct of initial captials on start<commit_after><|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: feflyole.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: mib $ $Date: 2002-08-09 08:39:22 $ * * 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): _______________________________________ * * ************************************************************************/ #ifdef PRECOMPILED #include "core_pch.hxx" #endif #pragma hdrstop #ifndef _IPOBJ_HXX #include <so3/ipobj.hxx> #endif #ifndef _EMBOBJ_HXX #include <so3/embobj.hxx> #endif #ifndef _SFX_CLIENTSH_HXX #include <sfx2/clientsh.hxx> #endif #ifndef _SFXVIEWSH_HXX #include <sfx2/viewsh.hxx> #endif #ifndef _SFXAPP_HXX #include <sfx2/app.hxx> #endif #ifndef _SCHDLL0_HXX #include <sch/schdll0.hxx> #endif #ifndef _SCH_DLL_HXX #include <sch/schdll.hxx> #endif #ifndef _SCH_MEMCHRT_HXX #include <sch/memchrt.hxx> #endif #ifndef INCLUDED_SVTOOLS_MODULEOPTIONS_HXX #include <svtools/moduleoptions.hxx> #endif #ifndef _FMTCNTNT_HXX #include <fmtcntnt.hxx> #endif #ifndef _FMTANCHR_HXX #include <fmtanchr.hxx> #endif #ifndef _FESH_HXX #include <fesh.hxx> #endif #ifndef _CNTFRM_HXX #include <cntfrm.hxx> #endif #ifndef _FRMFMT_HXX #include <frmfmt.hxx> #endif #ifndef _FLYFRM_HXX #include <flyfrm.hxx> #endif #ifndef _PAM_HXX #include <pam.hxx> #endif #ifndef _EDIMP_HXX #include <edimp.hxx> #endif #ifndef _NDTXT_HXX #include <ndtxt.hxx> #endif #ifndef _NOTXTFRM_HXX #include <notxtfrm.hxx> #endif #ifndef _NDOLE_HXX #include <ndole.hxx> #endif #ifndef _SWCLI_HXX #include <swcli.hxx> #endif SwFlyFrm *SwFEShell::FindFlyFrm( const SvEmbeddedObject *pIPObj ) const { SwFlyFrm *pFly = FindFlyFrm(); if ( pFly && pFly->Lower() && pFly->Lower()->IsNoTxtFrm() ) { SwOLENode *pNd = ((SwNoTxtFrm*)pFly->Lower())->GetNode()->GetOLENode(); if ( !pNd || &pNd->GetOLEObj().GetOleRef() != pIPObj ) pFly = 0; } else pFly = 0; if ( !pFly ) { //Kein Fly oder der falsche selektiert. Ergo muessen wir leider suchen. BOOL bExist = FALSE; SwStartNode *pStNd; ULONG nSttIdx = GetNodes().GetEndOfAutotext().StartOfSectionIndex() + 1, nEndIdx = GetNodes().GetEndOfAutotext().GetIndex(); while( nSttIdx < nEndIdx && 0 != (pStNd = GetNodes()[ nSttIdx ]->GetStartNode()) ) { SwNode *pNd = GetNodes()[ nSttIdx+1 ]; if ( pNd->IsOLENode() && //do not load Objects! must not be neccessary here ((SwOLENode*)pNd)->GetOLEObj().IsOleRef() && &((SwOLENode*)pNd)->GetOLEObj().GetOleRef() == pIPObj ) { bExist = TRUE; SwFrm *pFrm = ((SwOLENode*)pNd)->GetFrm(); if ( pFrm ) pFly = pFrm->FindFlyFrm(); break; } nSttIdx = pStNd->EndOfSectionIndex() + 1; } ASSERT( bExist, "OLE-Object unknown and FlyFrm not found." ); } return pFly; } String SwFEShell::GetUniqueOLEName() const { return GetDoc()->GetUniqueOLEName(); } String SwFEShell::GetUniqueFrameName() const { return GetDoc()->GetUniqueFrameName(); } void SwFEShell::MakeObjVisible( const SvEmbeddedObject *pIPObj ) const { SwFlyFrm *pFly = FindFlyFrm( pIPObj ); if ( pFly ) { SwRect aTmp( pFly->Prt() ); aTmp += pFly->Frm().Pos(); if ( !aTmp.IsOver( VisArea() ) ) { ((SwFEShell*)this)->StartAction(); ((SwFEShell*)this)->MakeVisible( aTmp ); ((SwFEShell*)this)->EndAction(); } } } BOOL SwFEShell::FinishOLEObj() // Server wird beendet { SfxInPlaceClient* pIPClient = GetSfxViewShell()->GetIPClient(); BOOL bRet = pIPClient && pIPClient->IsInPlaceActive(); if( bRet ) { if( CNT_OLE == GetCntType() ) ClearAutomaticContour(); // Link fuer Daten-Highlighting im Chart zuruecksetzen SvtModuleOptions aMOpt; if( aMOpt.IsChart() ) { SvInPlaceObject* pObj = pIPClient->GetIPObj(); SvGlobalName aObjClsId( *pObj->GetSvFactory() ); SchMemChart* pMemChart; if( SchModuleDummy::HasID( aObjClsId ) && 0 != (pMemChart = SchDLL::GetChartData( pObj ) )) { pMemChart->SetSelectionHdl( Link() ); //ggfs. auch die Selektion restaurieren LockView( TRUE ); //Scrollen im EndAction verhindern ClearMark(); LockView( FALSE ); } } if( ((SwOleClient*)pIPClient)->IsCheckForOLEInCaption() != IsCheckForOLEInCaption() ) SetCheckForOLEInCaption( !IsCheckForOLEInCaption() ); //InPlace beenden. pIPClient->GetProtocol().Reset2Open(); SFX_APP()->SetViewFrame( GetSfxViewShell()->GetViewFrame() ); } return bRet; } <commit_msg>INTEGRATION: CWS os8 (1.4.144); FILE MERGED 2003/04/03 07:10:47 os 1.4.144.1: #108583# precompiled headers removed<commit_after>/************************************************************************* * * $RCSfile: feflyole.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: vg $ $Date: 2003-04-17 14:08:22 $ * * 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): _______________________________________ * * ************************************************************************/ #pragma hdrstop #ifndef _IPOBJ_HXX #include <so3/ipobj.hxx> #endif #ifndef _EMBOBJ_HXX #include <so3/embobj.hxx> #endif #ifndef _SFX_CLIENTSH_HXX #include <sfx2/clientsh.hxx> #endif #ifndef _SFXVIEWSH_HXX #include <sfx2/viewsh.hxx> #endif #ifndef _SFXAPP_HXX #include <sfx2/app.hxx> #endif #ifndef _SCHDLL0_HXX #include <sch/schdll0.hxx> #endif #ifndef _SCH_DLL_HXX #include <sch/schdll.hxx> #endif #ifndef _SCH_MEMCHRT_HXX #include <sch/memchrt.hxx> #endif #ifndef INCLUDED_SVTOOLS_MODULEOPTIONS_HXX #include <svtools/moduleoptions.hxx> #endif #ifndef _FMTCNTNT_HXX #include <fmtcntnt.hxx> #endif #ifndef _FMTANCHR_HXX #include <fmtanchr.hxx> #endif #ifndef _FESH_HXX #include <fesh.hxx> #endif #ifndef _CNTFRM_HXX #include <cntfrm.hxx> #endif #ifndef _FRMFMT_HXX #include <frmfmt.hxx> #endif #ifndef _FLYFRM_HXX #include <flyfrm.hxx> #endif #ifndef _PAM_HXX #include <pam.hxx> #endif #ifndef _EDIMP_HXX #include <edimp.hxx> #endif #ifndef _NDTXT_HXX #include <ndtxt.hxx> #endif #ifndef _NOTXTFRM_HXX #include <notxtfrm.hxx> #endif #ifndef _NDOLE_HXX #include <ndole.hxx> #endif #ifndef _SWCLI_HXX #include <swcli.hxx> #endif SwFlyFrm *SwFEShell::FindFlyFrm( const SvEmbeddedObject *pIPObj ) const { SwFlyFrm *pFly = FindFlyFrm(); if ( pFly && pFly->Lower() && pFly->Lower()->IsNoTxtFrm() ) { SwOLENode *pNd = ((SwNoTxtFrm*)pFly->Lower())->GetNode()->GetOLENode(); if ( !pNd || &pNd->GetOLEObj().GetOleRef() != pIPObj ) pFly = 0; } else pFly = 0; if ( !pFly ) { //Kein Fly oder der falsche selektiert. Ergo muessen wir leider suchen. BOOL bExist = FALSE; SwStartNode *pStNd; ULONG nSttIdx = GetNodes().GetEndOfAutotext().StartOfSectionIndex() + 1, nEndIdx = GetNodes().GetEndOfAutotext().GetIndex(); while( nSttIdx < nEndIdx && 0 != (pStNd = GetNodes()[ nSttIdx ]->GetStartNode()) ) { SwNode *pNd = GetNodes()[ nSttIdx+1 ]; if ( pNd->IsOLENode() && //do not load Objects! must not be neccessary here ((SwOLENode*)pNd)->GetOLEObj().IsOleRef() && &((SwOLENode*)pNd)->GetOLEObj().GetOleRef() == pIPObj ) { bExist = TRUE; SwFrm *pFrm = ((SwOLENode*)pNd)->GetFrm(); if ( pFrm ) pFly = pFrm->FindFlyFrm(); break; } nSttIdx = pStNd->EndOfSectionIndex() + 1; } ASSERT( bExist, "OLE-Object unknown and FlyFrm not found." ); } return pFly; } String SwFEShell::GetUniqueOLEName() const { return GetDoc()->GetUniqueOLEName(); } String SwFEShell::GetUniqueFrameName() const { return GetDoc()->GetUniqueFrameName(); } void SwFEShell::MakeObjVisible( const SvEmbeddedObject *pIPObj ) const { SwFlyFrm *pFly = FindFlyFrm( pIPObj ); if ( pFly ) { SwRect aTmp( pFly->Prt() ); aTmp += pFly->Frm().Pos(); if ( !aTmp.IsOver( VisArea() ) ) { ((SwFEShell*)this)->StartAction(); ((SwFEShell*)this)->MakeVisible( aTmp ); ((SwFEShell*)this)->EndAction(); } } } BOOL SwFEShell::FinishOLEObj() // Server wird beendet { SfxInPlaceClient* pIPClient = GetSfxViewShell()->GetIPClient(); BOOL bRet = pIPClient && pIPClient->IsInPlaceActive(); if( bRet ) { if( CNT_OLE == GetCntType() ) ClearAutomaticContour(); // Link fuer Daten-Highlighting im Chart zuruecksetzen SvtModuleOptions aMOpt; if( aMOpt.IsChart() ) { SvInPlaceObject* pObj = pIPClient->GetIPObj(); SvGlobalName aObjClsId( *pObj->GetSvFactory() ); SchMemChart* pMemChart; if( SchModuleDummy::HasID( aObjClsId ) && 0 != (pMemChart = SchDLL::GetChartData( pObj ) )) { pMemChart->SetSelectionHdl( Link() ); //ggfs. auch die Selektion restaurieren LockView( TRUE ); //Scrollen im EndAction verhindern ClearMark(); LockView( FALSE ); } } if( ((SwOleClient*)pIPClient)->IsCheckForOLEInCaption() != IsCheckForOLEInCaption() ) SetCheckForOLEInCaption( !IsCheckForOLEInCaption() ); //InPlace beenden. pIPClient->GetProtocol().Reset2Open(); SFX_APP()->SetViewFrame( GetSfxViewShell()->GetViewFrame() ); } return bRet; } <|endoftext|>
<commit_before>#include <string> #include <iostream> #include <codecvt> #include <locale> #include <stdexcept> #include <iomanip> #include <ctime> #include <sstream> #include <Winsock2.h> #include <windows.h> #include "utils_win.h" #include "logger.h" #include "aps_meter.h" using namespace tracker::logger; class ConslogOutput : public Output { void emit(std::wstring log_json) { std::wcout << log_json << std::endl; } }; // TODO, error logging class FluentdUdpOutput : public Output { public: FluentdUdpOutput(): port(20039), host("FLUENTD_HOST_IP_IS_HERE") { if (!initWinsock()) { throw std::runtime_error("FluentdUdpOutput: Winsock initialize error"); } } void emit(std::wstring log_json) { std::wstring_convert<std::codecvt_utf8<wchar_t>> utf8_conv; send(utf8_conv.to_bytes(log_json + L"\n")); } private: bool initWinsock(void) { WSADATA wsaData; return WSAStartup(MAKEWORD(2, 2), &wsaData) == NO_ERROR; } void send(std::string &log) { SOCKET sendSocket = INVALID_SOCKET; sockaddr_in recvAddr; sendSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); if (sendSocket == INVALID_SOCKET) { // std::cout << "create UDP socket error" << std::endl; return; } recvAddr.sin_family = AF_INET; recvAddr.sin_port = htons(port); recvAddr.sin_addr.s_addr = inet_addr(host.c_str()); if (sendto(sendSocket, log.c_str(), log.size(), 0, (SOCKADDR *)&recvAddr, sizeof(recvAddr)) == SOCKET_ERROR) { // std::cout << "UDP sendto error" << std::endl; } closesocket(sendSocket); } int port; std::string host; }; class ActivityLog : public Log { public: ActivityLog(std::wstring &stat, std::wstring &activeUsername, std::wstring &activeWindowText, std::wstring &activeFilename, int actionPerSecond) : status(stat), username(activeUsername), windowText(activeWindowText), filename(activeFilename), aps(actionPerSecond), Log(L"activity") { } std::wstring to_json(void) { return std::wstring(L"{") + L" \"status\":\"" + status + L"\"" + L",\"user\":\"" + username + L"\"" + L",\"window_text\":\"" + windowText + L"\"" + L",\"filename\":\"" + filename + L"\"" + L",\"action_per_second\":" + std::to_wstring(aps) + L" }"; } private: std::wstring status; std::wstring username; std::wstring windowText; std::wstring filename; int aps; }; class InternalLog : public Log { public: InternalLog(std::wstring lev, std::wstring msg): Log(L"log"), level(lev), message(msg) { } std::wstring to_json(void) { return std::wstring(L"{") + L" \"timestamp\":\"" + current_time_and_date() + L"\"" + L",\"level\":\"" + level + L"\"" + L",\"message\":\"" + message + L"\"}"; } private: std::wstring current_time_and_date() { std::wstringstream ss; std::time_t t = std::time(NULL); ss << std::put_time(std::localtime(&t), L"%c"); return ss.str(); } std::wstring level; std::wstring message; }; class CounterFilter : public Filter { public: CounterFilter(int cnt = 60) : max_count(cnt), count(0) { } bool apply(Log *log) { count += 1; if (count >= max_count) { count = 0; return true; } return false; } void set_max(int cnt) { count = 0; max_count = cnt; } private: int count; int max_count; }; int main(void) { using namespace tracker::utils; using namespace tracker::aps; Logger logger; FluentdUdpOutput fluentd_udp_output; logger.route(L"activity", &fluentd_udp_output); ConslogOutput consolg_output; CounterFilter counter_filter(0); consolg_output.withFilter(&counter_filter); logger.route(L"log", &consolg_output); logger.send(InternalLog(L"INFO", L"starting activity-tracker")); counter_filter.set_max(60); ActionPerSecondMeter aps; aps.start(); while (true) { HWND activeWindow = GetForegroundWindow(); DWORD activePID; GetWindowThreadProcessId(activeWindow, &activePID); std::wstring activeWindowText = getActiveWindowText(activeWindow); std::wstring activeFilename = getAcitveFilename(activePID); std::wstring activeUsername = getActiveUsername(); std::wstring status = isIdle() ? L"idle" : L"active"; int actionPerSecond = aps.getActionPerSecond(); logger.send(ActivityLog(status, activeUsername, activeWindowText, activeFilename, actionPerSecond)); logger.send(InternalLog(L"INFO", L"activity-tracker is running...")); Sleep(1000); } } <commit_msg>feature(tracker): fluentd host and ip are given from command line.<commit_after>#include <string> #include <iostream> #include <codecvt> #include <locale> #include <stdexcept> #include <iomanip> #include <ctime> #include <sstream> #include <Winsock2.h> #include <windows.h> #include "utils_win.h" #include "logger.h" #include "aps_meter.h" using namespace tracker::logger; class ConslogOutput : public Output { void emit(std::wstring log_json) { std::wcout << log_json << std::endl; } }; // TODO, error logging class FluentdUdpOutput : public Output { public: FluentdUdpOutput(std::string fluentd_host, int fluentd_port): port(fluentd_port), host(fluentd_host) { if (!initWinsock()) { throw std::runtime_error("FluentdUdpOutput: Winsock initialize error"); } } void emit(std::wstring log_json) { std::wstring_convert<std::codecvt_utf8<wchar_t>> utf8_conv; send(utf8_conv.to_bytes(log_json + L"\n")); } private: bool initWinsock(void) { WSADATA wsaData; return WSAStartup(MAKEWORD(2, 2), &wsaData) == NO_ERROR; } void send(std::string &log) { SOCKET sendSocket = INVALID_SOCKET; sockaddr_in recvAddr; sendSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); if (sendSocket == INVALID_SOCKET) { // std::cout << "create UDP socket error" << std::endl; return; } recvAddr.sin_family = AF_INET; recvAddr.sin_port = htons(port); recvAddr.sin_addr.s_addr = inet_addr(host.c_str()); if (sendto(sendSocket, log.c_str(), log.size(), 0, (SOCKADDR *)&recvAddr, sizeof(recvAddr)) == SOCKET_ERROR) { // std::cout << "UDP sendto error" << std::endl; } closesocket(sendSocket); } int port; std::string host; }; class ActivityLog : public Log { public: ActivityLog(std::wstring &stat, std::wstring &activeUsername, std::wstring &activeWindowText, std::wstring &activeFilename, int actionPerSecond) : status(stat), username(activeUsername), windowText(activeWindowText), filename(activeFilename), aps(actionPerSecond), Log(L"activity") { } std::wstring to_json(void) { return std::wstring(L"{") + L" \"status\":\"" + status + L"\"" + L",\"user\":\"" + username + L"\"" + L",\"window_text\":\"" + windowText + L"\"" + L",\"filename\":\"" + filename + L"\"" + L",\"action_per_second\":" + std::to_wstring(aps) + L" }"; } private: std::wstring status; std::wstring username; std::wstring windowText; std::wstring filename; int aps; }; class InternalLog : public Log { public: InternalLog(std::wstring lev, std::wstring msg): Log(L"log"), level(lev), message(msg) { } std::wstring to_json(void) { return std::wstring(L"{") + L" \"timestamp\":\"" + current_time_and_date() + L"\"" + L",\"level\":\"" + level + L"\"" + L",\"message\":\"" + message + L"\"}"; } private: std::wstring current_time_and_date() { std::wstringstream ss; std::time_t t = std::time(NULL); ss << std::put_time(std::localtime(&t), L"%c"); return ss.str(); } std::wstring level; std::wstring message; }; class CounterFilter : public Filter { public: CounterFilter(int cnt = 60) : max_count(cnt), count(0) { } bool apply(Log *log) { count += 1; if (count >= max_count) { count = 0; return true; } return false; } void set_max(int cnt) { count = 0; max_count = cnt; } private: int count; int max_count; }; void usage(void) { std::cout << "activity-tracker\n" "\n" "An agent of personal activity monitoring system for Windows desktop.\n" "\n" "USAGE: tracker.exe FLUENTD_HOST_IP FLUENTD_UDP_PORT\n" " tracker.exe 192.168.11.5 20039\n" << std::endl; } int main(int argc, char **argv) { using namespace tracker::utils; using namespace tracker::aps; if (argc != 3) { usage(); return 0; } std::string fluentd_host = argv[1]; int fluentd_port = std::stoi(argv[2]); Logger logger; FluentdUdpOutput fluentd_udp_output(fluentd_host, fluentd_port); logger.route(L"activity", &fluentd_udp_output); ConslogOutput consolg_output; CounterFilter counter_filter(0); consolg_output.withFilter(&counter_filter); logger.route(L"log", &consolg_output); logger.send(InternalLog(L"INFO", L"starting activity-tracker")); counter_filter.set_max(60); ActionPerSecondMeter aps; aps.start(); while (true) { HWND activeWindow = GetForegroundWindow(); DWORD activePID; GetWindowThreadProcessId(activeWindow, &activePID); std::wstring activeWindowText = getActiveWindowText(activeWindow); std::wstring activeFilename = getAcitveFilename(activePID); std::wstring activeUsername = getActiveUsername(); std::wstring status = isIdle() ? L"idle" : L"active"; int actionPerSecond = aps.getActionPerSecond(); logger.send(ActivityLog(status, activeUsername, activeWindowText, activeFilename, actionPerSecond)); logger.send(InternalLog(L"INFO", L"activity-tracker is running...")); Sleep(1000); } } <|endoftext|>
<commit_before>/*! * \file stack.cpp * \brief implementation of stack class * * \author sabertazimi, <sabertazimi@gmail.com> * \version 1.0 * \date 2016-09-30 */ #include <iostream> #include "stack.h" // add include/ path to g++ flags using namespace std; /// \brief stack instructor /// \param m stack capacity /// \return void STACK::STACK(int m): elems(m > 0 ? new int[m] : new int[0]), max(m > 0 ? m : 0) { this->pos = 0; } /// \brief deep copy stack instructor /// \param s source stack reference /// \return void STACK::STACK(const STACK &s): elems(s.elems), max(s.max) { this->pos = 0; } /// \brief get capacity of stack /// \return capacity of stack int STACK::size(void) const { return this->max; } /// \brief [type casting] get number of elements in stack /// \return number of elements in stack STACK::operator int(void) const { return (int)(this->pos); } /// \brief [operator overload] get target element with index x /// \param x index of target element /// \return tartget element with index x int STACK::operator[](int x) const { // out of range check if (x < 0 || x >= (int)(*this)) return 0; return this->elems[x]; } /// \brief [operator overload] push a new element into stack /// \param e new element to push /// \return stack reference of p STACK& STACK::operator<<(int e) { // full check if (this->size() <= (int)(*this)) return *this; this->elems[this->pos++] = e; return *this; } /// \brief [operator overload] pop a element from stack /// \param e hold value of element poped /// \return stack reference of p STACK& STACK::operator>>(int &e) { // empty check if ((int)(*this) <= 0) { e = 0; return *this; } e = this->elems[--this->pos]; return *this; } /// \brief [operator overload] assign stack p with stack s /// \param s source stack reference /// \return stack reference of p STACK& STACK::operator=(const STACK &s) { this->pos = 0; for (int i = 0; i < (int)s && i < this->size(); i++) { (*this)<<(s[i]); } return *this; } /// \brief [operator overload] equal function /// \param s source stack reference /// \return ture or false int STACK::operator==(const STACK &s) const { // size or pos should equal if (this->size() != s.size() || (int)(*this) != (int)s) return 0; // every single element should equal for (int i = 0; i < (int)(*this); i++) { if ((*this)[i] != s[i]) return 0; } return 1; } /// \brief print all elements in stack /// \return void void STACK::print(void) const { for (int i = 0; i < (int)(*this); i++) { cout<<"\t"<<(*this)[i]; } cout<<"\n"; } /// \brief destroy stack /// \return void STACK::~STACK(void) { delete this->elems; this->pos = 0; } <commit_msg>update(stack): re-format stack class code and purge redundant comments<commit_after>/*! * \file stack.cpp * \brief implementation of stack class * * \author sabertazimi, <sabertazimi@gmail.com> * \version 1.0 * \date 2016-09-30 */ #include <iostream> #include "stack.h" // add include/ path to g++ flags using namespace std; STACK::STACK(int m): elems(m > 0 ? new int[m] : new int[0]), max(m > 0 ? m : 0) { this->pos = 0; } STACK::STACK(const STACK &s): elems(s.elems), max(s.max) { this->pos = 0; } int STACK::size(void) const { return this->max; } STACK::operator int(void) const { return (int)(this->pos); } int STACK::operator[](int x) const { // out of range check if (x < 0 || x >= (int)(*this)) return 0; return this->elems[x]; } STACK& STACK::operator<<(int e) { // full check if (this->size() <= (int)(*this)) return *this; this->elems[this->pos++] = e; return *this; } STACK& STACK::operator>>(int &e) { // empty check if ((int)(*this) <= 0) { e = 0; return *this; } e = this->elems[--this->pos]; return *this; } STACK& STACK::operator=(const STACK &s) { this->pos = 0; for (int i = 0; i < (int)s && i < this->size(); i++) { (*this)<<(s[i]); } return *this; } int STACK::operator==(const STACK &s) const { // size or pos should equal if (this->size() != s.size() || (int)(*this) != (int)s) return 0; // every single element should equal for (int i = 0; i < (int)(*this); i++) { if ((*this)[i] != s[i]) return 0; } return 1; } void STACK::print(void) const { for (int i = 0; i < (int)(*this); i++) { cout<<"\t"<<(*this)[i]; } cout<<"\n"; } STACK::~STACK(void) { delete this->elems; this->pos = 0; } <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ //$Id: graphics.cpp 17 2005-03-08 23:58:43Z pavlenko $ // mapnik #include <mapnik/graphics.hpp> #include <mapnik/image_util.hpp> #include <mapnik/global.hpp> // cairo #ifdef HAVE_CAIRO #include <cairomm/surface.h> #endif #include <iostream> namespace mapnik { image_32::image_32(int width,int height) :width_(width), height_(height), data_(width,height) {} image_32::image_32(const image_32& rhs) :width_(rhs.width_), height_(rhs.height_), data_(rhs.data_) {} #ifdef HAVE_CAIRO image_32::image_32(Cairo::RefPtr<Cairo::ImageSurface> rhs) :width_(rhs->get_width()), height_(rhs->get_height()), data_(rhs->get_width(),rhs->get_height()) { if (rhs->get_format() != Cairo::FORMAT_ARGB32) { std::cerr << "Unable to convert this Cairo format\n"; return; // throw exception ?? } int stride = rhs->get_stride() / 4; unsigned int out_row[width_]; const unsigned int *in_row = (const unsigned int *)rhs->get_data(); for (unsigned int row = 0; row < height_; row++, in_row += stride) { for (unsigned int column = 0; column < width_; column++) { unsigned int in = in_row[column]; unsigned int a = (in >> 24) & 0xff; unsigned int r = (in >> 16) & 0xff; unsigned int g = (in >> 8) & 0xff; unsigned int b = (in >> 0) & 0xff; #define DE_ALPHA(x) do { \ if (a == 0) x = 0; \ else x = x * 255 / a; \ if (x > 255) x = 255; \ } while(0) DE_ALPHA(r); DE_ALPHA(g); DE_ALPHA(b); out_row[column] = color(r, g, b, a).rgba(); } data_.setRow(row, out_row, width_); } } #endif image_32::~image_32() {} void image_32::set_grayscale_to_alpha() { for (int y = 0; y < height_; ++y) { unsigned int* row_from = data_.getRow(y); for (int x = 0; x < width_; ++x) { unsigned rgba = row_from[x]; unsigned r = rgba & 0xff; unsigned g = (rgba >> 8 ) & 0xff; unsigned b = (rgba >> 16) & 0xff; // magic numbers for grayscale unsigned a = (int)((r * .3) + (g * .59) + (b * .11)); row_from[x] = (a << 24)| (255 << 16) | (255 << 8) | (255) ; } } } void image_32::set_color_to_alpha(const color& c) { } void image_32::set_alpha(float opacity) { { for (int y = 0; y < height_; ++y) { unsigned int* row_to = data_.getRow(y); for (int x = 0; x < width_; ++x) { unsigned rgba = row_to[x]; #ifdef MAPNIK_BIG_ENDIAN unsigned a0 = (rgba & 0xff); unsigned a1 = int( (rgba & 0xff) * opacity ); if (a0 == a1) continue; unsigned r = (rgba >> 24) & 0xff; unsigned g = (rgba >> 16 ) & 0xff; unsigned b = (rgba >> 8) & 0xff; row_to[x] = (a1) | (b << 8) | (g << 16) | (r << 24) ; #else unsigned a0 = (rgba >> 24) & 0xff; unsigned a1 = int( ((rgba >> 24) & 0xff) * opacity ); //unsigned a1 = opacity; if (a0 == a1) continue; unsigned r = rgba & 0xff; unsigned g = (rgba >> 8 ) & 0xff; unsigned b = (rgba >> 16) & 0xff; row_to[x] = (a1 << 24)| (b << 16) | (g << 8) | (r) ; #endif } } } } void image_32::set_background(const color& background) { background_=background; data_.set(background_.rgba()); } const color& image_32::get_background() const { return background_; } } <commit_msg>avoid compiler warnings<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ //$Id: graphics.cpp 17 2005-03-08 23:58:43Z pavlenko $ // mapnik #include <mapnik/graphics.hpp> #include <mapnik/image_util.hpp> #include <mapnik/global.hpp> // cairo #ifdef HAVE_CAIRO #include <cairomm/surface.h> #endif #include <iostream> namespace mapnik { image_32::image_32(int width,int height) :width_(width), height_(height), data_(width,height) {} image_32::image_32(const image_32& rhs) :width_(rhs.width_), height_(rhs.height_), data_(rhs.data_) {} #ifdef HAVE_CAIRO image_32::image_32(Cairo::RefPtr<Cairo::ImageSurface> rhs) :width_(rhs->get_width()), height_(rhs->get_height()), data_(rhs->get_width(),rhs->get_height()) { if (rhs->get_format() != Cairo::FORMAT_ARGB32) { std::cerr << "Unable to convert this Cairo format\n"; return; // throw exception ?? } int stride = rhs->get_stride() / 4; unsigned int out_row[width_]; const unsigned int *in_row = (const unsigned int *)rhs->get_data(); for (unsigned int row = 0; row < height_; row++, in_row += stride) { for (unsigned int column = 0; column < width_; column++) { unsigned int in = in_row[column]; unsigned int a = (in >> 24) & 0xff; unsigned int r = (in >> 16) & 0xff; unsigned int g = (in >> 8) & 0xff; unsigned int b = (in >> 0) & 0xff; #define DE_ALPHA(x) do { \ if (a == 0) x = 0; \ else x = x * 255 / a; \ if (x > 255) x = 255; \ } while(0) DE_ALPHA(r); DE_ALPHA(g); DE_ALPHA(b); out_row[column] = color(r, g, b, a).rgba(); } data_.setRow(row, out_row, width_); } } #endif image_32::~image_32() {} void image_32::set_grayscale_to_alpha() { for (unsigned int y = 0; y < height_; ++y) { unsigned int* row_from = data_.getRow(y); for (unsigned int x = 0; x < width_; ++x) { unsigned rgba = row_from[x]; // TODO - big endian support unsigned r = rgba & 0xff; unsigned g = (rgba >> 8 ) & 0xff; unsigned b = (rgba >> 16) & 0xff; // magic numbers for grayscale unsigned a = (int)((r * .3) + (g * .59) + (b * .11)); row_from[x] = (a << 24)| (255 << 16) | (255 << 8) | (255) ; } } } void image_32::set_color_to_alpha(const color& c) { } void image_32::set_alpha(float opacity) { { for (unsigned int y = 0; y < height_; ++y) { unsigned int* row_to = data_.getRow(y); for (unsigned int x = 0; x < width_; ++x) { unsigned rgba = row_to[x]; #ifdef MAPNIK_BIG_ENDIAN unsigned a0 = (rgba & 0xff); unsigned a1 = int( (rgba & 0xff) * opacity ); if (a0 == a1) continue; unsigned r = (rgba >> 24) & 0xff; unsigned g = (rgba >> 16 ) & 0xff; unsigned b = (rgba >> 8) & 0xff; row_to[x] = (a1) | (b << 8) | (g << 16) | (r << 24) ; #else unsigned a0 = (rgba >> 24) & 0xff; unsigned a1 = int( ((rgba >> 24) & 0xff) * opacity ); //unsigned a1 = opacity; if (a0 == a1) continue; unsigned r = rgba & 0xff; unsigned g = (rgba >> 8 ) & 0xff; unsigned b = (rgba >> 16) & 0xff; row_to[x] = (a1 << 24)| (b << 16) | (g << 8) | (r) ; #endif } } } } void image_32::set_background(const color& background) { background_=background; data_.set(background_.rgba()); } const color& image_32::get_background() const { return background_; } } <|endoftext|>
<commit_before>/* * trigger.cpp * * Created on: 02/01/2016 * * ========================================================================= * Copyright (C) 2015-, Daniele De Sensi (d.desensi.software@gmail.com) * * This file is part of nornir. * * nornir is free software: you can redistribute it and/or * modify it under the terms of the Lesser GNU General Public * License as published by the Free Software Foundation, either * version 3 of the License, or (at your option) any later version. * nornir 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 * Lesser GNU General Public License for more details. * * You should have received a copy of the Lesser GNU General Public * License along with nornir. * If not, see <http://www.gnu.org/licenses/>. * * ========================================================================= */ #include "trigger.hpp" namespace nornir{ TriggerQBlocking::TriggerQBlocking(TriggerConfQBlocking confQBlocking, double thresholdQBlocking, Smoother<MonitoredSample> const* samples, AdaptiveNode* emitter): _confQBlocking(confQBlocking), _thresholdQBlocking(thresholdQBlocking), _samples(samples), _emitter(emitter), _blocking(false){ ; } double TriggerQBlocking::getIdleTime() const{ MonitoredSample avg = _samples->average(); /** * Latency = Utilization * Interarrival * Idle = Interarrival - Latency * * Interarrival = Latency/Utilization * Idle = Latency/Utilization - Latency **/ // We need to convert to microsec since the threshold is specified in // microsec. double latencyMicroSec = avg.latency / 1000.0; if(!avg.utilisation){avg.utilisation = 1;} // Should never happen return latencyMicroSec / avg.utilisation - latencyMicroSec; } bool TriggerQBlocking::setBlocking(){ if(!_blocking){ _emitter->setQBlocking(); _blocking = true; return true; } return false; } bool TriggerQBlocking::setNonBlocking(){ if(_blocking){ _emitter->setQNonblocking(); _blocking = false; return true; } return false; } bool TriggerQBlocking::trigger(){ switch(_confQBlocking){ case TRIGGER_Q_BLOCKING_YES:{ return setBlocking(); }break; case TRIGGER_Q_BLOCKING_NO:{ return setNonBlocking(); }break; case TRIGGER_Q_BLOCKING_AUTO:{ double idleTime = getIdleTime(); if(idleTime > _thresholdQBlocking){ return setBlocking(); }else if(idleTime < _thresholdQBlocking){ return setNonBlocking(); } }break; } return false; } } <commit_msg>[FIX][Trigger] Bug on blocking/nonblocking switching.<commit_after>/* * trigger.cpp * * Created on: 02/01/2016 * * ========================================================================= * Copyright (C) 2015-, Daniele De Sensi (d.desensi.software@gmail.com) * * This file is part of nornir. * * nornir is free software: you can redistribute it and/or * modify it under the terms of the Lesser GNU General Public * License as published by the Free Software Foundation, either * version 3 of the License, or (at your option) any later version. * nornir 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 * Lesser GNU General Public License for more details. * * You should have received a copy of the Lesser GNU General Public * License along with nornir. * If not, see <http://www.gnu.org/licenses/>. * * ========================================================================= */ #include "trigger.hpp" namespace nornir{ TriggerQBlocking::TriggerQBlocking(TriggerConfQBlocking confQBlocking, double thresholdQBlocking, Smoother<MonitoredSample> const* samples, AdaptiveNode* emitter): _confQBlocking(confQBlocking), _thresholdQBlocking(thresholdQBlocking), _samples(samples), _emitter(emitter), _blocking(false){ ; } double TriggerQBlocking::getIdleTime() const{ MonitoredSample avg = _samples->average(); /** * Latency = Utilization * Interarrival * Idle = Interarrival - Latency * * Interarrival = Latency/Utilization * Idle = Latency/Utilization - Latency **/ // We need to convert to microsec since the threshold is specified in // microsec. double latencyMicroSec = avg.latency / 1000.0; double utilisation = avg.utilisation / 100.0; // From [0, 100] to [0, 1] if(!utilisation){utilisation = 1;} // Should never happen return latencyMicroSec / utilisation - latencyMicroSec; } bool TriggerQBlocking::setBlocking(){ if(!_blocking){ _emitter->setQBlocking(); _blocking = true; return true; } return false; } bool TriggerQBlocking::setNonBlocking(){ if(_blocking){ _emitter->setQNonblocking(); _blocking = false; return true; } return false; } bool TriggerQBlocking::trigger(){ switch(_confQBlocking){ case TRIGGER_Q_BLOCKING_YES:{ return setBlocking(); }break; case TRIGGER_Q_BLOCKING_NO:{ return setNonBlocking(); }break; case TRIGGER_Q_BLOCKING_AUTO:{ double idleTime = getIdleTime(); if(idleTime > _thresholdQBlocking){ return setBlocking(); }else if(idleTime < _thresholdQBlocking){ return setNonBlocking(); } }break; } return false; } } <|endoftext|>
<commit_before>/** * Copyright (c) 2007-2012, Timothy Stack * * 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 Timothy Stack 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 REGENTS 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 REGENTS 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. * * @file grep_proc.cc */ #include "config.h" #include <stdio.h> #include <errno.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #include <signal.h> #include <sys/types.h> #include <sys/wait.h> #include "lnav_log.hh" #include "lnav_util.hh" #include "grep_proc.hh" #include "time_T.hh" using namespace std; grep_proc::grep_proc(pcre *code, grep_proc_source &gps) : gp_pcre(code), gp_code(code), gp_source(gps), gp_pipe_offset(0), gp_child(-1), gp_child_started(false), gp_last_line(0), gp_sink(NULL), gp_control(NULL) { require(this->invariant()); } grep_proc::~grep_proc() { this->gp_queue.clear(); this->cleanup(); } void grep_proc::handle_match(int line, string &line_value, int off, int *matches, int count) { int lpc; if (off == 0) { fprintf(stdout, "%d\n", line); } fprintf(stdout, "[%d:%d]\n", matches[0], matches[1]); for (lpc = 1; lpc < count; lpc++) { fprintf(stdout, "(%d:%d)", matches[lpc * 2], matches[lpc * 2 + 1]); fwrite(&(line_value.c_str()[matches[lpc * 2]]), 1, matches[lpc * 2 + 1] - matches[lpc * 2], stdout); fputc('\n', stdout); } } void grep_proc::start(void) { require(this->invariant()); if (this->gp_child_started || this->gp_queue.empty()) { return; } auto_pipe in_pipe(STDIN_FILENO); auto_pipe out_pipe(STDOUT_FILENO); auto_pipe err_pipe(STDERR_FILENO); /* Get ahold of some pipes for stdout and stderr. */ if (out_pipe.open() < 0) { throw error(errno); } if (err_pipe.open() < 0) { throw error(errno); } if ((this->gp_child = fork()) < 0) { throw error(errno); } in_pipe.after_fork(this->gp_child); out_pipe.after_fork(this->gp_child); err_pipe.after_fork(this->gp_child); if (this->gp_child != 0) { log_perror(fcntl(out_pipe.read_end(), F_SETFL, O_NONBLOCK)); log_perror(fcntl(out_pipe.read_end(), F_SETFD, 1)); this->gp_line_buffer.set_fd(out_pipe.read_end()); log_perror(fcntl(err_pipe.read_end(), F_SETFL, O_NONBLOCK)); log_perror(fcntl(err_pipe.read_end(), F_SETFD, 1)); require(this->gp_err_pipe.get() == -1); this->gp_err_pipe = err_pipe.read_end(); this->gp_child_started = true; this->gp_queue.clear(); return; } /* In the child... */ /* * Restore the default signal handlers so we don't hang around * forever if there is a problem. */ signal(SIGINT, SIG_DFL); signal(SIGTERM, SIG_DFL); this->child_init(); this->child_loop(); _exit(0); } void grep_proc::child_loop(void) { char outbuf[BUFSIZ * 2]; string line_value; stdout = fdopen(STDOUT_FILENO, "w"); /* Make sure buffering is on, not sure of the state in the parent. */ if (setvbuf(stdout, outbuf, _IOFBF, BUFSIZ * 2) < 0) { perror("setvbuf"); } line_value.reserve(BUFSIZ * 2); while (!this->gp_queue.empty()) { grep_line_t start_line = this->gp_queue.front().first; grep_line_t stop_line = this->gp_queue.front().second; bool done = false; int line; this->gp_queue.pop_front(); if (start_line == -1) { start_line = this->gp_highest_line; } for (line = start_line; (stop_line == -1 || line < stop_line) && !done; line++) { line_value.clear(); done = !this->gp_source.grep_value_for_line(line, line_value); if (!done) { pcre_context_static<128> pc; pcre_input pi(line_value); while (this->gp_pcre.match(pc, pi)) { pcre_context::iterator pc_iter; pcre_context::capture_t *m; if (pi.pi_offset == 0) { fprintf(stdout, "%d\n", line); } m = pc.all(); fprintf(stdout, "[%d:%d]\n", m->c_begin, m->c_end); for (pc_iter = pc.begin(); pc_iter != pc.end(); pc_iter++) { if (!pc_iter->is_valid()) { continue; } fprintf(stdout, "(%d:%d)", pc_iter->c_begin, pc_iter->c_end); /* If the capture was conditional, pcre will return a -1 * here. */ if (pc_iter->c_begin >= 0) { fwrite(pi.get_substr_start(pc_iter), 1, pc_iter->length(), stdout); } fputc('\n', stdout); } fprintf(stdout, "/\n"); } } if (((line + 1) % 10000) == 0) { /* Periodically flush the buffer so the parent sees progress */ this->child_batch(); } } if (stop_line == -1) { // When scanning to the end of the source, we need to return the // highest line that was seen so that the next request that // continues from the end works properly. fprintf(stdout, "h%d\n", line - 1); } this->child_term(); } } void grep_proc::cleanup(void) { if (this->gp_child != -1 && this->gp_child != 0) { int status; kill(this->gp_child, SIGTERM); while (waitpid(this->gp_child, &status, 0) < 0 && (errno == EINTR)) { ; } require(!WIFSIGNALED(status) || WTERMSIG(status) != SIGABRT); this->gp_child = -1; this->gp_child_started = false; if (this->gp_sink) { this->gp_sink->grep_end(*this); } } if (this->gp_err_pipe != -1) { this->gp_err_pipe.reset(); } this->gp_pipe_offset = 0; this->gp_line_buffer.reset(); ensure(this->invariant()); if (!this->gp_queue.empty()) { this->start(); } } void grep_proc::dispatch_line(char *line) { int start, end, capture_start; require(line != NULL); if (sscanf(line, "h%d", this->gp_highest_line.out()) == 1) { } else if (sscanf(line, "%d", this->gp_last_line.out()) == 1) { /* Starting a new line with matches. */ ensure(this->gp_last_line >= 0); } else if (sscanf(line, "[%d:%d]", &start, &end) == 2) { require(start >= 0); require(end >= 0); /* Pass the match offsets to the sink delegate. */ if (this->gp_sink != NULL) { this->gp_sink->grep_match(*this, this->gp_last_line, start, end); } } else if (sscanf(line, "(%d:%d)%n", &start, &end, &capture_start) == 2) { require(start == -1 || start >= 0); require(end >= 0); /* Pass the captured strings to the sink delegate. */ if (this->gp_sink != NULL) { this->gp_sink->grep_capture(*this, this->gp_last_line, start, end, start < 0 ? NULL : &line[capture_start]); } } else if (line[0] == '/') { if (this->gp_sink != NULL) { this->gp_sink->grep_match_end(*this, this->gp_last_line); } } else { log_error("bad line from child -- %s", line); } } void grep_proc::check_poll_set(const std::vector<struct pollfd> &pollfds) { require(this->invariant()); if (this->gp_err_pipe != -1 && pollfd_ready(pollfds, this->gp_err_pipe)) { char buffer[1024 + 1]; ssize_t rc; rc = read(this->gp_err_pipe, buffer, sizeof(buffer) - 1); if (rc > 0) { static const char *PREFIX = ": "; buffer[rc] = '\0'; if (strncmp(buffer, PREFIX, strlen(PREFIX)) == 0) { char *lf; if ((lf = strchr(buffer, '\n')) != NULL) { *lf = '\0'; } if (this->gp_control != NULL) { this->gp_control->grep_error(&buffer[strlen(PREFIX)]); } } } else if (rc == 0) { this->gp_err_pipe.reset(); } } if (this->gp_line_buffer.get_fd() != -1 && pollfd_ready(pollfds, this->gp_line_buffer.get_fd())) { try { static const int MAX_LOOPS = 100; int loop_count = 0; line_value lv; while ((loop_count < MAX_LOOPS) && (this->gp_line_buffer.read_line(this->gp_pipe_offset, lv))) { lv.terminate(); this->dispatch_line(lv.lv_start); loop_count += 1; } if (this->gp_sink != NULL) { this->gp_sink->grep_end_batch(*this); } if ((off_t) this->gp_line_buffer.get_file_size() == this->gp_pipe_offset) { this->cleanup(); } } catch (line_buffer::error & e) { this->cleanup(); } } ensure(this->invariant()); } <commit_msg>[grep_proc] uninitialized value<commit_after>/** * Copyright (c) 2007-2012, Timothy Stack * * 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 Timothy Stack 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 REGENTS 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 REGENTS 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. * * @file grep_proc.cc */ #include "config.h" #include <stdio.h> #include <errno.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #include <signal.h> #include <sys/types.h> #include <sys/wait.h> #include "lnav_log.hh" #include "lnav_util.hh" #include "grep_proc.hh" #include "time_T.hh" using namespace std; grep_proc::grep_proc(pcre *code, grep_proc_source &gps) : gp_pcre(code), gp_code(code), gp_source(gps), gp_pipe_offset(0), gp_child(-1), gp_child_started(false), gp_last_line(0), gp_sink(NULL), gp_control(NULL) { require(this->invariant()); } grep_proc::~grep_proc() { this->gp_queue.clear(); this->cleanup(); } void grep_proc::handle_match(int line, string &line_value, int off, int *matches, int count) { int lpc; if (off == 0) { fprintf(stdout, "%d\n", line); } fprintf(stdout, "[%d:%d]\n", matches[0], matches[1]); for (lpc = 1; lpc < count; lpc++) { fprintf(stdout, "(%d:%d)", matches[lpc * 2], matches[lpc * 2 + 1]); fwrite(&(line_value.c_str()[matches[lpc * 2]]), 1, matches[lpc * 2 + 1] - matches[lpc * 2], stdout); fputc('\n', stdout); } } void grep_proc::start(void) { require(this->invariant()); if (this->gp_child_started || this->gp_queue.empty()) { return; } auto_pipe in_pipe(STDIN_FILENO); auto_pipe out_pipe(STDOUT_FILENO); auto_pipe err_pipe(STDERR_FILENO); /* Get ahold of some pipes for stdout and stderr. */ if (out_pipe.open() < 0) { throw error(errno); } if (err_pipe.open() < 0) { throw error(errno); } if ((this->gp_child = fork()) < 0) { throw error(errno); } in_pipe.after_fork(this->gp_child); out_pipe.after_fork(this->gp_child); err_pipe.after_fork(this->gp_child); if (this->gp_child != 0) { log_perror(fcntl(out_pipe.read_end(), F_SETFL, O_NONBLOCK)); log_perror(fcntl(out_pipe.read_end(), F_SETFD, 1)); this->gp_line_buffer.set_fd(out_pipe.read_end()); log_perror(fcntl(err_pipe.read_end(), F_SETFL, O_NONBLOCK)); log_perror(fcntl(err_pipe.read_end(), F_SETFD, 1)); require(this->gp_err_pipe.get() == -1); this->gp_err_pipe = err_pipe.read_end(); this->gp_child_started = true; this->gp_queue.clear(); return; } /* In the child... */ /* * Restore the default signal handlers so we don't hang around * forever if there is a problem. */ signal(SIGINT, SIG_DFL); signal(SIGTERM, SIG_DFL); this->child_init(); this->child_loop(); _exit(0); } void grep_proc::child_loop(void) { char outbuf[BUFSIZ * 2]; string line_value; stdout = fdopen(STDOUT_FILENO, "w"); /* Make sure buffering is on, not sure of the state in the parent. */ if (setvbuf(stdout, outbuf, _IOFBF, BUFSIZ * 2) < 0) { perror("setvbuf"); } line_value.reserve(BUFSIZ * 2); while (!this->gp_queue.empty()) { grep_line_t start_line = this->gp_queue.front().first; grep_line_t stop_line = this->gp_queue.front().second; bool done = false; int line; this->gp_queue.pop_front(); if (start_line == -1) { start_line = this->gp_highest_line; } for (line = start_line; (stop_line == -1 || line < stop_line) && !done; line++) { line_value.clear(); done = !this->gp_source.grep_value_for_line(line, line_value); if (!done) { pcre_context_static<128> pc; pcre_input pi(line_value); while (this->gp_pcre.match(pc, pi)) { pcre_context::iterator pc_iter; pcre_context::capture_t *m; if (pi.pi_offset == 0) { fprintf(stdout, "%d\n", line); } m = pc.all(); fprintf(stdout, "[%d:%d]\n", m->c_begin, m->c_end); for (pc_iter = pc.begin(); pc_iter != pc.end(); pc_iter++) { if (!pc_iter->is_valid()) { continue; } fprintf(stdout, "(%d:%d)", pc_iter->c_begin, pc_iter->c_end); /* If the capture was conditional, pcre will return a -1 * here. */ if (pc_iter->c_begin >= 0) { fwrite(pi.get_substr_start(pc_iter), 1, pc_iter->length(), stdout); } fputc('\n', stdout); } fprintf(stdout, "/\n"); } } if (((line + 1) % 10000) == 0) { /* Periodically flush the buffer so the parent sees progress */ this->child_batch(); } } if (stop_line == -1) { // When scanning to the end of the source, we need to return the // highest line that was seen so that the next request that // continues from the end works properly. fprintf(stdout, "h%d\n", line - 1); } this->child_term(); } } void grep_proc::cleanup(void) { if (this->gp_child != -1 && this->gp_child != 0) { int status = 0; kill(this->gp_child, SIGTERM); while (waitpid(this->gp_child, &status, 0) < 0 && (errno == EINTR)) { ; } require(!WIFSIGNALED(status) || WTERMSIG(status) != SIGABRT); this->gp_child = -1; this->gp_child_started = false; if (this->gp_sink) { this->gp_sink->grep_end(*this); } } if (this->gp_err_pipe != -1) { this->gp_err_pipe.reset(); } this->gp_pipe_offset = 0; this->gp_line_buffer.reset(); ensure(this->invariant()); if (!this->gp_queue.empty()) { this->start(); } } void grep_proc::dispatch_line(char *line) { int start, end, capture_start; require(line != NULL); if (sscanf(line, "h%d", this->gp_highest_line.out()) == 1) { } else if (sscanf(line, "%d", this->gp_last_line.out()) == 1) { /* Starting a new line with matches. */ ensure(this->gp_last_line >= 0); } else if (sscanf(line, "[%d:%d]", &start, &end) == 2) { require(start >= 0); require(end >= 0); /* Pass the match offsets to the sink delegate. */ if (this->gp_sink != NULL) { this->gp_sink->grep_match(*this, this->gp_last_line, start, end); } } else if (sscanf(line, "(%d:%d)%n", &start, &end, &capture_start) == 2) { require(start == -1 || start >= 0); require(end >= 0); /* Pass the captured strings to the sink delegate. */ if (this->gp_sink != NULL) { this->gp_sink->grep_capture(*this, this->gp_last_line, start, end, start < 0 ? NULL : &line[capture_start]); } } else if (line[0] == '/') { if (this->gp_sink != NULL) { this->gp_sink->grep_match_end(*this, this->gp_last_line); } } else { log_error("bad line from child -- %s", line); } } void grep_proc::check_poll_set(const std::vector<struct pollfd> &pollfds) { require(this->invariant()); if (this->gp_err_pipe != -1 && pollfd_ready(pollfds, this->gp_err_pipe)) { char buffer[1024 + 1]; ssize_t rc; rc = read(this->gp_err_pipe, buffer, sizeof(buffer) - 1); if (rc > 0) { static const char *PREFIX = ": "; buffer[rc] = '\0'; if (strncmp(buffer, PREFIX, strlen(PREFIX)) == 0) { char *lf; if ((lf = strchr(buffer, '\n')) != NULL) { *lf = '\0'; } if (this->gp_control != NULL) { this->gp_control->grep_error(&buffer[strlen(PREFIX)]); } } } else if (rc == 0) { this->gp_err_pipe.reset(); } } if (this->gp_line_buffer.get_fd() != -1 && pollfd_ready(pollfds, this->gp_line_buffer.get_fd())) { try { static const int MAX_LOOPS = 100; int loop_count = 0; line_value lv; while ((loop_count < MAX_LOOPS) && (this->gp_line_buffer.read_line(this->gp_pipe_offset, lv))) { lv.terminate(); this->dispatch_line(lv.lv_start); loop_count += 1; } if (this->gp_sink != NULL) { this->gp_sink->grep_end_batch(*this); } if ((off_t) this->gp_line_buffer.get_file_size() == this->gp_pipe_offset) { this->cleanup(); } } catch (line_buffer::error & e) { this->cleanup(); } } ensure(this->invariant()); } <|endoftext|>
<commit_before>// Copyright (C) 2016 Elviss Strazdins // This file is part of the Ouzel engine. #include <emscripten.h> #include "InputEm.h" #include "core/Engine.h" #include "core/Window.h" #include "events/Event.h" EM_BOOL emKeyCallback(int eventType, const EmscriptenKeyboardEvent* keyEvent, void* userData) { switch (eventType) { case EMSCRIPTEN_EVENT_KEYPRESS: case EMSCRIPTEN_EVENT_KEYDOWN: ouzel::sharedEngine->getInput()->keyDown(ouzel::input::InputEm::convertKeyCode(keyEvent->code), ouzel::input::InputEm::getKeyboardModifiers(keyEvent)); return true; case EMSCRIPTEN_EVENT_KEYUP: ouzel::sharedEngine->getInput()->keyUp(ouzel::input::InputEm::convertKeyCode(keyEvent->code), ouzel::input::InputEm::getKeyboardModifiers(keyEvent)); return true; } return false; } EM_BOOL emMouseCallback(int eventType, const EmscriptenMouseEvent* mouseEvent, void* userData) { ouzel::input::MouseButton button; switch (mouseEvent->button) { case 0: button = ouzel::input::MouseButton::LEFT; break; case 1: button = ouzel::input::MouseButton::RIGHT; break; case 2: button = ouzel::input::MouseButton::MIDDLE; break; default: button = ouzel::input::MouseButton::NONE; break; } ouzel::Vector2 position(static_cast<float>(mouseEvent->clientX), static_cast<float>(mouseEvent->clientY)); switch (eventType) { case EMSCRIPTEN_EVENT_MOUSEDOWN: ouzel::sharedEngine->getInput()->mouseDown(button, ouzel::sharedEngine->getWindow()->convertWindowToNormalizedLocation(position), ouzel::input::InputEm::getMouseModifiers(mouseEvent)); return true; case EMSCRIPTEN_EVENT_MOUSEUP: ouzel::sharedEngine->getInput()->mouseUp(button, ouzel::sharedEngine->getWindow()->convertWindowToNormalizedLocation(position), ouzel::input::InputEm::getMouseModifiers(mouseEvent)); return true; case EMSCRIPTEN_EVENT_MOUSEMOVE: ouzel::sharedEngine->getInput()->mouseMove(ouzel::sharedEngine->getWindow()->convertWindowToNormalizedLocation(position), ouzel::input::InputEm::getMouseModifiers(mouseEvent)); return true; } return false; } EM_BOOL emWheelCallback(int eventType, const EmscriptenWheelEvent* wheelEvent, void* userData) { if (eventType == EMSCRIPTEN_EVENT_WHEEL) { ouzel::Vector2 position(static_cast<float>(wheelEvent->mouse.clientX), static_cast<float>(wheelEvent->mouse.clientY)); ouzel::sharedEngine->getInput()->mouseScroll(ouzel::Vector2(static_cast<float>(wheelEvent->deltaX), static_cast<float>(wheelEvent->deltaY)), ouzel::sharedEngine->getWindow()->convertWindowToNormalizedLocation(position), ouzel::input::InputEm::getMouseModifiers(&wheelEvent->mouse)); return true; } return false; } namespace ouzel { namespace input { static std::map<std::string, KeyboardKey> keyMap = { { "Backspace", KeyboardKey::BACKSPACE }, { "Tab", KeyboardKey::TAB }, { "Enter", KeyboardKey::RETURN }, { "Shift", KeyboardKey::SHIFT }, { "ControlLeft", KeyboardKey::LCONTROL }, { "ControlRight", KeyboardKey::RCONTROL }, { "AltLeft", KeyboardKey::LALT }, { "AltRight", KeyboardKey::RALT }, { "Pause", KeyboardKey::PAUSE }, { "CapsLock", KeyboardKey::CAPITAL }, { "Escape", KeyboardKey::ESCAPE }, { "PageUp", KeyboardKey::PRIOR }, { "PageDown", KeyboardKey::NEXT }, { "Home", KeyboardKey::HOME }, { "End", KeyboardKey::END }, { "ArrowLeft", KeyboardKey::LEFT }, { "ArrowUp", KeyboardKey::UP }, { "ArrowRight", KeyboardKey::RIGHT }, { "ArrowDown", KeyboardKey::DOWN }, { "Insert", KeyboardKey::INSERT }, { "Delete", KeyboardKey::DEL }, { "Digit0", KeyboardKey::KEY_0 }, { "Digit1", KeyboardKey::KEY_1 }, { "Digit2", KeyboardKey::KEY_2 }, { "Digit3", KeyboardKey::KEY_3 }, { "Digit4", KeyboardKey::KEY_4 }, { "Digit5", KeyboardKey::KEY_5 }, { "Digit6", KeyboardKey::KEY_6 }, { "Digit7", KeyboardKey::KEY_7 }, { "Digit8", KeyboardKey::KEY_8 }, { "Digit9", KeyboardKey::KEY_9 }, { "KeyA", KeyboardKey::KEY_A }, { "KeyB", KeyboardKey::KEY_B }, { "KeyC", KeyboardKey::KEY_C }, { "KeyD", KeyboardKey::KEY_D }, { "KeyE", KeyboardKey::KEY_E }, { "KeyF", KeyboardKey::KEY_F }, { "KeyG", KeyboardKey::KEY_G }, { "KeyH", KeyboardKey::KEY_H }, { "KeyI", KeyboardKey::KEY_I }, { "KeyJ", KeyboardKey::KEY_J }, { "KeyK", KeyboardKey::KEY_K }, { "KeyL", KeyboardKey::KEY_L }, { "KeyM", KeyboardKey::KEY_M }, { "KeyN", KeyboardKey::KEY_N }, { "KeyO", KeyboardKey::KEY_O }, { "KeyP", KeyboardKey::KEY_P }, { "KeyQ", KeyboardKey::KEY_Q }, { "KeyR", KeyboardKey::KEY_R }, { "KeyS", KeyboardKey::KEY_S }, { "KeyT", KeyboardKey::KEY_T }, { "KeyU", KeyboardKey::KEY_U }, { "KeyV", KeyboardKey::KEY_V }, { "KeyW", KeyboardKey::KEY_W }, { "KeyX", KeyboardKey::KEY_X }, { "KeyY", KeyboardKey::KEY_Y }, { "KeyZ", KeyboardKey::KEY_Z }, { "OSLeft", KeyboardKey::LWIN }, { "OSRight", KeyboardKey::RWIN }, { "Delete", KeyboardKey::DEL }, { "NumpadEnter", KeyboardKey::SEPARATOR }, { "NumpadDigit0", KeyboardKey::NUMPAD0 }, { "NumpadDigit1", KeyboardKey::NUMPAD1 }, { "NumpadDigit2", KeyboardKey::NUMPAD2 }, { "NumpadDigit3", KeyboardKey::NUMPAD3 }, { "NumpadDigit4", KeyboardKey::NUMPAD4 }, { "NumpadDigit5", KeyboardKey::NUMPAD5 }, { "NumpadDigit6", KeyboardKey::NUMPAD6 }, { "NumpadDigit7", KeyboardKey::NUMPAD7 }, { "NumpadDigit8", KeyboardKey::NUMPAD8 }, { "NumpadDigit9", KeyboardKey::NUMPAD9 }, { "NumpadMultiply", KeyboardKey::MULTIPLY }, { "NumpadAdd", KeyboardKey::ADD }, { "NumpadSubtract", KeyboardKey::SUBTRACT }, { "NumpadDecimal", KeyboardKey::DECIMAL }, { "NumpadDivide", KeyboardKey::DIVIDE }, { "F1", KeyboardKey::F1 }, { "F2", KeyboardKey::F2 }, { "F3", KeyboardKey::F3 }, { "F4", KeyboardKey::F4 }, { "F5", KeyboardKey::F5 }, { "F6", KeyboardKey::F6 }, { "F7", KeyboardKey::F7 }, { "F8", KeyboardKey::F8 }, { "F9", KeyboardKey::F9 }, { "F10", KeyboardKey::F10 }, { "F11", KeyboardKey::F11 }, { "F12", KeyboardKey::F12 }, { "NumLock", KeyboardKey::NUMLOCK }, { "ScrollLock", KeyboardKey::SCROLL }, { "Semicolon", KeyboardKey::SEMICOLON }, { "Equal", KeyboardKey::EQUAL }, { "Comma", KeyboardKey::COMMA }, { "Minus", KeyboardKey::MINUS }, { "Period", KeyboardKey::PERIOD }, { "Slash", KeyboardKey::SLASH }, { "Backquote", KeyboardKey::GRAVE }, { "BracketLeft", KeyboardKey::BRACKET_LEFT }, { "Backslash", KeyboardKey::BACKSLASH }, { "BracketRight", KeyboardKey::BRACKET_RIGHT }, { "Quote", KeyboardKey::BRACKET_RIGHT }, { "IntlBackslash", KeyboardKey::LESS } }; InputEm::InputEm() { emscripten_set_keypress_callback(nullptr, this, 1, emKeyCallback); emscripten_set_keydown_callback(nullptr, this, 1, emKeyCallback); emscripten_set_keyup_callback(nullptr, this, 1, emKeyCallback); emscripten_set_mousedown_callback("#canvas", this, 1, emMouseCallback); emscripten_set_mouseup_callback("#canvas", this, 1, emMouseCallback); emscripten_set_mousemove_callback("#canvas", this, 1, emMouseCallback); emscripten_set_wheel_callback("#canvas", this, 1, emWheelCallback); } InputEm::~InputEm() { } KeyboardKey InputEm::convertKeyCode(const EM_UTF8 key[32]) { auto i = keyMap.find(key); if (i != keyMap.end()) { return i->second; } else { return KeyboardKey::NONE; } } uint32_t InputEm::getKeyboardModifiers(const EmscriptenKeyboardEvent* keyboardEvent) { uint32_t modifiers = 0; if (keyboardEvent->ctrlKey) modifiers |= ouzel::CONTROL_DOWN; if (keyboardEvent->shiftKey) modifiers |= ouzel::SHIFT_DOWN; if (keyboardEvent->altKey) modifiers |= ouzel::ALT_DOWN; if (keyboardEvent->metaKey) modifiers |= ouzel::COMMAND_DOWN; return modifiers; } uint32_t InputEm::getMouseModifiers(const EmscriptenMouseEvent* mouseEvent) { uint32_t modifiers = 0; if (mouseEvent->ctrlKey) modifiers |= ouzel::CONTROL_DOWN; if (mouseEvent->shiftKey) modifiers |= ouzel::SHIFT_DOWN; if (mouseEvent->altKey) modifiers |= ouzel::ALT_DOWN; if (mouseEvent->metaKey) modifiers |= ouzel::COMMAND_DOWN; return modifiers; } void InputEm::setCursorVisible(bool visible) { if (!visible) { cursorVisible = visible; emscripten_hide_mouse(); } } bool InputEm::isCursorVisible() const { return cursorVisible; } } // namespace input } // namespace ouzel <commit_msg>Fix Emscripten key conversion code Log warning when trying to show cursor on Emscripten target<commit_after>// Copyright (C) 2016 Elviss Strazdins // This file is part of the Ouzel engine. #include <emscripten.h> #include "InputEm.h" #include "core/Engine.h" #include "core/Window.h" #include "events/Event.h" #include "utils/Utils.h" EM_BOOL emKeyCallback(int eventType, const EmscriptenKeyboardEvent* keyEvent, void* userData) { switch (eventType) { case EMSCRIPTEN_EVENT_KEYPRESS: case EMSCRIPTEN_EVENT_KEYDOWN: ouzel::sharedEngine->getInput()->keyDown(ouzel::input::InputEm::convertKeyCode(keyEvent->code), ouzel::input::InputEm::getKeyboardModifiers(keyEvent)); return true; case EMSCRIPTEN_EVENT_KEYUP: ouzel::sharedEngine->getInput()->keyUp(ouzel::input::InputEm::convertKeyCode(keyEvent->code), ouzel::input::InputEm::getKeyboardModifiers(keyEvent)); return true; } return false; } EM_BOOL emMouseCallback(int eventType, const EmscriptenMouseEvent* mouseEvent, void* userData) { ouzel::input::MouseButton button; switch (mouseEvent->button) { case 0: button = ouzel::input::MouseButton::LEFT; break; case 1: button = ouzel::input::MouseButton::RIGHT; break; case 2: button = ouzel::input::MouseButton::MIDDLE; break; default: button = ouzel::input::MouseButton::NONE; break; } ouzel::Vector2 position(static_cast<float>(mouseEvent->clientX), static_cast<float>(mouseEvent->clientY)); switch (eventType) { case EMSCRIPTEN_EVENT_MOUSEDOWN: ouzel::sharedEngine->getInput()->mouseDown(button, ouzel::sharedEngine->getWindow()->convertWindowToNormalizedLocation(position), ouzel::input::InputEm::getMouseModifiers(mouseEvent)); return true; case EMSCRIPTEN_EVENT_MOUSEUP: ouzel::sharedEngine->getInput()->mouseUp(button, ouzel::sharedEngine->getWindow()->convertWindowToNormalizedLocation(position), ouzel::input::InputEm::getMouseModifiers(mouseEvent)); return true; case EMSCRIPTEN_EVENT_MOUSEMOVE: ouzel::sharedEngine->getInput()->mouseMove(ouzel::sharedEngine->getWindow()->convertWindowToNormalizedLocation(position), ouzel::input::InputEm::getMouseModifiers(mouseEvent)); return true; } return false; } EM_BOOL emWheelCallback(int eventType, const EmscriptenWheelEvent* wheelEvent, void* userData) { if (eventType == EMSCRIPTEN_EVENT_WHEEL) { ouzel::Vector2 position(static_cast<float>(wheelEvent->mouse.clientX), static_cast<float>(wheelEvent->mouse.clientY)); ouzel::sharedEngine->getInput()->mouseScroll(ouzel::Vector2(static_cast<float>(wheelEvent->deltaX), static_cast<float>(wheelEvent->deltaY)), ouzel::sharedEngine->getWindow()->convertWindowToNormalizedLocation(position), ouzel::input::InputEm::getMouseModifiers(&wheelEvent->mouse)); return true; } return false; } namespace ouzel { namespace input { static std::map<std::string, KeyboardKey> keyMap = { { "Backspace", KeyboardKey::BACKSPACE }, { "Tab", KeyboardKey::TAB }, { "Enter", KeyboardKey::RETURN }, { "Shift", KeyboardKey::SHIFT }, { "ControlLeft", KeyboardKey::LCONTROL }, { "ControlRight", KeyboardKey::RCONTROL }, { "AltLeft", KeyboardKey::LALT }, { "AltRight", KeyboardKey::RALT }, { "Pause", KeyboardKey::PAUSE }, { "CapsLock", KeyboardKey::CAPITAL }, { "Escape", KeyboardKey::ESCAPE }, { "PageUp", KeyboardKey::PRIOR }, { "PageDown", KeyboardKey::NEXT }, { "Home", KeyboardKey::HOME }, { "End", KeyboardKey::END }, { "ArrowLeft", KeyboardKey::LEFT }, { "ArrowUp", KeyboardKey::UP }, { "ArrowRight", KeyboardKey::RIGHT }, { "ArrowDown", KeyboardKey::DOWN }, { "Insert", KeyboardKey::INSERT }, { "Delete", KeyboardKey::DEL }, { "Digit0", KeyboardKey::KEY_0 }, { "Digit1", KeyboardKey::KEY_1 }, { "Digit2", KeyboardKey::KEY_2 }, { "Digit3", KeyboardKey::KEY_3 }, { "Digit4", KeyboardKey::KEY_4 }, { "Digit5", KeyboardKey::KEY_5 }, { "Digit6", KeyboardKey::KEY_6 }, { "Digit7", KeyboardKey::KEY_7 }, { "Digit8", KeyboardKey::KEY_8 }, { "Digit9", KeyboardKey::KEY_9 }, { "KeyA", KeyboardKey::KEY_A }, { "KeyB", KeyboardKey::KEY_B }, { "KeyC", KeyboardKey::KEY_C }, { "KeyD", KeyboardKey::KEY_D }, { "KeyE", KeyboardKey::KEY_E }, { "KeyF", KeyboardKey::KEY_F }, { "KeyG", KeyboardKey::KEY_G }, { "KeyH", KeyboardKey::KEY_H }, { "KeyI", KeyboardKey::KEY_I }, { "KeyJ", KeyboardKey::KEY_J }, { "KeyK", KeyboardKey::KEY_K }, { "KeyL", KeyboardKey::KEY_L }, { "KeyM", KeyboardKey::KEY_M }, { "KeyN", KeyboardKey::KEY_N }, { "KeyO", KeyboardKey::KEY_O }, { "KeyP", KeyboardKey::KEY_P }, { "KeyQ", KeyboardKey::KEY_Q }, { "KeyR", KeyboardKey::KEY_R }, { "KeyS", KeyboardKey::KEY_S }, { "KeyT", KeyboardKey::KEY_T }, { "KeyU", KeyboardKey::KEY_U }, { "KeyV", KeyboardKey::KEY_V }, { "KeyW", KeyboardKey::KEY_W }, { "KeyX", KeyboardKey::KEY_X }, { "KeyY", KeyboardKey::KEY_Y }, { "KeyZ", KeyboardKey::KEY_Z }, { "OSLeft", KeyboardKey::LSUPER }, { "OSRight", KeyboardKey::RSUPER }, { "Delete", KeyboardKey::DEL }, { "NumpadEnter", KeyboardKey::SEPARATOR }, { "NumpadDigit0", KeyboardKey::NUMPAD0 }, { "NumpadDigit1", KeyboardKey::NUMPAD1 }, { "NumpadDigit2", KeyboardKey::NUMPAD2 }, { "NumpadDigit3", KeyboardKey::NUMPAD3 }, { "NumpadDigit4", KeyboardKey::NUMPAD4 }, { "NumpadDigit5", KeyboardKey::NUMPAD5 }, { "NumpadDigit6", KeyboardKey::NUMPAD6 }, { "NumpadDigit7", KeyboardKey::NUMPAD7 }, { "NumpadDigit8", KeyboardKey::NUMPAD8 }, { "NumpadDigit9", KeyboardKey::NUMPAD9 }, { "NumpadMultiply", KeyboardKey::MULTIPLY }, { "NumpadAdd", KeyboardKey::ADD }, { "NumpadSubtract", KeyboardKey::SUBTRACT }, { "NumpadDecimal", KeyboardKey::DECIMAL }, { "NumpadDivide", KeyboardKey::DIVIDE }, { "F1", KeyboardKey::F1 }, { "F2", KeyboardKey::F2 }, { "F3", KeyboardKey::F3 }, { "F4", KeyboardKey::F4 }, { "F5", KeyboardKey::F5 }, { "F6", KeyboardKey::F6 }, { "F7", KeyboardKey::F7 }, { "F8", KeyboardKey::F8 }, { "F9", KeyboardKey::F9 }, { "F10", KeyboardKey::F10 }, { "F11", KeyboardKey::F11 }, { "F12", KeyboardKey::F12 }, { "NumLock", KeyboardKey::NUMLOCK }, { "ScrollLock", KeyboardKey::SCROLL }, { "Semicolon", KeyboardKey::SEMICOLON }, { "Equal", KeyboardKey::EQUAL }, { "Comma", KeyboardKey::COMMA }, { "Minus", KeyboardKey::MINUS }, { "Period", KeyboardKey::PERIOD }, { "Slash", KeyboardKey::SLASH }, { "Backquote", KeyboardKey::GRAVE }, { "BracketLeft", KeyboardKey::BRACKET_LEFT }, { "Backslash", KeyboardKey::BACKSLASH }, { "BracketRight", KeyboardKey::BRACKET_RIGHT }, { "Quote", KeyboardKey::BRACKET_RIGHT }, { "IntlBackslash", KeyboardKey::LESS } }; InputEm::InputEm() { emscripten_set_keypress_callback(nullptr, this, 1, emKeyCallback); emscripten_set_keydown_callback(nullptr, this, 1, emKeyCallback); emscripten_set_keyup_callback(nullptr, this, 1, emKeyCallback); emscripten_set_mousedown_callback("#canvas", this, 1, emMouseCallback); emscripten_set_mouseup_callback("#canvas", this, 1, emMouseCallback); emscripten_set_mousemove_callback("#canvas", this, 1, emMouseCallback); emscripten_set_wheel_callback("#canvas", this, 1, emWheelCallback); } InputEm::~InputEm() { } KeyboardKey InputEm::convertKeyCode(const EM_UTF8 key[32]) { auto i = keyMap.find(key); if (i != keyMap.end()) { return i->second; } else { return KeyboardKey::NONE; } } uint32_t InputEm::getKeyboardModifiers(const EmscriptenKeyboardEvent* keyboardEvent) { uint32_t modifiers = 0; if (keyboardEvent->ctrlKey) modifiers |= ouzel::CONTROL_DOWN; if (keyboardEvent->shiftKey) modifiers |= ouzel::SHIFT_DOWN; if (keyboardEvent->altKey) modifiers |= ouzel::ALT_DOWN; if (keyboardEvent->metaKey) modifiers |= ouzel::SUPER_DOWN; return modifiers; } uint32_t InputEm::getMouseModifiers(const EmscriptenMouseEvent* mouseEvent) { uint32_t modifiers = 0; if (mouseEvent->ctrlKey) modifiers |= ouzel::CONTROL_DOWN; if (mouseEvent->shiftKey) modifiers |= ouzel::SHIFT_DOWN; if (mouseEvent->altKey) modifiers |= ouzel::ALT_DOWN; if (mouseEvent->metaKey) modifiers |= ouzel::SUPER_DOWN; return modifiers; } void InputEm::setCursorVisible(bool visible) { if (!visible) { cursorVisible = visible; emscripten_hide_mouse(); } else { log(LOG_LEVEL_WARNING, "Cursors showing is not implemented for Emscripten target"); } } bool InputEm::isCursorVisible() const { return cursorVisible; } } // namespace input } // namespace ouzel <|endoftext|>
<commit_before>//===--- swift-demangle.cpp - Swift Demangler app -------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // This is the entry point. // //===----------------------------------------------------------------------===// #include "swift/Basic/DemangleWrappers.h" #include "swift/Basic/ManglingMacros.h" #include "llvm/ADT/SmallString.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/PrettyStackTrace.h" #include "llvm/Support/Regex.h" #include "llvm/Support/Signals.h" #include "llvm/Support/raw_ostream.h" // For std::rand, to work around a bug if main()'s first function call passes // argv[0]. #if defined(__CYGWIN__) #include <cstdlib> #endif #include <iostream> static llvm::cl::opt<bool> ExpandMode("expand", llvm::cl::desc("Expand mode (show node structure of the demangling)")); static llvm::cl::opt<bool> CompactMode("compact", llvm::cl::desc("Compact mode (only emit the demangled names)")); static llvm::cl::opt<bool> TreeOnly("tree-only", llvm::cl::desc("Tree-only mode (do not show the demangled string)")); static llvm::cl::opt<bool> RemangleMode("test-remangle", llvm::cl::desc("Remangle test mode (show the remangled string)")); static llvm::cl::opt<bool> DisableSugar("no-sugar", llvm::cl::desc("No sugar mode (disable common language idioms such as ? and [] from the output)")); static llvm::cl::opt<bool> Simplified("simplified", llvm::cl::desc("Don't display module names or implicit self types")); static llvm::cl::list<std::string> InputNames(llvm::cl::Positional, llvm::cl::desc("[mangled name...]"), llvm::cl::ZeroOrMore); static llvm::StringRef substrBefore(llvm::StringRef whole, llvm::StringRef part) { return whole.slice(0, part.data() - whole.data()); } static llvm::StringRef substrAfter(llvm::StringRef whole, llvm::StringRef part) { return whole.substr((part.data() - whole.data()) + part.size()); } static void demangle(llvm::raw_ostream &os, llvm::StringRef name, const swift::Demangle::DemangleOptions &options) { bool hadLeadingUnderscore = false; if (name.startswith("__")) { hadLeadingUnderscore = true; name = name.substr(1); } swift::Demangle::NodePointer pointer = swift::demangle_wrappers::demangleSymbolAsNode(name); if (ExpandMode || TreeOnly) { llvm::outs() << "Demangling for " << name << '\n'; swift::demangle_wrappers::NodeDumper(pointer).print(llvm::outs()); } if (RemangleMode) { std::string remangled; if (!pointer) { // Just reprint the original mangled name if it didn't demangle. // This makes it easier to share the same database between the // mangling and demangling tests. remangled = name; } else { remangled = swift::Demangle::mangleNode(pointer, /*NewMangling*/ name.startswith(MANGLING_PREFIX_STR)); if (name != remangled) { llvm::errs() << "\nError: re-mangled name \n " << remangled << "\ndoes not match original name\n " << name << '\n'; exit(1); } } if (hadLeadingUnderscore) llvm::outs() << '_'; llvm::outs() << remangled; return; } if (!TreeOnly) { std::string string = swift::Demangle::nodeToString(pointer, options); if (!CompactMode) llvm::outs() << name << " ---> "; llvm::outs() << (string.empty() ? name : llvm::StringRef(string)); } } static int demangleSTDIN(const swift::Demangle::DemangleOptions &options) { // This doesn't handle Unicode symbols, but maybe that's okay. llvm::Regex maybeSymbol("(_T|" MANGLING_PREFIX_STR ")[_a-zA-Z0-9$]+"); for (std::string mangled; std::getline(std::cin, mangled);) { llvm::StringRef inputContents(mangled); llvm::SmallVector<llvm::StringRef, 1> matches; while (maybeSymbol.match(inputContents, &matches)) { llvm::outs() << substrBefore(inputContents, matches.front()); demangle(llvm::outs(), matches.front(), options); inputContents = substrAfter(inputContents, matches.front()); } llvm::outs() << inputContents << '\n'; } return EXIT_SUCCESS; } int main(int argc, char **argv) { #if defined(__CYGWIN__) // Cygwin clang 3.5.2 with '-O3' generates CRASHING BINARY, // if main()'s first function call is passing argv[0]. std::rand(); #endif llvm::cl::ParseCommandLineOptions(argc, argv); swift::Demangle::DemangleOptions options; options.SynthesizeSugarOnTypes = !DisableSugar; if (Simplified) options = swift::Demangle::DemangleOptions::SimplifiedUIDemangleOptions(); if (InputNames.empty()) { CompactMode = true; return demangleSTDIN(options); } else { for (llvm::StringRef name : InputNames) { demangle(llvm::outs(), name, options); llvm::outs() << '\n'; } return EXIT_SUCCESS; } } <commit_msg>swift-demangle: add -remangle-new option<commit_after>//===--- swift-demangle.cpp - Swift Demangler app -------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // This is the entry point. // //===----------------------------------------------------------------------===// #include "swift/Basic/DemangleWrappers.h" #include "swift/Basic/ManglingMacros.h" #include "llvm/ADT/SmallString.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/PrettyStackTrace.h" #include "llvm/Support/Regex.h" #include "llvm/Support/Signals.h" #include "llvm/Support/raw_ostream.h" // For std::rand, to work around a bug if main()'s first function call passes // argv[0]. #if defined(__CYGWIN__) #include <cstdlib> #endif #include <iostream> static llvm::cl::opt<bool> ExpandMode("expand", llvm::cl::desc("Expand mode (show node structure of the demangling)")); static llvm::cl::opt<bool> CompactMode("compact", llvm::cl::desc("Compact mode (only emit the demangled names)")); static llvm::cl::opt<bool> TreeOnly("tree-only", llvm::cl::desc("Tree-only mode (do not show the demangled string)")); static llvm::cl::opt<bool> RemangleMode("test-remangle", llvm::cl::desc("Remangle test mode (show the remangled string)")); static llvm::cl::opt<bool> RemangleNew("remangle-new", llvm::cl::desc("Remangle the symbol with new mangling scheme")); static llvm::cl::opt<bool> DisableSugar("no-sugar", llvm::cl::desc("No sugar mode (disable common language idioms such as ? and [] from the output)")); static llvm::cl::opt<bool> Simplified("simplified", llvm::cl::desc("Don't display module names or implicit self types")); static llvm::cl::list<std::string> InputNames(llvm::cl::Positional, llvm::cl::desc("[mangled name...]"), llvm::cl::ZeroOrMore); static llvm::StringRef substrBefore(llvm::StringRef whole, llvm::StringRef part) { return whole.slice(0, part.data() - whole.data()); } static llvm::StringRef substrAfter(llvm::StringRef whole, llvm::StringRef part) { return whole.substr((part.data() - whole.data()) + part.size()); } static void demangle(llvm::raw_ostream &os, llvm::StringRef name, const swift::Demangle::DemangleOptions &options) { bool hadLeadingUnderscore = false; if (name.startswith("__")) { hadLeadingUnderscore = true; name = name.substr(1); } swift::Demangle::NodePointer pointer = swift::demangle_wrappers::demangleSymbolAsNode(name); if (ExpandMode || TreeOnly) { llvm::outs() << "Demangling for " << name << '\n'; swift::demangle_wrappers::NodeDumper(pointer).print(llvm::outs()); } if (RemangleMode) { std::string remangled; if (!pointer) { // Just reprint the original mangled name if it didn't demangle. // This makes it easier to share the same database between the // mangling and demangling tests. remangled = name; } else { remangled = swift::Demangle::mangleNode(pointer, /*NewMangling*/ name.startswith(MANGLING_PREFIX_STR)); if (name != remangled) { llvm::errs() << "\nError: re-mangled name \n " << remangled << "\ndoes not match original name\n " << name << '\n'; exit(1); } } if (hadLeadingUnderscore) llvm::outs() << '_'; llvm::outs() << remangled; return; } if (!TreeOnly) { if (RemangleNew) { if (!pointer) { llvm::errs() << "Can't de-mangle " << name << '\n'; exit(1); } std::string remangled = swift::Demangle::mangleNodeNew(pointer); llvm::outs() << remangled; return; } std::string string = swift::Demangle::nodeToString(pointer, options); if (!CompactMode) llvm::outs() << name << " ---> "; llvm::outs() << (string.empty() ? name : llvm::StringRef(string)); } } static int demangleSTDIN(const swift::Demangle::DemangleOptions &options) { // This doesn't handle Unicode symbols, but maybe that's okay. llvm::Regex maybeSymbol("(_T|" MANGLING_PREFIX_STR ")[_a-zA-Z0-9$]+"); for (std::string mangled; std::getline(std::cin, mangled);) { llvm::StringRef inputContents(mangled); llvm::SmallVector<llvm::StringRef, 1> matches; while (maybeSymbol.match(inputContents, &matches)) { llvm::outs() << substrBefore(inputContents, matches.front()); demangle(llvm::outs(), matches.front(), options); inputContents = substrAfter(inputContents, matches.front()); } llvm::outs() << inputContents << '\n'; } return EXIT_SUCCESS; } int main(int argc, char **argv) { #if defined(__CYGWIN__) // Cygwin clang 3.5.2 with '-O3' generates CRASHING BINARY, // if main()'s first function call is passing argv[0]. std::rand(); #endif llvm::cl::ParseCommandLineOptions(argc, argv); swift::Demangle::DemangleOptions options; options.SynthesizeSugarOnTypes = !DisableSugar; if (Simplified) options = swift::Demangle::DemangleOptions::SimplifiedUIDemangleOptions(); if (InputNames.empty()) { CompactMode = true; return demangleSTDIN(options); } else { for (llvm::StringRef name : InputNames) { demangle(llvm::outs(), name, options); llvm::outs() << '\n'; } return EXIT_SUCCESS; } } <|endoftext|>
<commit_before>/* rescoring1D.C * * Copyright (C) 2011 Marcel Schumann * * This program 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 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 * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see <http://www.gnu.org/licenses/>. */ // ---------------------------------------------------- // $Maintainer: Marcel Schumann $ // $Authors: Marcel Schumann $ // ---------------------------------------------------- #include <BALL/SCORING/FUNCTIONS/rescoring1D.h> #include <BALL/KERNEL/molecularInteractions.h> namespace BALL { Rescoring1D::Rescoring1D(AtomContainer& receptor, AtomContainer& reference_ligand, Options& options, String free_energy_label, ScoringFunction* sf) : Rescoring(receptor, reference_ligand, options, free_energy_label, sf) { name_ = "Rescoring1D"; use_calibration_ = 1; setup_(); } void Rescoring1D::setup_() { scoring_function_->enableStoreInteractions(1); Protein* protein = dynamic_cast<Protein*>(scoring_function_->getReceptor()); if (!protein) { System* sys = dynamic_cast<System*>(scoring_function_->getReceptor()); if (sys) { protein = sys->getProtein(0); } } if (protein) { protein_ = protein; } else { throw BALL::Exception::GeneralException(__FILE__, __LINE__, "Rescoring1D setup error", "No Protein found in receptor object"); } } void Rescoring1D::generateScoreContributions_(vector<vector<double> >* matrix, vector<double>* v) { Size column_no = 0; for (ResidueConstIterator it = protein_->beginResidue(); +it; it++, column_no++) { double score = 0; for (AtomConstIterator it2 = it->beginAtom(); +it2; it2++) { if (it2->interactions) score += it2->interactions->getInteractionEnergy(); } if (matrix) { (*matrix)[column_no].push_back(score); } else if (v) { v->push_back(score); } } } } <commit_msg>Clarified licence<commit_after>// ---------------------------------------------------- // $Maintainer: Marcel Schumann $ // $Authors: Marcel Schumann $ // ---------------------------------------------------- #include <BALL/SCORING/FUNCTIONS/rescoring1D.h> #include <BALL/KERNEL/molecularInteractions.h> namespace BALL { Rescoring1D::Rescoring1D(AtomContainer& receptor, AtomContainer& reference_ligand, Options& options, String free_energy_label, ScoringFunction* sf) : Rescoring(receptor, reference_ligand, options, free_energy_label, sf) { name_ = "Rescoring1D"; use_calibration_ = 1; setup_(); } void Rescoring1D::setup_() { scoring_function_->enableStoreInteractions(1); Protein* protein = dynamic_cast<Protein*>(scoring_function_->getReceptor()); if (!protein) { System* sys = dynamic_cast<System*>(scoring_function_->getReceptor()); if (sys) { protein = sys->getProtein(0); } } if (protein) { protein_ = protein; } else { throw BALL::Exception::GeneralException(__FILE__, __LINE__, "Rescoring1D setup error", "No Protein found in receptor object"); } } void Rescoring1D::generateScoreContributions_(vector<vector<double> >* matrix, vector<double>* v) { Size column_no = 0; for (ResidueConstIterator it = protein_->beginResidue(); +it; it++, column_no++) { double score = 0; for (AtomConstIterator it2 = it->beginAtom(); +it2; it2++) { if (it2->interactions) score += it2->interactions->getInteractionEnergy(); } if (matrix) { (*matrix)[column_no].push_back(score); } else if (v) { v->push_back(score); } } } } <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// /// /// A buffer class for temporarily storaging sound samples, operates as a /// first-in-first-out pipe. /// /// Samples are added to the end of the sample buffer with the 'putSamples' /// function, and are received from the beginning of the buffer by calling /// the 'receiveSamples' function. The class automatically removes the /// outputted samples from the buffer, as well as grows the buffer size /// whenever necessary. /// /// Author : Copyright (c) Olli Parviainen /// Author e-mail : oparviai 'at' iki.fi /// SoundTouch WWW: http://www.surina.net/soundtouch /// //////////////////////////////////////////////////////////////////////////////// // // Last changed : $Date$ // File revision : $Revision: 4 $ // // $Id$ // //////////////////////////////////////////////////////////////////////////////// // // License : // // SoundTouch audio processing library // Copyright (c) Olli Parviainen // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // //////////////////////////////////////////////////////////////////////////////// #include <stdlib.h> #include <memory.h> #include <string.h> #include <assert.h> #include <stdexcept> #include "FIFOSampleBuffer.h" using namespace soundtouch; // Constructor FIFOSampleBuffer::FIFOSampleBuffer(int numChannels) { assert(numChannels > 0); sizeInBytes = 0; // reasonable initial value buffer = NULL; bufferUnaligned = NULL; samplesInBuffer = 0; bufferPos = 0; channels = (uint)numChannels; ensureCapacity(32); // allocate initial capacity } // destructor FIFOSampleBuffer::~FIFOSampleBuffer() { delete[] bufferUnaligned; bufferUnaligned = NULL; buffer = NULL; } // Sets number of channels, 1 = mono, 2 = stereo void FIFOSampleBuffer::setChannels(int numChannels) { uint usedBytes; assert(numChannels > 0); usedBytes = channels * samplesInBuffer; channels = (uint)numChannels; samplesInBuffer = usedBytes / channels; } // if output location pointer 'bufferPos' isn't zero, 'rewinds' the buffer and // zeroes this pointer by copying samples from the 'bufferPos' pointer // location on to the beginning of the buffer. void FIFOSampleBuffer::rewind() { if (buffer && bufferPos) { memmove(buffer, ptrBegin(), sizeof(SAMPLETYPE) * channels * samplesInBuffer); bufferPos = 0; } } // Adds 'numSamples' pcs of samples from the 'samples' memory position to // the sample buffer. void FIFOSampleBuffer::putSamples(const SAMPLETYPE *samples, uint nSamples) { memcpy(ptrEnd(nSamples), samples, sizeof(SAMPLETYPE) * nSamples * channels); samplesInBuffer += nSamples; } // Increases the number of samples in the buffer without copying any actual // samples. // // This function is used to update the number of samples in the sample buffer // when accessing the buffer directly with 'ptrEnd' function. Please be // careful though! void FIFOSampleBuffer::putSamples(uint nSamples) { uint req; req = samplesInBuffer + nSamples; ensureCapacity(req); samplesInBuffer += nSamples; } // Returns a pointer to the end of the used part of the sample buffer (i.e. // where the new samples are to be inserted). This function may be used for // inserting new samples into the sample buffer directly. Please be careful! // // Parameter 'slackCapacity' tells the function how much free capacity (in // terms of samples) there _at least_ should be, in order to the caller to // succesfully insert all the required samples to the buffer. When necessary, // the function grows the buffer size to comply with this requirement. // // When using this function as means for inserting new samples, also remember // to increase the sample count afterwards, by calling the // 'putSamples(numSamples)' function. SAMPLETYPE *FIFOSampleBuffer::ptrEnd(uint slackCapacity) { ensureCapacity(samplesInBuffer + slackCapacity); return buffer + samplesInBuffer * channels; } // Returns a pointer to the beginning of the currently non-outputted samples. // This function is provided for accessing the output samples directly. // Please be careful! // // When using this function to output samples, also remember to 'remove' the // outputted samples from the buffer by calling the // 'receiveSamples(numSamples)' function SAMPLETYPE *FIFOSampleBuffer::ptrBegin() { assert(buffer); return buffer + bufferPos * channels; } // Ensures that the buffer has enought capacity, i.e. space for _at least_ // 'capacityRequirement' number of samples. The buffer is grown in steps of // 4 kilobytes to eliminate the need for frequently growing up the buffer, // as well as to round the buffer size up to the virtual memory page size. void FIFOSampleBuffer::ensureCapacity(uint capacityRequirement) { SAMPLETYPE *tempUnaligned, *temp; if (capacityRequirement > getCapacity()) { // enlarge the buffer in 4kbyte steps (round up to next 4k boundary) sizeInBytes = (capacityRequirement * channels * sizeof(SAMPLETYPE) + 4095) & (uint)-4096; assert(sizeInBytes % 2 == 0); tempUnaligned = new SAMPLETYPE[sizeInBytes / sizeof(SAMPLETYPE) + 16 / sizeof(SAMPLETYPE)]; if (tempUnaligned == NULL) { throw std::runtime_error("Couldn't allocate memory!\n"); } // Align the buffer to begin at 16byte cache line boundary for optimal performance temp = (SAMPLETYPE *)(((ulong)tempUnaligned + 15) & (ulong)-16); memcpy(temp, ptrBegin(), samplesInBuffer * channels * sizeof(SAMPLETYPE)); delete[] bufferUnaligned; buffer = temp; bufferUnaligned = tempUnaligned; bufferPos = 0; } else { // simply rewind the buffer (if necessary) rewind(); } } // Returns the current buffer capacity in terms of samples uint FIFOSampleBuffer::getCapacity() const { return sizeInBytes / (channels * sizeof(SAMPLETYPE)); } // Returns the number of samples currently in the buffer uint FIFOSampleBuffer::numSamples() const { return samplesInBuffer; } // Output samples from beginning of the sample buffer. Copies demanded number // of samples to output and removes them from the sample buffer. If there // are less than 'numsample' samples in the buffer, returns all available. // // Returns number of samples copied. uint FIFOSampleBuffer::receiveSamples(SAMPLETYPE *output, uint maxSamples) { uint num; num = (maxSamples > samplesInBuffer) ? samplesInBuffer : maxSamples; memcpy(output, ptrBegin(), channels * sizeof(SAMPLETYPE) * num); return receiveSamples(num); } // Removes samples from the beginning of the sample buffer without copying them // anywhere. Used to reduce the number of samples in the buffer, when accessing // the sample buffer with the 'ptrBegin' function. uint FIFOSampleBuffer::receiveSamples(uint maxSamples) { if (maxSamples >= samplesInBuffer) { uint temp; temp = samplesInBuffer; samplesInBuffer = 0; return temp; } samplesInBuffer -= maxSamples; bufferPos += maxSamples; return maxSamples; } // Returns nonzero if the sample buffer is empty int FIFOSampleBuffer::isEmpty() const { return (samplesInBuffer == 0) ? 1 : 0; } // Clears the sample buffer void FIFOSampleBuffer::clear() { samplesInBuffer = 0; bufferPos = 0; } <commit_msg>Check for empty buffer<commit_after>//////////////////////////////////////////////////////////////////////////////// /// /// A buffer class for temporarily storaging sound samples, operates as a /// first-in-first-out pipe. /// /// Samples are added to the end of the sample buffer with the 'putSamples' /// function, and are received from the beginning of the buffer by calling /// the 'receiveSamples' function. The class automatically removes the /// outputted samples from the buffer, as well as grows the buffer size /// whenever necessary. /// /// Author : Copyright (c) Olli Parviainen /// Author e-mail : oparviai 'at' iki.fi /// SoundTouch WWW: http://www.surina.net/soundtouch /// //////////////////////////////////////////////////////////////////////////////// // // Last changed : $Date$ // File revision : $Revision: 4 $ // // $Id$ // //////////////////////////////////////////////////////////////////////////////// // // License : // // SoundTouch audio processing library // Copyright (c) Olli Parviainen // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // //////////////////////////////////////////////////////////////////////////////// #include <stdlib.h> #include <memory.h> #include <string.h> #include <assert.h> #include <stdexcept> #include "FIFOSampleBuffer.h" using namespace soundtouch; // Constructor FIFOSampleBuffer::FIFOSampleBuffer(int numChannels) { assert(numChannels > 0); sizeInBytes = 0; // reasonable initial value buffer = NULL; bufferUnaligned = NULL; samplesInBuffer = 0; bufferPos = 0; channels = (uint)numChannels; ensureCapacity(32); // allocate initial capacity } // destructor FIFOSampleBuffer::~FIFOSampleBuffer() { delete[] bufferUnaligned; bufferUnaligned = NULL; buffer = NULL; } // Sets number of channels, 1 = mono, 2 = stereo void FIFOSampleBuffer::setChannels(int numChannels) { uint usedBytes; assert(numChannels > 0); usedBytes = channels * samplesInBuffer; channels = (uint)numChannels; samplesInBuffer = usedBytes / channels; } // if output location pointer 'bufferPos' isn't zero, 'rewinds' the buffer and // zeroes this pointer by copying samples from the 'bufferPos' pointer // location on to the beginning of the buffer. void FIFOSampleBuffer::rewind() { if (buffer && bufferPos) { memmove(buffer, ptrBegin(), sizeof(SAMPLETYPE) * channels * samplesInBuffer); bufferPos = 0; } } // Adds 'numSamples' pcs of samples from the 'samples' memory position to // the sample buffer. void FIFOSampleBuffer::putSamples(const SAMPLETYPE *samples, uint nSamples) { memcpy(ptrEnd(nSamples), samples, sizeof(SAMPLETYPE) * nSamples * channels); samplesInBuffer += nSamples; } // Increases the number of samples in the buffer without copying any actual // samples. // // This function is used to update the number of samples in the sample buffer // when accessing the buffer directly with 'ptrEnd' function. Please be // careful though! void FIFOSampleBuffer::putSamples(uint nSamples) { uint req; req = samplesInBuffer + nSamples; ensureCapacity(req); samplesInBuffer += nSamples; } // Returns a pointer to the end of the used part of the sample buffer (i.e. // where the new samples are to be inserted). This function may be used for // inserting new samples into the sample buffer directly. Please be careful! // // Parameter 'slackCapacity' tells the function how much free capacity (in // terms of samples) there _at least_ should be, in order to the caller to // succesfully insert all the required samples to the buffer. When necessary, // the function grows the buffer size to comply with this requirement. // // When using this function as means for inserting new samples, also remember // to increase the sample count afterwards, by calling the // 'putSamples(numSamples)' function. SAMPLETYPE *FIFOSampleBuffer::ptrEnd(uint slackCapacity) { ensureCapacity(samplesInBuffer + slackCapacity); return buffer + samplesInBuffer * channels; } // Returns a pointer to the beginning of the currently non-outputted samples. // This function is provided for accessing the output samples directly. // Please be careful! // // When using this function to output samples, also remember to 'remove' the // outputted samples from the buffer by calling the // 'receiveSamples(numSamples)' function SAMPLETYPE *FIFOSampleBuffer::ptrBegin() { assert(buffer); return buffer + bufferPos * channels; } // Ensures that the buffer has enought capacity, i.e. space for _at least_ // 'capacityRequirement' number of samples. The buffer is grown in steps of // 4 kilobytes to eliminate the need for frequently growing up the buffer, // as well as to round the buffer size up to the virtual memory page size. void FIFOSampleBuffer::ensureCapacity(uint capacityRequirement) { SAMPLETYPE *tempUnaligned, *temp; if (capacityRequirement > getCapacity()) { // enlarge the buffer in 4kbyte steps (round up to next 4k boundary) sizeInBytes = (capacityRequirement * channels * sizeof(SAMPLETYPE) + 4095) & (uint)-4096; assert(sizeInBytes % 2 == 0); tempUnaligned = new SAMPLETYPE[sizeInBytes / sizeof(SAMPLETYPE) + 16 / sizeof(SAMPLETYPE)]; if (tempUnaligned == NULL) { throw std::runtime_error("Couldn't allocate memory!\n"); } // Align the buffer to begin at 16byte cache line boundary for optimal performance temp = (SAMPLETYPE *)(((ulong)tempUnaligned + 15) & (ulong)-16); if (samplesInBuffer) { memcpy(temp, ptrBegin(), samplesInBuffer * channels * sizeof(SAMPLETYPE)); } delete[] bufferUnaligned; buffer = temp; bufferUnaligned = tempUnaligned; bufferPos = 0; } else { // simply rewind the buffer (if necessary) rewind(); } } // Returns the current buffer capacity in terms of samples uint FIFOSampleBuffer::getCapacity() const { return sizeInBytes / (channels * sizeof(SAMPLETYPE)); } // Returns the number of samples currently in the buffer uint FIFOSampleBuffer::numSamples() const { return samplesInBuffer; } // Output samples from beginning of the sample buffer. Copies demanded number // of samples to output and removes them from the sample buffer. If there // are less than 'numsample' samples in the buffer, returns all available. // // Returns number of samples copied. uint FIFOSampleBuffer::receiveSamples(SAMPLETYPE *output, uint maxSamples) { uint num; num = (maxSamples > samplesInBuffer) ? samplesInBuffer : maxSamples; memcpy(output, ptrBegin(), channels * sizeof(SAMPLETYPE) * num); return receiveSamples(num); } // Removes samples from the beginning of the sample buffer without copying them // anywhere. Used to reduce the number of samples in the buffer, when accessing // the sample buffer with the 'ptrBegin' function. uint FIFOSampleBuffer::receiveSamples(uint maxSamples) { if (maxSamples >= samplesInBuffer) { uint temp; temp = samplesInBuffer; samplesInBuffer = 0; return temp; } samplesInBuffer -= maxSamples; bufferPos += maxSamples; return maxSamples; } // Returns nonzero if the sample buffer is empty int FIFOSampleBuffer::isEmpty() const { return (samplesInBuffer == 0) ? 1 : 0; } // Clears the sample buffer void FIFOSampleBuffer::clear() { samplesInBuffer = 0; bufferPos = 0; } <|endoftext|>
<commit_before>/****************************************************************** * * Round for C++ * * Copyright (C) Satoshi Konno 2014 * * This is licensed under BSD-style license, see file COPYING. * ******************************************************************/ #include <boost/filesystem.hpp> #include <boost/foreach.hpp> #include <round/Round.h> #include <round/core/LocalNode.h> #include <round/core/SystemMethod.h> //////////////////////////////////////////////// // Constructor //////////////////////////////////////////////// Round::LocalNode::LocalNode() { init(); } Round::LocalNode::~LocalNode() { } void Round::LocalNode::init() { setState(NodeStatus::STOP); } //////////////////////////////////////////////// // Configuration //////////////////////////////////////////////// bool Round::LocalNode::loadConfigFromString(const std::string &string, Error *error) { if (this->nodeConfig.loadFromString(string, error) == false) return false; return true; } bool Round::LocalNode::loadConfigFromFile(const std::string &filename, Error *error) { if (this->nodeConfig.loadFromFile(filename, error) == false) return false; return true; } bool Round::LocalNode::isConfigValid(Error *error) { return this->nodeConfig.isValid(error); } bool Round::LocalNode::getClusterName(std::string *name, Error *error) { return this->nodeConfig.getCluster(name, error); } //////////////////////////////////////////////// // Thread //////////////////////////////////////////////// bool Round::LocalNode::start(Error *error) { stop(error); bool areAllOperationSucess = true; setState(NodeStatus::ACTIVATING); nodeWorker.setObject(this); if (nodeWorker.start()) { if (!this->nodeGraph.addNode(this)) { areAllOperationSucess = false; } } else { areAllOperationSucess = false; } if (!areAllOperationSucess) { stop(error); return false; } setState(NodeStatus::ACTIVE); return true; } bool Round::LocalNode::stop(Error *error) { bool areAllOperationSucess = true; if (!nodeWorker.stop()) { areAllOperationSucess = false; return false; } NodeGraph *nodeGraph = getNodeGraph(); if (!nodeGraph->clear()) { areAllOperationSucess = false; } if (areAllOperationSucess == true) { setState(NodeStatus::STOP); } return areAllOperationSucess; } bool Round::LocalNode::restart(Error *error) { if (stop(error) == false) return false; return start(error); } //////////////////////////////////////////////// // Notification //////////////////////////////////////////////// bool Round::LocalNode::nodeAdded(Round::Node *notifyNode) { Error error; std::string notifyNodeCluster; if (!notifyNode->getClusterName(&notifyNodeCluster, &error)) return false; std::string thisNodeCluster; if (!getClusterName(&thisNodeCluster, &error)) return false; if (thisNodeCluster.compare(notifyNodeCluster) != 0) return false; if (this->nodeGraph.hasNode(notifyNode)) return true; if (!this->nodeGraph.addNode(notifyNode)) return true; if (equals(notifyNode)) return true; return true; } bool Round::LocalNode::nodeRemoved(Round::Node *notifyNode) { if (!this->nodeGraph.hasNode(notifyNode)) return true; if (equals(notifyNode)) { this->nodeGraph.removeNode(notifyNode); return true; } ssize_t notifyNodeIndex = this->nodeGraph.getNodeIndex(notifyNode); if (notifyNodeIndex < 0) return false; Node *failedNode = this->nodeGraph.getNode(notifyNodeIndex); if (!failedNode) return false; return true; } //////////////////////////////////////////////// // Message //////////////////////////////////////////////// bool Round::LocalNode::postMessage(NodeRequest *nodeReq, NodeResponse *nodeRes, Error *error) { // Set id and ts parameter clock_t localTs = getLocalClock(); nodeReq->setId(localTs); nodeReq->setTimestamp(localTs); // Post RPC message return execMessage(nodeReq, nodeRes, error); } bool Round::LocalNode::pushMessage(const NodeRequest *nodeReq) { return this->nodeMsgMgr.pushMessage(nodeReq); } bool Round::LocalNode::waitMessage(const NodeRequest **nodeReq) { *nodeReq = NULL; const Message *nodeMsg = NULL; if (!this->nodeMsgMgr.waitMessage(&nodeMsg)) return false; *nodeReq = dynamic_cast<const NodeRequest *>(nodeMsg); return (*nodeReq) ? true : false; } //////////////////////////////////////////////// // Execution //////////////////////////////////////////////// bool Round::LocalNode::hasUserMethod(const std::string &method) { return this->scriptMgr.hasScript(method); } bool Round::LocalNode::setError(int rpcErrorCode, Error *err) { if (!err) return false; RPC::JSON::ErrorCodeToError(rpcErrorCode, err); return true; } bool Round::LocalNode::execMessage(const NodeRequest *nodeReq, NodeResponse *nodeRes, Error *err) { if (!nodeReq || !nodeRes || !err) return false; // Check hash code if (nodeReq->hasHash()) { std::string hashCode; if (getHashCode(&hashCode)) { if (hashCode.length() != HashObject::GetHashCodeLength()) { setError(RPC::JSON::ErrorCodeBadHashCode, err); return false; } NodeGraph *nodeGraph = getNodeGraph(); if (!nodeGraph->isHandleNode(this, hashCode)) { setError(RPC::JSON::ErrorCodeMovedPermanently, err); return false; } } } // Update local clock clock_t remoteTs; if (nodeRes->getTimestamp(&remoteTs)) { setRemoteClock(remoteTs); } else { incrementLocalClock(); } // Set id and ts parameter size_t msgId; if (nodeReq->getId(&msgId)) { nodeRes->setId(msgId); } nodeRes->setTimestamp(getLocalClock()); // Exec Message std::string name; if (!nodeReq->getMethod(&name) || (name.length() <= 0)) { setError(RPC::JSON::ErrorCodeMethodNotFound, err); return false; } if (isSetMethod(name)) { if (!setMethod(nodeReq, nodeRes, err)) { setError(RPC::JSON::ErrorCodeInvalidParams, err); return false; } return true; } if (hasUserMethod(name)) { std::string params; nodeReq->getParams(&params); std::string result; bool isSuccess = this->scriptMgr.run(name, params, &result, err); if (isSuccess) { nodeRes->setResult(result); } else { nodeRes->setError(err); } return isSuccess; } if (isSystemMethod(name)) { return execSystemMethod(nodeReq, nodeRes, err); } setError(RPC::JSON::ErrorCodeMethodNotFound, err); return false; } //////////////////////////////////////////////// // System Static Method //////////////////////////////////////////////// bool Round::LocalNode::isSetMethod(const std::string &method) { return (SystemMethodRequest::SET_METHOD.compare(method) == 0) ? true : false; } bool Round::LocalNode::setMethod(const NodeRequest *nodeReq, NodeResponse *nodeRes, Error *err) { std::string params; nodeReq->getParams(&params); JSONParser jsonParser; if (!jsonParser.parse(params, err)) { RPC::JSON::ErrorCodeToError(RPC::JSON::ErrorCodeInvalidParams, err); return false; } JSONObject *jsonObj = jsonParser.getRootObject(); if (!jsonObj->isDictionary()) { RPC::JSON::ErrorCodeToError(RPC::JSON::ErrorCodeInvalidParams, err); return false; } JSONDictionary *jsonDict = dynamic_cast<JSONDictionary *>(jsonObj); if (!jsonDict) { RPC::JSON::ErrorCodeToError(RPC::JSON::ErrorCodeInvalidParams, err); return false; } std::string scriptMethod; if (!jsonDict->get(SystemMethodRequest::NAME, &scriptMethod) || (scriptMethod.length() <= 0)) { RPC::JSON::ErrorCodeToError(RPC::JSON::ErrorCodeInvalidParams, err); return false; } // Couldn't override '_set_method' if (isSetMethod(scriptMethod)) { RPC::JSON::ErrorCodeToError(RPC::JSON::ErrorCodeInvalidParams, err); return false; } std::string scriptLang; if (!jsonDict->get(SystemMethodRequest::LANGUAGE, &scriptLang) || (scriptLang.length() <= 0)) { RPC::JSON::ErrorCodeToError(RPC::JSON::ErrorCodeInvalidParams, err); return false; } // This method is removed if the code parameter is null. std::string scriptCode; jsonDict->get(SystemMethodRequest::CODE, &scriptCode); // Encode int encodeType = Script::ENCODING_NONE; std::string encodeTypeStr; if (jsonDict->get(SystemMethodRequest::ENCODE, &encodeTypeStr)) { if (encodeTypeStr.compare(SystemMethodRequest::ENCODE_BASE64)) { encodeType = Script::ENCODING_BASE64; } } return this->scriptMgr.setScript(scriptMethod, scriptLang, scriptCode, encodeType, err); } //////////////////////////////////////////////// // System Dynamic Method //////////////////////////////////////////////// bool Round::LocalNode::isSystemMethod(const std::string &method) { return (method.find(SystemMethodRequest::PREFIX) == 0) ? true : false; } bool Round::LocalNode::execSystemMethod(const NodeRequest *nodeReq, NodeResponse *nodeRes, Error *error) { static std::map<std::string, int> systemMethods; enum { SystemGetNodeInfo, SystemGetClusterInfo, SystemGetNetworkInfo, }; if (systemMethods.size() <= 0) { systemMethods[SystemMethodRequest::GET_NODE_INFO] = SystemGetNodeInfo; systemMethods[SystemMethodRequest::GET_CLUSTER_INFO] = SystemGetClusterInfo; systemMethods[SystemMethodRequest::GET_NETWORK_INFO] = SystemGetNetworkInfo; } std::string reqMethod; nodeReq->getMethod(&reqMethod); if (systemMethods.find(reqMethod) == systemMethods.end()) { RPC::JSON::ErrorCodeToError(RPC::JSON::ErrorCodeMethodNotFound, error); return false; } int systemMethodType = systemMethods[reqMethod]; switch (systemMethodType) { case SystemGetNodeInfo: return _get_node_info(nodeReq, nodeRes, error); case SystemGetClusterInfo: return _get_cluster_info(nodeReq, nodeRes, error); case SystemGetNetworkInfo: return _get_network_info(nodeReq, nodeRes, error); } RPC::JSON::ErrorCodeToError(RPC::JSON::ErrorCodeMethodNotFound, error); return false; } bool Round::LocalNode::_get_node_info(const NodeRequest *nodeReq, NodeResponse *nodeRes, Error *error) { SystemGetNodeInfoResponse sysRes(nodeRes); return sysRes.setNode(this); } bool Round::LocalNode::_get_cluster_info(const NodeRequest *nodeReq, NodeResponse *nodeRes, Error *error) { SystemGetClusterInfoResponse sysRes(nodeRes); return sysRes.setCluster(this); } bool Round::LocalNode::_get_network_info(const NodeRequest *nodeReq, NodeResponse *nodeRes, Error *error) { SystemGetNetworkInfoResponse sysRes(nodeRes); return sysRes.setClusters(this); } <commit_msg>* Fixed LocalNode::execMessage(). #16<commit_after>/****************************************************************** * * Round for C++ * * Copyright (C) Satoshi Konno 2014 * * This is licensed under BSD-style license, see file COPYING. * ******************************************************************/ #include <boost/filesystem.hpp> #include <boost/foreach.hpp> #include <round/Round.h> #include <round/core/LocalNode.h> #include <round/core/SystemMethod.h> //////////////////////////////////////////////// // Constructor //////////////////////////////////////////////// Round::LocalNode::LocalNode() { init(); } Round::LocalNode::~LocalNode() { } void Round::LocalNode::init() { setState(NodeStatus::STOP); } //////////////////////////////////////////////// // Configuration //////////////////////////////////////////////// bool Round::LocalNode::loadConfigFromString(const std::string &string, Error *error) { if (this->nodeConfig.loadFromString(string, error) == false) return false; return true; } bool Round::LocalNode::loadConfigFromFile(const std::string &filename, Error *error) { if (this->nodeConfig.loadFromFile(filename, error) == false) return false; return true; } bool Round::LocalNode::isConfigValid(Error *error) { return this->nodeConfig.isValid(error); } bool Round::LocalNode::getClusterName(std::string *name, Error *error) { return this->nodeConfig.getCluster(name, error); } //////////////////////////////////////////////// // Thread //////////////////////////////////////////////// bool Round::LocalNode::start(Error *error) { stop(error); bool areAllOperationSucess = true; setState(NodeStatus::ACTIVATING); nodeWorker.setObject(this); if (nodeWorker.start()) { if (!this->nodeGraph.addNode(this)) { areAllOperationSucess = false; } } else { areAllOperationSucess = false; } if (!areAllOperationSucess) { stop(error); return false; } setState(NodeStatus::ACTIVE); return true; } bool Round::LocalNode::stop(Error *error) { bool areAllOperationSucess = true; if (!nodeWorker.stop()) { areAllOperationSucess = false; return false; } NodeGraph *nodeGraph = getNodeGraph(); if (!nodeGraph->clear()) { areAllOperationSucess = false; } if (areAllOperationSucess == true) { setState(NodeStatus::STOP); } return areAllOperationSucess; } bool Round::LocalNode::restart(Error *error) { if (stop(error) == false) return false; return start(error); } //////////////////////////////////////////////// // Notification //////////////////////////////////////////////// bool Round::LocalNode::nodeAdded(Round::Node *notifyNode) { Error error; std::string notifyNodeCluster; if (!notifyNode->getClusterName(&notifyNodeCluster, &error)) return false; std::string thisNodeCluster; if (!getClusterName(&thisNodeCluster, &error)) return false; if (thisNodeCluster.compare(notifyNodeCluster) != 0) return false; if (this->nodeGraph.hasNode(notifyNode)) return true; if (!this->nodeGraph.addNode(notifyNode)) return true; if (equals(notifyNode)) return true; return true; } bool Round::LocalNode::nodeRemoved(Round::Node *notifyNode) { if (!this->nodeGraph.hasNode(notifyNode)) return true; if (equals(notifyNode)) { this->nodeGraph.removeNode(notifyNode); return true; } ssize_t notifyNodeIndex = this->nodeGraph.getNodeIndex(notifyNode); if (notifyNodeIndex < 0) return false; Node *failedNode = this->nodeGraph.getNode(notifyNodeIndex); if (!failedNode) return false; return true; } //////////////////////////////////////////////// // Message //////////////////////////////////////////////// bool Round::LocalNode::postMessage(NodeRequest *nodeReq, NodeResponse *nodeRes, Error *error) { // Set id and ts parameter clock_t localTs = getLocalClock(); nodeReq->setId(localTs); nodeReq->setTimestamp(localTs); // Post RPC message return execMessage(nodeReq, nodeRes, error); } bool Round::LocalNode::pushMessage(const NodeRequest *nodeReq) { return this->nodeMsgMgr.pushMessage(nodeReq); } bool Round::LocalNode::waitMessage(const NodeRequest **nodeReq) { *nodeReq = NULL; const Message *nodeMsg = NULL; if (!this->nodeMsgMgr.waitMessage(&nodeMsg)) return false; *nodeReq = dynamic_cast<const NodeRequest *>(nodeMsg); return (*nodeReq) ? true : false; } //////////////////////////////////////////////// // Execution //////////////////////////////////////////////// bool Round::LocalNode::hasUserMethod(const std::string &method) { return this->scriptMgr.hasScript(method); } bool Round::LocalNode::setError(int rpcErrorCode, Error *err) { if (!err) return false; RPC::JSON::ErrorCodeToError(rpcErrorCode, err); return true; } bool Round::LocalNode::execMessage(const NodeRequest *nodeReq, NodeResponse *nodeRes, Error *err) { if (!nodeReq || !nodeRes || !err) return false; // Check hash code if (nodeReq->hasHash()) { std::string hashCode; if (nodeReq->getHash(&hashCode)) { if (hashCode.length() != HashObject::GetHashCodeLength()) { setError(RPC::JSON::ErrorCodeBadHashCode, err); return false; } NodeGraph *nodeGraph = getNodeGraph(); if (!nodeGraph->isHandleNode(this, hashCode)) { setError(RPC::JSON::ErrorCodeMovedPermanently, err); return false; } } } // Update local clock clock_t remoteTs; if (nodeRes->getTimestamp(&remoteTs)) { setRemoteClock(remoteTs); } else { incrementLocalClock(); } // Set id and ts parameter size_t msgId; if (nodeReq->getId(&msgId)) { nodeRes->setId(msgId); } nodeRes->setTimestamp(getLocalClock()); // Exec Message std::string name; if (!nodeReq->getMethod(&name) || (name.length() <= 0)) { setError(RPC::JSON::ErrorCodeMethodNotFound, err); return false; } if (isSetMethod(name)) { if (!setMethod(nodeReq, nodeRes, err)) { setError(RPC::JSON::ErrorCodeInvalidParams, err); return false; } return true; } if (hasUserMethod(name)) { std::string params; nodeReq->getParams(&params); std::string result; bool isSuccess = this->scriptMgr.run(name, params, &result, err); if (isSuccess) { nodeRes->setResult(result); } else { nodeRes->setError(err); } return isSuccess; } if (isSystemMethod(name)) { return execSystemMethod(nodeReq, nodeRes, err); } setError(RPC::JSON::ErrorCodeMethodNotFound, err); return false; } //////////////////////////////////////////////// // System Static Method //////////////////////////////////////////////// bool Round::LocalNode::isSetMethod(const std::string &method) { return (SystemMethodRequest::SET_METHOD.compare(method) == 0) ? true : false; } bool Round::LocalNode::setMethod(const NodeRequest *nodeReq, NodeResponse *nodeRes, Error *err) { std::string params; nodeReq->getParams(&params); JSONParser jsonParser; if (!jsonParser.parse(params, err)) { RPC::JSON::ErrorCodeToError(RPC::JSON::ErrorCodeInvalidParams, err); return false; } JSONObject *jsonObj = jsonParser.getRootObject(); if (!jsonObj->isDictionary()) { RPC::JSON::ErrorCodeToError(RPC::JSON::ErrorCodeInvalidParams, err); return false; } JSONDictionary *jsonDict = dynamic_cast<JSONDictionary *>(jsonObj); if (!jsonDict) { RPC::JSON::ErrorCodeToError(RPC::JSON::ErrorCodeInvalidParams, err); return false; } std::string scriptMethod; if (!jsonDict->get(SystemMethodRequest::NAME, &scriptMethod) || (scriptMethod.length() <= 0)) { RPC::JSON::ErrorCodeToError(RPC::JSON::ErrorCodeInvalidParams, err); return false; } // Couldn't override '_set_method' if (isSetMethod(scriptMethod)) { RPC::JSON::ErrorCodeToError(RPC::JSON::ErrorCodeInvalidParams, err); return false; } std::string scriptLang; if (!jsonDict->get(SystemMethodRequest::LANGUAGE, &scriptLang) || (scriptLang.length() <= 0)) { RPC::JSON::ErrorCodeToError(RPC::JSON::ErrorCodeInvalidParams, err); return false; } // This method is removed if the code parameter is null. std::string scriptCode; jsonDict->get(SystemMethodRequest::CODE, &scriptCode); // Encode int encodeType = Script::ENCODING_NONE; std::string encodeTypeStr; if (jsonDict->get(SystemMethodRequest::ENCODE, &encodeTypeStr)) { if (encodeTypeStr.compare(SystemMethodRequest::ENCODE_BASE64)) { encodeType = Script::ENCODING_BASE64; } } return this->scriptMgr.setScript(scriptMethod, scriptLang, scriptCode, encodeType, err); } //////////////////////////////////////////////// // System Dynamic Method //////////////////////////////////////////////// bool Round::LocalNode::isSystemMethod(const std::string &method) { return (method.find(SystemMethodRequest::PREFIX) == 0) ? true : false; } bool Round::LocalNode::execSystemMethod(const NodeRequest *nodeReq, NodeResponse *nodeRes, Error *error) { static std::map<std::string, int> systemMethods; enum { SystemGetNodeInfo, SystemGetClusterInfo, SystemGetNetworkInfo, }; if (systemMethods.size() <= 0) { systemMethods[SystemMethodRequest::GET_NODE_INFO] = SystemGetNodeInfo; systemMethods[SystemMethodRequest::GET_CLUSTER_INFO] = SystemGetClusterInfo; systemMethods[SystemMethodRequest::GET_NETWORK_INFO] = SystemGetNetworkInfo; } std::string reqMethod; nodeReq->getMethod(&reqMethod); if (systemMethods.find(reqMethod) == systemMethods.end()) { RPC::JSON::ErrorCodeToError(RPC::JSON::ErrorCodeMethodNotFound, error); return false; } int systemMethodType = systemMethods[reqMethod]; switch (systemMethodType) { case SystemGetNodeInfo: return _get_node_info(nodeReq, nodeRes, error); case SystemGetClusterInfo: return _get_cluster_info(nodeReq, nodeRes, error); case SystemGetNetworkInfo: return _get_network_info(nodeReq, nodeRes, error); } RPC::JSON::ErrorCodeToError(RPC::JSON::ErrorCodeMethodNotFound, error); return false; } bool Round::LocalNode::_get_node_info(const NodeRequest *nodeReq, NodeResponse *nodeRes, Error *error) { SystemGetNodeInfoResponse sysRes(nodeRes); return sysRes.setNode(this); } bool Round::LocalNode::_get_cluster_info(const NodeRequest *nodeReq, NodeResponse *nodeRes, Error *error) { SystemGetClusterInfoResponse sysRes(nodeRes); return sysRes.setCluster(this); } bool Round::LocalNode::_get_network_info(const NodeRequest *nodeReq, NodeResponse *nodeRes, Error *error) { SystemGetNetworkInfoResponse sysRes(nodeRes); return sysRes.setClusters(this); } <|endoftext|>
<commit_before>AliEmcalTRDTracking* AddTaskTRDTracking(const char *suffix = "") { return AliEmcalTRDTracking::AddTaskTRDTracking(suffix); } <commit_msg>Fixing task name in add macro<commit_after>AliEmcalTRDTrackingTask* AddTaskTRDTracking(const char *suffix = "") { return AliEmcalTRDTrackingTask::AddTaskTRDTracking(suffix); } <|endoftext|>
<commit_before>#include "image_png.h" #include "ohno.h" #include "png.h" #include "util.h" #include <cassert> #include <csetjmp> #include <functional> #include <iostream> namespace { const int PNG_SIG_SIZE = 8; void readPngStream(png_structp s, png_bytep data, png_size_t length) { if(!s) return; std::istream *input = static_cast<std::istream*>(png_get_io_ptr(s)); input->read(reinterpret_cast<char*>(data), length); if(!input->good()) { std::cout << "readPngStream error" << std::endl; png_error(s, "Read Error"); } } void writePngStream(png_structp s, png_bytep data, png_size_t length) { if(!s) return; std::ostream *output = static_cast<std::ostream*>(png_get_io_ptr(s)); output->write(reinterpret_cast<char*>(data), length); if(!output->good()) { std::cout << "writePngStream error" << std::endl; png_error(s, "Write Error"); } } void flushPngStream(png_structp s) { if(!s) return; std::ostream *output = static_cast<std::ostream*>(png_get_io_ptr(s)); output->flush(); if(!output->good()) { std::cout << "flushPngStream error" << std::endl; png_error(s, "Write Error"); } } // libpng has the design flaw of forcing us to care about endianness. It // should supply data in native endianness, rather than forcing us to // explicitly choose between big- or little-. Our hack to check if PNG default // endianness matches native endianness is to create an int in PNG endianness // and then compare it to a native int. If if doesn't match, then we need to // call png_set_swap. Thus we avoid having to know what native endianness is. bool shouldSwapEndian() { int32_t one; png_save_int_32(reinterpret_cast<png_bytep>(&one), 1); return one == 1; } class PngReader { public: PngReader( png_voidp error_ptr, png_error_ptr error_fn, png_error_ptr warn_fn ) { s = png_create_read_struct(PNG_LIBPNG_VER_STRING, error_ptr, error_fn, warn_fn); if(!s) throw OHNO("png_create_read_struct failed"); i = png_create_info_struct(s); if(!i) { png_destroy_read_struct(&s, nullptr, nullptr); throw OHNO("png_create_info_struct failed"); } } ~PngReader() { png_destroy_read_struct(&s, &i, nullptr); } png_structp s; png_infop i; }; class PngWriter { public: PngWriter( png_voidp error_ptr, png_error_ptr error_fn, png_error_ptr warn_fn ) { s = png_create_write_struct(PNG_LIBPNG_VER_STRING, error_ptr, error_fn, warn_fn); if(!s) throw OHNO("png_create_write_struct failed"); i = png_create_info_struct(s); if(!i) { png_destroy_write_struct(&s, nullptr); throw OHNO("png_create_info_struct failed"); } } ~PngWriter() { png_destroy_write_struct(&s, &i); } png_structp s; png_infop i; }; } Image readPng(std::istream &input) { char signature[PNG_SIG_SIZE]; input.read(signature, PNG_SIG_SIZE); if(!input.good()) throw OHNO("couldn't read PNG signature"); if(png_sig_cmp(reinterpret_cast<png_const_bytep>(signature), 0, PNG_SIG_SIZE)) throw OHNO("PNG signature doesn't match"); PngReader reader(nullptr, nullptr, nullptr); if(setjmp(png_jmpbuf(reader.s))) throw OHNO("got PNG long jump"); png_set_read_fn(reader.s, &input, readPngStream); png_set_sig_bytes(reader.s, PNG_SIG_SIZE); // TODO gamma, alpha png_read_info(reader.s, reader.i); png_uint_32 width = png_get_image_width(reader.s, reader.i); png_uint_32 height = png_get_image_height(reader.s, reader.i); png_byte bit_depth = png_get_bit_depth(reader.s, reader.i); png_byte color_type = png_get_color_type(reader.s, reader.i); if(bit_depth < 8) { // Expand to 8 bits per channel png_set_packing(reader.s); png_set_expand(reader.s); } if(bit_depth == 16 && shouldSwapEndian()) { png_set_swap(reader.s); } if(color_type & PNG_COLOR_MASK_PALETTE) { png_set_palette_to_rgb(reader.s); } bool has_alpha = color_type & PNG_COLOR_MASK_ALPHA; if(png_get_valid(reader.s, reader.i, PNG_INFO_tRNS)) { png_set_tRNS_to_alpha(reader.s); has_alpha = true; } Pixel::Type type; if(has_alpha) { if(color_type & PNG_COLOR_MASK_COLOR) { type = (bit_depth <= 8) ? Pixel::RGBA8_T : Pixel::RGBA16_T; } else { type = (bit_depth <= 8) ? Pixel::VA8_T : Pixel::VA16_T; } } else { if(color_type & PNG_COLOR_MASK_COLOR) { type = (bit_depth <= 8) ? Pixel::RGB8_T : Pixel::RGB16_T; } else { type = (bit_depth <= 8) ? Pixel::V8_T : Pixel::V16_T; } } std::cout << "reading PNG width=" << width << " height=" << height << " bit_depth=" << (int) bit_depth << " type=" << Pixel::name(type) << std::endl; Image img(width, height, type); png_bytepp rows = new png_bytep[height]; for(int i = 0; i < (int)height; i++) { rows[i] = reinterpret_cast<png_bytep>(img.getRowPtr(i)); } png_read_image(reader.s, rows); delete[] rows; png_read_end(reader.s, nullptr); return img; } void writePng(std::ostream &output, Image &img) { PngWriter writer(nullptr, nullptr, nullptr); if(setjmp(png_jmpbuf(writer.s))) throw OHNO("got PNG long jump"); png_set_write_fn(writer.s, &output, writePngStream, flushPngStream); png_byte bit_depth; switch(img.type()) { case Pixel::V8_T: case Pixel::VA8_T: case Pixel::RGB8_T: case Pixel::RGBA8_T: bit_depth = 8; break; case Pixel::V16_T: case Pixel::VA16_T: case Pixel::RGB16_T: case Pixel::RGBA16_T: bit_depth = 16; break; case Pixel::RGBf_T: case Pixel::RGBE8_T: throw OHNO("PNG unsupported pixel type"); default: assert(0); return; } png_byte color_type; switch(img.type()) { case Pixel::V8_T: case Pixel::V16_T: color_type = PNG_COLOR_TYPE_GRAY; break; case Pixel::VA8_T: case Pixel::VA16_T: color_type = PNG_COLOR_TYPE_GRAY_ALPHA; break; case Pixel::RGB8_T: case Pixel::RGB16_T: color_type = PNG_COLOR_TYPE_RGB; break; case Pixel::RGBA8_T: case Pixel::RGBA16_T: color_type = PNG_COLOR_TYPE_RGB_ALPHA; break; default: assert(0); return; } int width = img.width(); int height = img.height(); Pixel::Type type = img.type(); std::cout << "writing PNG width=" << width << " height=" << height << " bit_depth=" << (int) bit_depth << " type=" << Pixel::name(type) << std::endl; png_set_IHDR( writer.s, writer.i, width, height, bit_depth, color_type, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT); int transform = PNG_TRANSFORM_IDENTITY; if(bit_depth == 16 && shouldSwapEndian()) transform = PNG_TRANSFORM_SWAP_ENDIAN; png_bytepp rows = new png_bytep[height]; for(int i = 0; i < (int)height; i++) { rows[i] = reinterpret_cast<png_bytep>(img.getRowPtr(i)); } png_set_rows(writer.s, writer.i, rows); png_write_png(writer.s, writer.i, transform, nullptr); delete[] rows; } <commit_msg>convert raw pointers to unique_ptr in image_png<commit_after>#include "image_png.h" #include "ohno.h" #include "png.h" #include "util.h" #include <cassert> #include <csetjmp> #include <functional> #include <iostream> #include <memory> namespace { const int PNG_SIG_SIZE = 8; void readPngStream(png_structp s, png_bytep data, png_size_t length) { if(!s) return; std::istream *input = static_cast<std::istream*>(png_get_io_ptr(s)); input->read(reinterpret_cast<char*>(data), length); if(!input->good()) { std::cout << "readPngStream error" << std::endl; png_error(s, "Read Error"); } } void writePngStream(png_structp s, png_bytep data, png_size_t length) { if(!s) return; std::ostream *output = static_cast<std::ostream*>(png_get_io_ptr(s)); output->write(reinterpret_cast<char*>(data), length); if(!output->good()) { std::cout << "writePngStream error" << std::endl; png_error(s, "Write Error"); } } void flushPngStream(png_structp s) { if(!s) return; std::ostream *output = static_cast<std::ostream*>(png_get_io_ptr(s)); output->flush(); if(!output->good()) { std::cout << "flushPngStream error" << std::endl; png_error(s, "Write Error"); } } // libpng has the design flaw of forcing us to care about endianness. It // should supply data in native endianness, rather than forcing us to // explicitly choose between big- or little-. Our hack to check if PNG default // endianness matches native endianness is to create an int in PNG endianness // and then compare it to a native int. If if doesn't match, then we need to // call png_set_swap. Thus we avoid having to know what native endianness is. bool shouldSwapEndian() { int32_t one; png_save_int_32(reinterpret_cast<png_bytep>(&one), 1); return one == 1; } class PngReader { public: PngReader( png_voidp error_ptr, png_error_ptr error_fn, png_error_ptr warn_fn ) { s = png_create_read_struct(PNG_LIBPNG_VER_STRING, error_ptr, error_fn, warn_fn); if(!s) throw OHNO("png_create_read_struct failed"); i = png_create_info_struct(s); if(!i) { png_destroy_read_struct(&s, nullptr, nullptr); throw OHNO("png_create_info_struct failed"); } } ~PngReader() { png_destroy_read_struct(&s, &i, nullptr); } png_structp s; png_infop i; }; class PngWriter { public: PngWriter( png_voidp error_ptr, png_error_ptr error_fn, png_error_ptr warn_fn ) { s = png_create_write_struct(PNG_LIBPNG_VER_STRING, error_ptr, error_fn, warn_fn); if(!s) throw OHNO("png_create_write_struct failed"); i = png_create_info_struct(s); if(!i) { png_destroy_write_struct(&s, nullptr); throw OHNO("png_create_info_struct failed"); } } ~PngWriter() { png_destroy_write_struct(&s, &i); } png_structp s; png_infop i; }; } Image readPng(std::istream &input) { char signature[PNG_SIG_SIZE]; input.read(signature, PNG_SIG_SIZE); if(!input.good()) throw OHNO("couldn't read PNG signature"); if(png_sig_cmp(reinterpret_cast<png_const_bytep>(signature), 0, PNG_SIG_SIZE)) throw OHNO("PNG signature doesn't match"); PngReader reader(nullptr, nullptr, nullptr); if(setjmp(png_jmpbuf(reader.s))) throw OHNO("got PNG long jump"); png_set_read_fn(reader.s, &input, readPngStream); png_set_sig_bytes(reader.s, PNG_SIG_SIZE); // TODO gamma, alpha png_read_info(reader.s, reader.i); png_uint_32 width = png_get_image_width(reader.s, reader.i); png_uint_32 height = png_get_image_height(reader.s, reader.i); png_byte bit_depth = png_get_bit_depth(reader.s, reader.i); png_byte color_type = png_get_color_type(reader.s, reader.i); if(bit_depth < 8) { // Expand to 8 bits per channel png_set_packing(reader.s); png_set_expand(reader.s); } if(bit_depth == 16 && shouldSwapEndian()) { png_set_swap(reader.s); } if(color_type & PNG_COLOR_MASK_PALETTE) { png_set_palette_to_rgb(reader.s); } bool has_alpha = color_type & PNG_COLOR_MASK_ALPHA; if(png_get_valid(reader.s, reader.i, PNG_INFO_tRNS)) { png_set_tRNS_to_alpha(reader.s); has_alpha = true; } Pixel::Type type; if(has_alpha) { if(color_type & PNG_COLOR_MASK_COLOR) { type = (bit_depth <= 8) ? Pixel::RGBA8_T : Pixel::RGBA16_T; } else { type = (bit_depth <= 8) ? Pixel::VA8_T : Pixel::VA16_T; } } else { if(color_type & PNG_COLOR_MASK_COLOR) { type = (bit_depth <= 8) ? Pixel::RGB8_T : Pixel::RGB16_T; } else { type = (bit_depth <= 8) ? Pixel::V8_T : Pixel::V16_T; } } std::cout << "reading PNG width=" << width << " height=" << height << " bit_depth=" << (int) bit_depth << " type=" << Pixel::name(type) << std::endl; Image img(width, height, type); std::unique_ptr<png_bytep[]> rows(new png_bytep[height]); for(int i = 0; i < (int)height; i++) { rows[i] = reinterpret_cast<png_bytep>(img.getRowPtr(i)); } png_read_image(reader.s, rows.get()); rows.reset(); png_read_end(reader.s, nullptr); return img; } void writePng(std::ostream &output, Image &img) { PngWriter writer(nullptr, nullptr, nullptr); if(setjmp(png_jmpbuf(writer.s))) throw OHNO("got PNG long jump"); png_set_write_fn(writer.s, &output, writePngStream, flushPngStream); png_byte bit_depth; switch(img.type()) { case Pixel::V8_T: case Pixel::VA8_T: case Pixel::RGB8_T: case Pixel::RGBA8_T: bit_depth = 8; break; case Pixel::V16_T: case Pixel::VA16_T: case Pixel::RGB16_T: case Pixel::RGBA16_T: bit_depth = 16; break; case Pixel::RGBf_T: case Pixel::RGBE8_T: throw OHNO("PNG unsupported pixel type"); default: assert(0); return; } png_byte color_type; switch(img.type()) { case Pixel::V8_T: case Pixel::V16_T: color_type = PNG_COLOR_TYPE_GRAY; break; case Pixel::VA8_T: case Pixel::VA16_T: color_type = PNG_COLOR_TYPE_GRAY_ALPHA; break; case Pixel::RGB8_T: case Pixel::RGB16_T: color_type = PNG_COLOR_TYPE_RGB; break; case Pixel::RGBA8_T: case Pixel::RGBA16_T: color_type = PNG_COLOR_TYPE_RGB_ALPHA; break; default: assert(0); return; } int width = img.width(); int height = img.height(); Pixel::Type type = img.type(); std::cout << "writing PNG width=" << width << " height=" << height << " bit_depth=" << (int) bit_depth << " type=" << Pixel::name(type) << std::endl; png_set_IHDR( writer.s, writer.i, width, height, bit_depth, color_type, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT); int transform = PNG_TRANSFORM_IDENTITY; if(bit_depth == 16 && shouldSwapEndian()) transform = PNG_TRANSFORM_SWAP_ENDIAN; std::unique_ptr<png_bytep[]> rows(new png_bytep[height]); for(int i = 0; i < (int)height; i++) { rows[i] = reinterpret_cast<png_bytep>(img.getRowPtr(i)); } png_set_rows(writer.s, writer.i, rows.get()); png_write_png(writer.s, writer.i, transform, nullptr); rows.reset(); } <|endoftext|>