text
stringlengths
54
60.6k
<commit_before>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkDiffusionDICOMFileReader.h" #include "mitkDiffusionDICOMFileReaderHelper.h" #include "mitkDiffusionHeaderSiemensDICOMFileReader.h" #include "mitkDiffusionHeaderSiemensMosaicDICOMFileReader.h" #include "mitkDiffusionHeaderGEDICOMFileReader.h" #include "mitkDiffusionHeaderPhilipsDICOMFileReader.h" static void PerformHeaderAnalysis( mitk::DiffusionHeaderDICOMFileReader::DICOMHeaderListType headers ) { unsigned int images = headers.size(); unsigned int unweighted_images = 0; unsigned int weighted_images = 0; mitk::DiffusionHeaderDICOMFileReader::DICOMHeaderListType::const_iterator c_iter = headers.begin(); while( c_iter != headers.end() ) { const mitk::DiffusionImageDICOMHeaderInformation h = *c_iter; if( h.baseline ) unweighted_images++; if( h.b_value > 0 ) weighted_images++; ++c_iter; } MITK_INFO << " :: Analyzed volumes " << images << "\n" << " :: \t"<< unweighted_images << " b = 0" << "\n" << " :: \t"<< weighted_images << " b > 0"; } mitk::DiffusionDICOMFileReader::DiffusionDICOMFileReader() { m_IsMosaicData = false; } mitk::DiffusionDICOMFileReader::~DiffusionDICOMFileReader() { } bool mitk::DiffusionDICOMFileReader ::LoadImages() { // prepare data reading DiffusionDICOMFileReaderHelper helper; DiffusionDICOMFileReaderHelper::VolumeFileNamesContainer filenames; const size_t number_of_outputs = this->GetNumberOfOutputs(); for( size_t idx = 0; idx < number_of_outputs; idx++ ) { DICOMImageFrameList flist = this->GetOutput(idx).GetImageFrameList(); std::vector< std::string > FileNamesPerVolume; DICOMImageFrameList::const_iterator cIt = flist.begin(); while( cIt != flist.end() ) { FileNamesPerVolume.push_back( (*cIt)->Filename ); ++cIt; } filenames.push_back( FileNamesPerVolume ); } // TODO : only prototyping to test loading of diffusion images // we need some solution for the different types typedef mitk::DiffusionImage<short> DiffusionImageType; DiffusionImageType::Pointer output_image = DiffusionImageType::New(); DiffusionImageType::GradientDirectionContainerType::Pointer directions = DiffusionImageType::GradientDirectionContainerType::New(); double max_bvalue = 0; for( size_t idx = 0; idx < number_of_outputs; idx++ ) { DiffusionImageDICOMHeaderInformation header = this->m_RetrievedHeader.at(idx); if( max_bvalue < header.b_value ) max_bvalue = header.b_value; } // normalize the retrieved gradient directions according to the set b-value (maximal one) for( size_t idx = 0; idx < number_of_outputs; idx++ ) { DiffusionImageDICOMHeaderInformation header = this->m_RetrievedHeader.at(idx); DiffusionImageType::GradientDirectionType grad = header.g_vector; grad.normalize(); grad *= sqrt( header.b_value / max_bvalue ); directions->push_back( grad ); } // initialize the output image output_image->SetDirections( directions ); output_image->SetReferenceBValue( max_bvalue ); if( this->m_IsMosaicData ) { mitk::DiffusionHeaderSiemensMosaicDICOMFileReader::Pointer mosaic_reader = dynamic_cast< mitk::DiffusionHeaderSiemensMosaicDICOMFileReader* >( this->m_HeaderReader.GetPointer() ); // retrieve the remaining meta-information needed for mosaic reconstruction // it suffices to get it exemplatory from the first file in the file list mosaic_reader->RetrieveMosaicInformation( filenames.at(0).at(0) ); mitk::MosaicDescriptor mdesc = mosaic_reader->GetMosaicDescriptor(); output_image->SetVectorImage( helper.LoadMosaicToVector<short, 3>( filenames, mdesc ) ); } else { output_image->SetVectorImage( helper.LoadToVector<short, 3>( filenames ) ); } output_image->InitializeFromVectorImage(); //output_image->UpdateBValueMap(); // reduce the number of outputs to 1 as we will produce a single image this->SetNumberOfOutputs(1); // set the image to output DICOMImageBlockDescriptor& block = this->InternalGetOutput(0); block.SetMitkImage( (mitk::Image::Pointer) output_image ); return block.GetMitkImage().IsNotNull(); } void mitk::DiffusionDICOMFileReader ::AnalyzeInputFiles() { Superclass::AnalyzeInputFiles(); // collect output from superclass size_t number_of_outputs = this->GetNumberOfOutputs(); if(number_of_outputs == 0) { MITK_ERROR << "Failed to parse input, retrieved 0 outputs from SeriesGDCMReader "; } DICOMImageBlockDescriptor block_0 = this->GetOutput(0); MITK_INFO << "Retrieved " << number_of_outputs << "outputs."; // collect vendor ID from the first output, first image StringList inputFilename; DICOMImageFrameInfo::Pointer frame_0 = block_0.GetImageFrameList().at(0); inputFilename.push_back( frame_0->Filename ); gdcm::Scanner gdcmScanner; gdcm::Tag t_vendor(0x008, 0x0070); gdcm::Tag t_imagetype(0x008, 0x008); // add DICOM Tag for vendor gdcmScanner.AddTag( t_vendor ); // add DICOM Tag for image type gdcmScanner.AddTag( t_imagetype ); gdcmScanner.Scan( inputFilename ); // retrieve both vendor and image type std::string vendor = gdcmScanner.GetValue( frame_0->Filename.c_str(), t_vendor ); std::string image_type = gdcmScanner.GetValue( frame_0->Filename.c_str(), t_imagetype ); MITK_INFO << "Got vendor: " << vendor << " image type " << image_type; // parse vendor tag if( vendor.find("SIEMENS") != std::string::npos ) { if( image_type.find("MOSAIC") != std::string::npos ) { m_HeaderReader = mitk::DiffusionHeaderSiemensMosaicDICOMFileReader::New(); this->m_IsMosaicData = true; } else { m_HeaderReader = mitk::DiffusionHeaderSiemensDICOMFileReader::New(); } } else if( vendor.find("GE") != std::string::npos ) { m_HeaderReader = mitk::DiffusionHeaderGEDICOMFileReader::New(); } else if( vendor.find("Philips") != std::string::npos ) { m_HeaderReader = mitk::DiffusionHeaderPhilipsDICOMFileReader::New(); } else { // unknown vendor } if( m_HeaderReader.IsNull() ) { MITK_ERROR << "No header reader for given vendor. "; return; } bool canread = false; for( size_t idx = 0; idx < number_of_outputs; idx++ ) { DICOMImageFrameInfo::Pointer frame = this->GetOutput( idx ).GetImageFrameList().at(0); canread = m_HeaderReader->ReadDiffusionHeader(frame->Filename); } // collect the information m_RetrievedHeader = m_HeaderReader->GetHeaderInformation(); // TODO : Analyze outputs + header information, i.e. for the loading confidence MITK_INFO << "----- Diffusion DICOM Analysis Report ---- "; PerformHeaderAnalysis( m_RetrievedHeader ); MITK_INFO << "==========================================="; } bool mitk::DiffusionDICOMFileReader ::CanHandleFile(const std::string &filename) { //FIXME : return true; } <commit_msg>Directinos has to be set after reference value<commit_after>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkDiffusionDICOMFileReader.h" #include "mitkDiffusionDICOMFileReaderHelper.h" #include "mitkDiffusionHeaderSiemensDICOMFileReader.h" #include "mitkDiffusionHeaderSiemensMosaicDICOMFileReader.h" #include "mitkDiffusionHeaderGEDICOMFileReader.h" #include "mitkDiffusionHeaderPhilipsDICOMFileReader.h" static void PerformHeaderAnalysis( mitk::DiffusionHeaderDICOMFileReader::DICOMHeaderListType headers ) { unsigned int images = headers.size(); unsigned int unweighted_images = 0; unsigned int weighted_images = 0; mitk::DiffusionHeaderDICOMFileReader::DICOMHeaderListType::const_iterator c_iter = headers.begin(); while( c_iter != headers.end() ) { const mitk::DiffusionImageDICOMHeaderInformation h = *c_iter; if( h.baseline ) unweighted_images++; if( h.b_value > 0 ) weighted_images++; ++c_iter; } MITK_INFO << " :: Analyzed volumes " << images << "\n" << " :: \t"<< unweighted_images << " b = 0" << "\n" << " :: \t"<< weighted_images << " b > 0"; } mitk::DiffusionDICOMFileReader::DiffusionDICOMFileReader() { m_IsMosaicData = false; } mitk::DiffusionDICOMFileReader::~DiffusionDICOMFileReader() { } bool mitk::DiffusionDICOMFileReader ::LoadImages() { // prepare data reading DiffusionDICOMFileReaderHelper helper; DiffusionDICOMFileReaderHelper::VolumeFileNamesContainer filenames; const size_t number_of_outputs = this->GetNumberOfOutputs(); for( size_t idx = 0; idx < number_of_outputs; idx++ ) { DICOMImageFrameList flist = this->GetOutput(idx).GetImageFrameList(); std::vector< std::string > FileNamesPerVolume; DICOMImageFrameList::const_iterator cIt = flist.begin(); while( cIt != flist.end() ) { FileNamesPerVolume.push_back( (*cIt)->Filename ); ++cIt; } filenames.push_back( FileNamesPerVolume ); } // TODO : only prototyping to test loading of diffusion images // we need some solution for the different types typedef mitk::DiffusionImage<short> DiffusionImageType; DiffusionImageType::Pointer output_image = DiffusionImageType::New(); DiffusionImageType::GradientDirectionContainerType::Pointer directions = DiffusionImageType::GradientDirectionContainerType::New(); double max_bvalue = 0; for( size_t idx = 0; idx < number_of_outputs; idx++ ) { DiffusionImageDICOMHeaderInformation header = this->m_RetrievedHeader.at(idx); if( max_bvalue < header.b_value ) max_bvalue = header.b_value; } // normalize the retrieved gradient directions according to the set b-value (maximal one) for( size_t idx = 0; idx < number_of_outputs; idx++ ) { DiffusionImageDICOMHeaderInformation header = this->m_RetrievedHeader.at(idx); DiffusionImageType::GradientDirectionType grad = header.g_vector; grad.normalize(); grad *= sqrt( header.b_value / max_bvalue ); directions->push_back( grad ); } // initialize the output image output_image->SetReferenceBValue( max_bvalue ); output_image->SetDirections( directions ); if( this->m_IsMosaicData ) { mitk::DiffusionHeaderSiemensMosaicDICOMFileReader::Pointer mosaic_reader = dynamic_cast< mitk::DiffusionHeaderSiemensMosaicDICOMFileReader* >( this->m_HeaderReader.GetPointer() ); // retrieve the remaining meta-information needed for mosaic reconstruction // it suffices to get it exemplatory from the first file in the file list mosaic_reader->RetrieveMosaicInformation( filenames.at(0).at(0) ); mitk::MosaicDescriptor mdesc = mosaic_reader->GetMosaicDescriptor(); output_image->SetVectorImage( helper.LoadMosaicToVector<short, 3>( filenames, mdesc ) ); } else { output_image->SetVectorImage( helper.LoadToVector<short, 3>( filenames ) ); } output_image->InitializeFromVectorImage(); //output_image->UpdateBValueMap(); // reduce the number of outputs to 1 as we will produce a single image this->SetNumberOfOutputs(1); // set the image to output DICOMImageBlockDescriptor& block = this->InternalGetOutput(0); block.SetMitkImage( (mitk::Image::Pointer) output_image ); return block.GetMitkImage().IsNotNull(); } void mitk::DiffusionDICOMFileReader ::AnalyzeInputFiles() { Superclass::AnalyzeInputFiles(); // collect output from superclass size_t number_of_outputs = this->GetNumberOfOutputs(); if(number_of_outputs == 0) { MITK_ERROR << "Failed to parse input, retrieved 0 outputs from SeriesGDCMReader "; } DICOMImageBlockDescriptor block_0 = this->GetOutput(0); MITK_INFO << "Retrieved " << number_of_outputs << "outputs."; // collect vendor ID from the first output, first image StringList inputFilename; DICOMImageFrameInfo::Pointer frame_0 = block_0.GetImageFrameList().at(0); inputFilename.push_back( frame_0->Filename ); gdcm::Scanner gdcmScanner; gdcm::Tag t_vendor(0x008, 0x0070); gdcm::Tag t_imagetype(0x008, 0x008); // add DICOM Tag for vendor gdcmScanner.AddTag( t_vendor ); // add DICOM Tag for image type gdcmScanner.AddTag( t_imagetype ); gdcmScanner.Scan( inputFilename ); // retrieve both vendor and image type std::string vendor = gdcmScanner.GetValue( frame_0->Filename.c_str(), t_vendor ); std::string image_type = gdcmScanner.GetValue( frame_0->Filename.c_str(), t_imagetype ); MITK_INFO << "Got vendor: " << vendor << " image type " << image_type; // parse vendor tag if( vendor.find("SIEMENS") != std::string::npos ) { if( image_type.find("MOSAIC") != std::string::npos ) { m_HeaderReader = mitk::DiffusionHeaderSiemensMosaicDICOMFileReader::New(); this->m_IsMosaicData = true; } else { m_HeaderReader = mitk::DiffusionHeaderSiemensDICOMFileReader::New(); } } else if( vendor.find("GE") != std::string::npos ) { m_HeaderReader = mitk::DiffusionHeaderGEDICOMFileReader::New(); } else if( vendor.find("Philips") != std::string::npos ) { m_HeaderReader = mitk::DiffusionHeaderPhilipsDICOMFileReader::New(); } else { // unknown vendor } if( m_HeaderReader.IsNull() ) { MITK_ERROR << "No header reader for given vendor. "; return; } bool canread = false; for( size_t idx = 0; idx < number_of_outputs; idx++ ) { DICOMImageFrameInfo::Pointer frame = this->GetOutput( idx ).GetImageFrameList().at(0); canread = m_HeaderReader->ReadDiffusionHeader(frame->Filename); } // collect the information m_RetrievedHeader = m_HeaderReader->GetHeaderInformation(); // TODO : Analyze outputs + header information, i.e. for the loading confidence MITK_INFO << "----- Diffusion DICOM Analysis Report ---- "; PerformHeaderAnalysis( m_RetrievedHeader ); MITK_INFO << "==========================================="; } bool mitk::DiffusionDICOMFileReader ::CanHandleFile(const std::string &filename) { //FIXME : return true; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: menubarmanager.hxx,v $ * * $Revision: 1.8 $ * * last change: $Author: kz $ $Date: 2005-03-01 19:29:47 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef __FRAMEWORK_UIELEMENT_MENUBARMANAGER_HXX_ #define __FRAMEWORK_UIELEMENT_MENUBARMANAGER_HXX_ /** Attention: stl headers must(!) be included at first. Otherwhise it can make trouble with solaris headers ... */ #include <vector> //_________________________________________________________________________________________________________________ // my own includes //_________________________________________________________________________________________________________________ #ifndef __FRAMEWORK_THREADHELP_THREADHELPBASE_HXX_ #include <threadhelp/threadhelpbase.hxx> #endif #ifndef __FRAMEWORK_MACROS_DEBUG_HXX_ #include <macros/debug.hxx> #endif //_________________________________________________________________________________________________________________ // interface includes //_________________________________________________________________________________________________________________ #ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_ #include <com/sun/star/frame/XFrame.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_XDISPATCH_HPP_ #include <com/sun/star/frame/XDispatch.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_FEATURESTATEEVENT_HPP_ #include <com/sun/star/frame/FeatureStateEvent.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_XFRAMEACTIONLISTENER_HPP_ #include <com/sun/star/frame/XFrameActionListener.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_ #include <com/sun/star/beans/PropertyValue.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_XPOPUPMENUCONTROLLER_HPP_ #include <com/sun/star/frame/XPopupMenuController.hpp> #endif #ifndef _COM_SUN_STAR_AWT_XSYSTEMDEPENDENTMENUPEER_HPP_ #include <com/sun/star/awt/XSystemDependentMenuPeer.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XINDEXACCESS_HPP_ #include <com/sun/star/container/XIndexAccess.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_ #include <com/sun/star/container/XNameAccess.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_ #include <com/sun/star/lang/XComponent.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XMULTICOMPONENTFACTORY_HPP_ #include <com/sun/star/lang/XMultiComponentFactory.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_XUICONTROLLERREGISTRATION_HPP_ #include <com/sun/star/frame/XUIControllerRegistration.hpp> #endif #ifndef _COM_SUN_STAR_UI_XUICONFIGURATIONLISTENER_HPP_ #include <com/sun/star/ui/XUIConfigurationListener.hpp> #endif #ifndef _COM_SUN_STAR_UI_XIMAGEMANAGER_HPP_ #include <com/sun/star/ui/XImageManager.hpp> #endif #ifndef _COM_SUN_STAR_UI_XACCELERATORCONFIGURATION_HPP_ #include <com/sun/star/ui/XAcceleratorConfiguration.hpp> #endif //_________________________________________________________________________________________________________________ // other includes //_________________________________________________________________________________________________________________ #ifndef _RTL_USTRING_ #include <rtl/ustring.hxx> #endif #ifndef _SV_MENU_HXX #include <vcl/menu.hxx> #endif #ifndef _SV_ACCEL_HXX #include <vcl/accel.hxx> #endif #ifndef _TOOLKIT_AWT_VCLXMENU_HXX_ #include <toolkit/awt/vclxmenu.hxx> #endif #ifndef _CPPUHELPER_WEAK_HXX_ #include <cppuhelper/weak.hxx> #endif #ifndef _CPPUHELPER_INTERFACECONTAINER_HXX_ #include <cppuhelper/interfacecontainer.hxx> #endif // #110897# #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif namespace framework { class BmkMenu; class AddonMenu; class AddonPopupMenu; class MenuBarManager : public com::sun::star::frame::XStatusListener , public com::sun::star::frame::XFrameActionListener , public com::sun::star::ui::XUIConfigurationListener , public com::sun::star::lang::XComponent , public com::sun::star::awt::XSystemDependentMenuPeer , public ThreadHelpBase , public ::cppu::OWeakObject { protected: // #110897# MenuBarManager( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceFactory, com::sun::star::uno::Reference< com::sun::star::frame::XFrame >& rFrame, AddonMenu* pAddonMenu, sal_Bool bDelete, sal_Bool bDeleteChildren ); // #110897# MenuBarManager( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceFactory, com::sun::star::uno::Reference< com::sun::star::frame::XFrame >& rFrame, AddonPopupMenu* pAddonMenu, sal_Bool bDelete, sal_Bool bDeleteChildren ); public: // #110897# MenuBarManager( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceFactory, com::sun::star::uno::Reference< com::sun::star::frame::XFrame >& rFrame, Menu* pMenu, sal_Bool bDelete, sal_Bool bDeleteChildren ); // #110897# const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& getServiceFactory(); virtual ~MenuBarManager(); // XInterface virtual void SAL_CALL acquire() throw(); virtual void SAL_CALL release() throw(); virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type & rType ) throw( ::com::sun::star::uno::RuntimeException ); // XComponent virtual void SAL_CALL dispose() throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL addEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& xListener ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL removeEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& aListener ) throw (::com::sun::star::uno::RuntimeException); // XStatusListener virtual void SAL_CALL statusChanged( const com::sun::star::frame::FeatureStateEvent& Event ) throw ( ::com::sun::star::uno::RuntimeException ); // XFrameActionListener virtual void SAL_CALL frameAction( const com::sun::star::frame::FrameActionEvent& Action ) throw ( ::com::sun::star::uno::RuntimeException ); // XEventListener virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source ) throw ( ::com::sun::star::uno::RuntimeException ); // XUIConfigurationListener virtual void SAL_CALL elementInserted( const ::com::sun::star::ui::ConfigurationEvent& Event ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL elementRemoved( const ::com::sun::star::ui::ConfigurationEvent& Event ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL elementReplaced( const ::com::sun::star::ui::ConfigurationEvent& Event ) throw (::com::sun::star::uno::RuntimeException); // XSystemDependentMenuPeer virtual ::com::sun::star::uno::Any SAL_CALL getMenuHandle( const ::com::sun::star::uno::Sequence< sal_Int8 >& ProcessId, sal_Int16 SystemType ) throw (::com::sun::star::uno::RuntimeException); DECL_LINK( Select, Menu * ); Menu* GetMenuBar() const { return m_pVCLMenu; } // Configuration methods static void FillMenu( USHORT& nId, Menu* pMenu, const ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexAccess >& rItemContainer ); void FillMenuManager( Menu* pMenu, ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame, sal_Bool bDelete, sal_Bool bDeleteChildren ); void SetItemContainer( const ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexAccess >& rItemContainer ); protected: DECL_LINK( Highlight, Menu * ); DECL_LINK( Activate, Menu * ); DECL_LINK( Deactivate, Menu * ); void RemoveListener(); void RequestImages(); void RetrieveImageManagers(); private: String RetrieveLabelFromCommand( const String& aCmdURL ); void UpdateSpecialFileMenu( Menu* pMenu ); void UpdateSpecialWindowMenu( Menu* pMenu ); void Destroy(); struct MenuItemHandler { MenuItemHandler( USHORT aItemId, ::com::sun::star::uno::Reference< ::com::sun::star::frame::XStatusListener >& xManager, ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch >& rDispatch ) : nItemId( aItemId ), xSubMenuManager( xManager ), xMenuItemDispatch( rDispatch ) {} USHORT nItemId; ::rtl::OUString aTargetFrame; ::rtl::OUString aMenuItemURL; ::rtl::OUString aFilter; ::rtl::OUString aPassword; ::rtl::OUString aTitle; ::com::sun::star::uno::Reference< ::com::sun::star::frame::XStatusListener > xSubMenuManager; ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch > xMenuItemDispatch; ::com::sun::star::uno::Reference< ::com::sun::star::frame::XPopupMenuController > xPopupMenuController; ::com::sun::star::uno::Reference< ::com::sun::star::awt::XPopupMenu > xPopupMenu; KeyCode aKeyCode; }; void RetrieveShortcuts( std::vector< MenuItemHandler* >& aMenuShortCuts ); void CreatePicklistArguments( ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& aArgsList, const MenuItemHandler* ); static void impl_RetrieveShortcutsFromConfiguration( const ::com::sun::star::uno::Reference< ::com::sun::star::ui::XAcceleratorConfiguration >& rAccelCfg, const ::com::sun::star::uno::Sequence< rtl::OUString >& rCommands, std::vector< MenuItemHandler* >& aMenuShortCuts ); MenuItemHandler* GetMenuItemHandler( USHORT nItemId ); sal_Bool m_bDisposed : 1, m_bInitialized : 1, m_bDeleteMenu : 1, m_bDeleteChildren : 1, m_bActive : 1, m_bIsBookmarkMenu : 1, m_bWasHiContrast : 1, m_bShowMenuImages : 1; sal_Bool m_bModuleIdentified : 1, m_bRetrieveImages : 1, m_bAcceleratorCfg : 1; ::rtl::OUString m_aMenuItemCommand; ::rtl::OUString m_aModuleIdentifier; Menu* m_pVCLMenu; ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame > m_xFrame; ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess > m_xUICommandLabels; ::com::sun::star::uno::Reference< ::com::sun::star::frame::XUIControllerRegistration > m_xPopupMenuControllerRegistration; ::std::vector< MenuItemHandler* > m_aMenuItemHandlerVector; ::cppu::OMultiTypeInterfaceContainerHelper m_aListenerContainer; /// container for ALL Listener ::com::sun::star::uno::Reference< ::com::sun::star::ui::XImageManager > m_xDocImageManager; ::com::sun::star::uno::Reference< ::com::sun::star::ui::XImageManager > m_xModuleImageManager; ::com::sun::star::uno::Reference< ::com::sun::star::ui::XAcceleratorConfiguration > m_xDocAcceleratorManager; ::com::sun::star::uno::Reference< ::com::sun::star::ui::XAcceleratorConfiguration > m_xModuleAcceleratorManager; ::com::sun::star::uno::Reference< ::com::sun::star::ui::XAcceleratorConfiguration > m_xGlobalAcceleratorManager; // #110897# const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& mxServiceFactory; }; } // namespace #endif <commit_msg>INTEGRATION: CWS fwkfinal1 (1.8.4); FILE MERGED 2005/03/04 14:45:36 cd 1.8.4.1: #i38064# Use provided module identifier to retrieve command labels for OLE<commit_after>/************************************************************************* * * $RCSfile: menubarmanager.hxx,v $ * * $Revision: 1.9 $ * * last change: $Author: vg $ $Date: 2005-03-23 14:11:03 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef __FRAMEWORK_UIELEMENT_MENUBARMANAGER_HXX_ #define __FRAMEWORK_UIELEMENT_MENUBARMANAGER_HXX_ /** Attention: stl headers must(!) be included at first. Otherwhise it can make trouble with solaris headers ... */ #include <vector> //_________________________________________________________________________________________________________________ // my own includes //_________________________________________________________________________________________________________________ #ifndef __FRAMEWORK_THREADHELP_THREADHELPBASE_HXX_ #include <threadhelp/threadhelpbase.hxx> #endif #ifndef __FRAMEWORK_MACROS_DEBUG_HXX_ #include <macros/debug.hxx> #endif //_________________________________________________________________________________________________________________ // interface includes //_________________________________________________________________________________________________________________ #ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_ #include <com/sun/star/frame/XFrame.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_XDISPATCH_HPP_ #include <com/sun/star/frame/XDispatch.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_FEATURESTATEEVENT_HPP_ #include <com/sun/star/frame/FeatureStateEvent.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_XFRAMEACTIONLISTENER_HPP_ #include <com/sun/star/frame/XFrameActionListener.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_ #include <com/sun/star/beans/PropertyValue.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_XPOPUPMENUCONTROLLER_HPP_ #include <com/sun/star/frame/XPopupMenuController.hpp> #endif #ifndef _COM_SUN_STAR_AWT_XSYSTEMDEPENDENTMENUPEER_HPP_ #include <com/sun/star/awt/XSystemDependentMenuPeer.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XINDEXACCESS_HPP_ #include <com/sun/star/container/XIndexAccess.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_ #include <com/sun/star/container/XNameAccess.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_ #include <com/sun/star/lang/XComponent.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XMULTICOMPONENTFACTORY_HPP_ #include <com/sun/star/lang/XMultiComponentFactory.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_XUICONTROLLERREGISTRATION_HPP_ #include <com/sun/star/frame/XUIControllerRegistration.hpp> #endif #ifndef _COM_SUN_STAR_UI_XUICONFIGURATIONLISTENER_HPP_ #include <com/sun/star/ui/XUIConfigurationListener.hpp> #endif #ifndef _COM_SUN_STAR_UI_XIMAGEMANAGER_HPP_ #include <com/sun/star/ui/XImageManager.hpp> #endif #ifndef _COM_SUN_STAR_UI_XACCELERATORCONFIGURATION_HPP_ #include <com/sun/star/ui/XAcceleratorConfiguration.hpp> #endif //_________________________________________________________________________________________________________________ // other includes //_________________________________________________________________________________________________________________ #ifndef _RTL_USTRING_ #include <rtl/ustring.hxx> #endif #ifndef _SV_MENU_HXX #include <vcl/menu.hxx> #endif #ifndef _SV_ACCEL_HXX #include <vcl/accel.hxx> #endif #ifndef _TOOLKIT_AWT_VCLXMENU_HXX_ #include <toolkit/awt/vclxmenu.hxx> #endif #ifndef _CPPUHELPER_WEAK_HXX_ #include <cppuhelper/weak.hxx> #endif #ifndef _CPPUHELPER_INTERFACECONTAINER_HXX_ #include <cppuhelper/interfacecontainer.hxx> #endif // #110897# #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif namespace framework { class BmkMenu; class AddonMenu; class AddonPopupMenu; class MenuBarManager : public com::sun::star::frame::XStatusListener , public com::sun::star::frame::XFrameActionListener , public com::sun::star::ui::XUIConfigurationListener , public com::sun::star::lang::XComponent , public com::sun::star::awt::XSystemDependentMenuPeer , public ThreadHelpBase , public ::cppu::OWeakObject { protected: // #110897# MenuBarManager( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceFactory, com::sun::star::uno::Reference< com::sun::star::frame::XFrame >& rFrame, AddonMenu* pAddonMenu, sal_Bool bDelete, sal_Bool bDeleteChildren ); // #110897# MenuBarManager( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceFactory, com::sun::star::uno::Reference< com::sun::star::frame::XFrame >& rFrame, AddonPopupMenu* pAddonMenu, sal_Bool bDelete, sal_Bool bDeleteChildren ); public: // #110897# MenuBarManager( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceFactory, com::sun::star::uno::Reference< com::sun::star::frame::XFrame >& rFrame, const rtl::OUString& aModuleIdentifier, Menu* pMenu, sal_Bool bDelete, sal_Bool bDeleteChildren ); // #110897# const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& getServiceFactory(); virtual ~MenuBarManager(); // XInterface virtual void SAL_CALL acquire() throw(); virtual void SAL_CALL release() throw(); virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type & rType ) throw( ::com::sun::star::uno::RuntimeException ); // XComponent virtual void SAL_CALL dispose() throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL addEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& xListener ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL removeEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& aListener ) throw (::com::sun::star::uno::RuntimeException); // XStatusListener virtual void SAL_CALL statusChanged( const com::sun::star::frame::FeatureStateEvent& Event ) throw ( ::com::sun::star::uno::RuntimeException ); // XFrameActionListener virtual void SAL_CALL frameAction( const com::sun::star::frame::FrameActionEvent& Action ) throw ( ::com::sun::star::uno::RuntimeException ); // XEventListener virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source ) throw ( ::com::sun::star::uno::RuntimeException ); // XUIConfigurationListener virtual void SAL_CALL elementInserted( const ::com::sun::star::ui::ConfigurationEvent& Event ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL elementRemoved( const ::com::sun::star::ui::ConfigurationEvent& Event ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL elementReplaced( const ::com::sun::star::ui::ConfigurationEvent& Event ) throw (::com::sun::star::uno::RuntimeException); // XSystemDependentMenuPeer virtual ::com::sun::star::uno::Any SAL_CALL getMenuHandle( const ::com::sun::star::uno::Sequence< sal_Int8 >& ProcessId, sal_Int16 SystemType ) throw (::com::sun::star::uno::RuntimeException); DECL_LINK( Select, Menu * ); Menu* GetMenuBar() const { return m_pVCLMenu; } // Configuration methods static void FillMenu( USHORT& nId, Menu* pMenu, const ::rtl::OUString& rModuleIdentifier, const ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexAccess >& rItemContainer ); void FillMenuManager( Menu* pMenu, ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame, const rtl::OUString& rModuleIdentifier, sal_Bool bDelete, sal_Bool bDeleteChildren ); void SetItemContainer( const ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexAccess >& rItemContainer ); protected: DECL_LINK( Highlight, Menu * ); DECL_LINK( Activate, Menu * ); DECL_LINK( Deactivate, Menu * ); void RemoveListener(); void RequestImages(); void RetrieveImageManagers(); private: String RetrieveLabelFromCommand( const String& aCmdURL ); void UpdateSpecialFileMenu( Menu* pMenu ); void UpdateSpecialWindowMenu( Menu* pMenu ); void Destroy(); struct MenuItemHandler { MenuItemHandler( USHORT aItemId, ::com::sun::star::uno::Reference< ::com::sun::star::frame::XStatusListener >& xManager, ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch >& rDispatch ) : nItemId( aItemId ), xSubMenuManager( xManager ), xMenuItemDispatch( rDispatch ) {} USHORT nItemId; ::rtl::OUString aTargetFrame; ::rtl::OUString aMenuItemURL; ::rtl::OUString aFilter; ::rtl::OUString aPassword; ::rtl::OUString aTitle; ::com::sun::star::uno::Reference< ::com::sun::star::frame::XStatusListener > xSubMenuManager; ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch > xMenuItemDispatch; ::com::sun::star::uno::Reference< ::com::sun::star::frame::XPopupMenuController > xPopupMenuController; ::com::sun::star::uno::Reference< ::com::sun::star::awt::XPopupMenu > xPopupMenu; KeyCode aKeyCode; }; void RetrieveShortcuts( std::vector< MenuItemHandler* >& aMenuShortCuts ); void CreatePicklistArguments( ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& aArgsList, const MenuItemHandler* ); static void impl_RetrieveShortcutsFromConfiguration( const ::com::sun::star::uno::Reference< ::com::sun::star::ui::XAcceleratorConfiguration >& rAccelCfg, const ::com::sun::star::uno::Sequence< rtl::OUString >& rCommands, std::vector< MenuItemHandler* >& aMenuShortCuts ); MenuItemHandler* GetMenuItemHandler( USHORT nItemId ); sal_Bool m_bDisposed : 1, m_bInitialized : 1, m_bDeleteMenu : 1, m_bDeleteChildren : 1, m_bActive : 1, m_bIsBookmarkMenu : 1, m_bWasHiContrast : 1, m_bShowMenuImages : 1; sal_Bool m_bModuleIdentified : 1, m_bRetrieveImages : 1, m_bAcceleratorCfg : 1; ::rtl::OUString m_aMenuItemCommand; ::rtl::OUString m_aModuleIdentifier; Menu* m_pVCLMenu; ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame > m_xFrame; ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess > m_xUICommandLabels; ::com::sun::star::uno::Reference< ::com::sun::star::frame::XUIControllerRegistration > m_xPopupMenuControllerRegistration; ::std::vector< MenuItemHandler* > m_aMenuItemHandlerVector; ::cppu::OMultiTypeInterfaceContainerHelper m_aListenerContainer; /// container for ALL Listener ::com::sun::star::uno::Reference< ::com::sun::star::ui::XImageManager > m_xDocImageManager; ::com::sun::star::uno::Reference< ::com::sun::star::ui::XImageManager > m_xModuleImageManager; ::com::sun::star::uno::Reference< ::com::sun::star::ui::XAcceleratorConfiguration > m_xDocAcceleratorManager; ::com::sun::star::uno::Reference< ::com::sun::star::ui::XAcceleratorConfiguration > m_xModuleAcceleratorManager; ::com::sun::star::uno::Reference< ::com::sun::star::ui::XAcceleratorConfiguration > m_xGlobalAcceleratorManager; // #110897# const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& mxServiceFactory; }; } // namespace #endif <|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 "otbWrapperMapProjectionParametersHandler.h" // Needed for methods relative to projections #include "otbImageToGenericRSOutputParameters.h" #include "otbWrapperInputImageListParameter.h" namespace otb { namespace Wrapper { void MapProjectionParametersHandler::AddMapProjectionParameters( Application::Pointer app, const std::string & key) { app->AddParameter(ParameterType_Choice, key, "Map Projection"); app->SetParameterDescription(key,"Defines the map projection to be used."); // utm std::ostringstream oss; oss << key<<".utm"; app->AddChoice(oss.str(), "Universal Trans-Mercator (UTM)"); app->SetParameterDescription(oss.str(),"A system of transverse mercator projections dividing the surface of Earth between 80S and 84N latitude."); oss << ".zone"; app->AddParameter(ParameterType_Int, oss.str(), "Zone number"); app->SetParameterDescription(oss.str(),"The zone number ranges from 1 to 60 and allows defining the transverse mercator projection (along with the hemisphere)"); app->SetMinimumParameterIntValue(oss.str(), 1); app->SetDefaultParameterInt(oss.str(), 31); oss.str(""); oss <<key<<".utm" <<".northhem"; app->AddParameter(ParameterType_Bool, oss.str(), "Northern Hemisphere"); app->SetParameterDescription(oss.str(),"The transverse mercator projections are defined by their zone number as well as the hemisphere. Activate this parameter if your image is in the northern hemisphere."); // lambert2 oss.str(""); oss << key<<".lambert2"; app->AddChoice(oss.str(), "Lambert II Etendu"); app->SetParameterDescription(oss.str(),"This is a Lambert Conformal Conic projection mainly used in France."); // lambert93 oss.str(""); oss << key<<".lambert93"; app->AddChoice(oss.str(), "Lambert93"); app->SetParameterDescription(oss.str(), "This is a Lambert 93 projection mainly used in France."); // wgs84 oss.str(""); oss << key<<".wgs"; app->AddChoice(oss.str(), "WGS 84"); app->SetParameterDescription(oss.str(),"This is a Geographical projection"); // epsg code oss.str(""); oss<<key<<".epsg"; app->AddChoice(oss.str(),"EPSG Code"); app->SetParameterDescription(oss.str(), "This code is a generic way of identifying map projections, and allows specifying a large amount of them. See www.spatialreference.org to find which EPSG code is associated to your projection;"); oss <<".code"; app->AddParameter(ParameterType_Int, oss.str(), "EPSG Code"); app->SetParameterDescription(oss.str(),"See www.spatialreference.org to find which EPSG code is associated to your projection"); app->SetDefaultParameterInt(oss.str(), 4326); app->SetParameterString(key, "utm"); } /** * Helper method : Compute the ProjectionRef knowing the map * projection picked up by the user * */ const std::string MapProjectionParametersHandler::GetProjectionRefFromChoice(const Application::Pointer app, const std::string & key) { std::ostringstream zoneKey; zoneKey << key<<".utm.zone"; std::ostringstream hemKey; hemKey << key<<".utm.northhem"; std::ostringstream epsgKey; epsgKey << key <<".epsg.code"; // Get the user choice switch ( app->GetParameterInt(key) ) { case Map_Utm: { return OGRSpatialReferenceAdapter(app->GetParameterInt(zoneKey.str()),app->IsParameterEnabled(hemKey.str())).ToWkt(); } break; case Map_Lambert2: { return OGRSpatialReferenceAdapter("IGNF:LAMBE").ToWkt(); } break; case Map_Lambert93: { return OGRSpatialReferenceAdapter("IGNF:LAMB93").ToWkt(); } break; case Map_WGS84: { return OGRSpatialReferenceAdapter().ToWkt(); } break; case Map_Epsg: { return OGRSpatialReferenceAdapter(app->GetParameterInt(epsgKey.str())).ToWkt(); } break; } return ""; } /** * Helper method : Compute the UTM parameters relative to an image Origin * Note: The key of the image must be set to be able to get the image. * The key must be totally if the InputImageParameter belongs * to a ParameterGroup, ie set io.in */ void MapProjectionParametersHandler::InitializeUTMParameters(Application::Pointer app, const std::string & imageKey, const std::string & mapKey ) { // Get the UTM params keys std::ostringstream zoneKey; zoneKey << mapKey << ".utm.zone"; std::ostringstream hemKey; hemKey << mapKey << ".utm.northhem"; // Compute the zone and the hemisphere if not UserValue defined if (!app->HasUserValue(zoneKey.str()) && app->HasValue(imageKey)) { // Compute the Origin lat/long coordinate typedef otb::ImageToGenericRSOutputParameters<FloatVectorImageType> OutputParametersEstimatorType; OutputParametersEstimatorType::Pointer genericRSEstimator = OutputParametersEstimatorType::New(); Parameter* param = app->GetParameterByKey(imageKey); if (dynamic_cast<InputImageParameter*> (param)) { genericRSEstimator->SetInput(app->GetParameterImage(imageKey)); } else if (dynamic_cast<InputImageListParameter*> (param)) { genericRSEstimator->SetInput(app->GetParameterImageList(imageKey)->GetNthElement(0)); } genericRSEstimator->SetOutputProjectionRef(otb::GeoInformationConversion::ToWKT(4326)); genericRSEstimator->Compute(); int zone = otb::Utils::GetZoneFromGeoPoint(genericRSEstimator->GetOutputOrigin()[0], genericRSEstimator->GetOutputOrigin()[1]); // Update the UTM Gui fields app->SetParameterInt(zoneKey.str(), zone); if (genericRSEstimator->GetOutputOrigin()[1] > 0.) { app->EnableParameter(hemKey.str()); } else { app->DisableParameter(hemKey.str()); } app->AutomaticValueOn(zoneKey.str()); app->AutomaticValueOn(hemKey.str()); } } }// End namespace Wrapper }// End namespace otb <commit_msg>REFAC: Use new OGRSpatialReferenceAdapter::UTMFromGeoPoint() method<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 "otbWrapperMapProjectionParametersHandler.h" // Needed for methods relative to projections #include "otbImageToGenericRSOutputParameters.h" #include "otbWrapperInputImageListParameter.h" namespace otb { namespace Wrapper { void MapProjectionParametersHandler::AddMapProjectionParameters( Application::Pointer app, const std::string & key) { app->AddParameter(ParameterType_Choice, key, "Map Projection"); app->SetParameterDescription(key,"Defines the map projection to be used."); // utm std::ostringstream oss; oss << key<<".utm"; app->AddChoice(oss.str(), "Universal Trans-Mercator (UTM)"); app->SetParameterDescription(oss.str(),"A system of transverse mercator projections dividing the surface of Earth between 80S and 84N latitude."); oss << ".zone"; app->AddParameter(ParameterType_Int, oss.str(), "Zone number"); app->SetParameterDescription(oss.str(),"The zone number ranges from 1 to 60 and allows defining the transverse mercator projection (along with the hemisphere)"); app->SetMinimumParameterIntValue(oss.str(), 1); app->SetDefaultParameterInt(oss.str(), 31); oss.str(""); oss <<key<<".utm" <<".northhem"; app->AddParameter(ParameterType_Bool, oss.str(), "Northern Hemisphere"); app->SetParameterDescription(oss.str(),"The transverse mercator projections are defined by their zone number as well as the hemisphere. Activate this parameter if your image is in the northern hemisphere."); // lambert2 oss.str(""); oss << key<<".lambert2"; app->AddChoice(oss.str(), "Lambert II Etendu"); app->SetParameterDescription(oss.str(),"This is a Lambert Conformal Conic projection mainly used in France."); // lambert93 oss.str(""); oss << key<<".lambert93"; app->AddChoice(oss.str(), "Lambert93"); app->SetParameterDescription(oss.str(), "This is a Lambert 93 projection mainly used in France."); // wgs84 oss.str(""); oss << key<<".wgs"; app->AddChoice(oss.str(), "WGS 84"); app->SetParameterDescription(oss.str(),"This is a Geographical projection"); // epsg code oss.str(""); oss<<key<<".epsg"; app->AddChoice(oss.str(),"EPSG Code"); app->SetParameterDescription(oss.str(), "This code is a generic way of identifying map projections, and allows specifying a large amount of them. See www.spatialreference.org to find which EPSG code is associated to your projection;"); oss <<".code"; app->AddParameter(ParameterType_Int, oss.str(), "EPSG Code"); app->SetParameterDescription(oss.str(),"See www.spatialreference.org to find which EPSG code is associated to your projection"); app->SetDefaultParameterInt(oss.str(), 4326); app->SetParameterString(key, "utm"); } /** * Helper method : Compute the ProjectionRef knowing the map * projection picked up by the user * */ const std::string MapProjectionParametersHandler::GetProjectionRefFromChoice(const Application::Pointer app, const std::string & key) { std::ostringstream zoneKey; zoneKey << key<<".utm.zone"; std::ostringstream hemKey; hemKey << key<<".utm.northhem"; std::ostringstream epsgKey; epsgKey << key <<".epsg.code"; // Get the user choice switch ( app->GetParameterInt(key) ) { case Map_Utm: { return OGRSpatialReferenceAdapter(app->GetParameterInt(zoneKey.str()),app->IsParameterEnabled(hemKey.str())).ToWkt(); } break; case Map_Lambert2: { return OGRSpatialReferenceAdapter("IGNF:LAMBE").ToWkt(); } break; case Map_Lambert93: { return OGRSpatialReferenceAdapter("IGNF:LAMB93").ToWkt(); } break; case Map_WGS84: { return OGRSpatialReferenceAdapter().ToWkt(); } break; case Map_Epsg: { return OGRSpatialReferenceAdapter(app->GetParameterInt(epsgKey.str())).ToWkt(); } break; } return ""; } /** * Helper method : Compute the UTM parameters relative to an image Origin * Note: The key of the image must be set to be able to get the image. * The key must be totally if the InputImageParameter belongs * to a ParameterGroup, ie set io.in */ void MapProjectionParametersHandler::InitializeUTMParameters(Application::Pointer app, const std::string & imageKey, const std::string & mapKey ) { // Get the UTM params keys std::ostringstream zoneKey; zoneKey << mapKey << ".utm.zone"; std::ostringstream hemKey; hemKey << mapKey << ".utm.northhem"; // Compute the zone and the hemisphere if not UserValue defined if (!app->HasUserValue(zoneKey.str()) && app->HasValue(imageKey)) { // Compute the Origin lat/long coordinate typedef otb::ImageToGenericRSOutputParameters<FloatVectorImageType> OutputParametersEstimatorType; OutputParametersEstimatorType::Pointer genericRSEstimator = OutputParametersEstimatorType::New(); Parameter* param = app->GetParameterByKey(imageKey); if (dynamic_cast<InputImageParameter*> (param)) { genericRSEstimator->SetInput(app->GetParameterImage(imageKey)); } else if (dynamic_cast<InputImageListParameter*> (param)) { genericRSEstimator->SetInput(app->GetParameterImageList(imageKey)->GetNthElement(0)); } genericRSEstimator->SetOutputProjectionRef(OGRSpatialReferenceAdapter().ToWkt()); genericRSEstimator->Compute(); unsigned int zone(0); bool north(true); otb::OGRSpatialReferenceAdapter::UTMFromGeoPoint(genericRSEstimator->GetOutputOrigin()[0], genericRSEstimator->GetOutputOrigin()[1], zone, north); // Update the UTM Gui fields app->SetParameterInt(zoneKey.str(), zone); if (north) { app->EnableParameter(hemKey.str()); } else { app->DisableParameter(hemKey.str()); } app->AutomaticValueOn(zoneKey.str()); app->AutomaticValueOn(hemKey.str()); } } }// End namespace Wrapper }// End namespace otb <|endoftext|>
<commit_before>// // Created by phitherek on 20.11.15. // #include <iostream> #include <cstdlib> #include "Converter.h" #include "ConversionError.h" using namespace std; int main() { cout << "ConversionTest for OziExplorer to UI-View Converter v. 0.2 (C) 2015 by Phitherek_ SO9PH" << std::endl; try { Converter c("siatka.map", "siatka.inf"); c.convert(); } catch(ConversionError& e) { cerr << "Caught ConversionError: " << e.what() << std::endl; cout << "Failure!" << std::endl; return EXIT_FAILURE; } cout << "Success!" << std::endl; return EXIT_SUCCESS; }<commit_msg>Better ConversionTest.<commit_after>// // Created by phitherek on 20.11.15. // #include <iostream> #include <cstdlib> #include <typeinfo> #include "Converter.h" #include "ConversionError.h" using namespace std; int main() { try { cout << "ConversionTest for OziExplorer to UI-View Converter v. 0.2 (C) 2015 by Phitherek_ SO9PH" << std::endl; try { Converter c("siatka.map", "siatka.inf"); c.convert(); } catch(ConversionError& e) { cerr << "Caught ConversionError: " << e.what() << std::endl; cout << "Failure!" << std::endl; return EXIT_FAILURE; } cout << "Success!" << std::endl; return EXIT_SUCCESS; } catch(std::exception& e) { cout << "Caught exception: " << typeid(e).name() << ": " << e.what() << endl; return EXIT_FAILURE; } }<|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: toolbarmanager.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: kz $ $Date: 2005-01-13 18:54:20 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef __FRAMEWORK_UIELEMENT_TOOLBARMANAGER_HXX_ #define __FRAMEWORK_UIELEMENT_TOOLBARMANAGER_HXX_ //_________________________________________________________________________________________________________________ // my own includes //_________________________________________________________________________________________________________________ #ifndef __FRAMEWORK_THREADHELP_THREADHELPBASE_HXX_ #include <threadhelp/threadhelpbase.hxx> #endif #ifndef __FRAMEWORK_MACROS_GENERIC_HXX_ #include <macros/generic.hxx> #endif #ifndef __FRAMEWORK_MACROS_XINTERFACE_HXX_ #include <macros/xinterface.hxx> #endif #ifndef __FRAMEWORK_MACROS_XTYPEPROVIDER_HXX_ #include <macros/xtypeprovider.hxx> #endif #ifndef __FRAMEWORK_STDTYPES_H_ #include <stdtypes.h> #endif //_________________________________________________________________________________________________________________ // interface includes //_________________________________________________________________________________________________________________ #ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_ #include <com/sun/star/frame/XFrame.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_XSTATUSLISTENER_HPP_ #include <com/sun/star/frame/XStatusListener.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_ #include <com/sun/star/lang/XComponent.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XINDEXACCESS_HPP_ #include <com/sun/star/container/XIndexAccess.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_ #include <com/sun/star/container/XNameAccess.hpp> #endif #ifndef _DRAFTS_COM_SUN_STAR_FRAME_XMODULEMANAGER_HPP_ #include <drafts/com/sun/star/frame/XModuleManager.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef _DRAFTS_COM_SUN_STAR_FRAME_XUICONTROLLERREGISTRATION_HPP_ #include <drafts/com/sun/star/frame/XUIControllerRegistration.hpp> #endif #ifndef _DRAFTS_COM_SUN_STAR_UI_XIMAGEMANAGER_HPP_ #include <drafts/com/sun/star/ui/XImageManager.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_XSTATUSLISTENER_HPP_ #include <com/sun/star/frame/XStatusListener.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_XSUBTOOLBARCONTROLLER_HPP_ #include <com/sun/star/frame/XSubToolbarController.hpp> #endif //_________________________________________________________________________________________________________________ // other includes //_________________________________________________________________________________________________________________ #ifndef _RTL_USTRING_ #include <rtl/ustring.hxx> #endif #ifndef _CPPUHELPER_WEAK_HXX_ #include <cppuhelper/weak.hxx> #endif #ifndef _CPPUHELPER_INTERFACECONTAINER_HXX_ #include <cppuhelper/interfacecontainer.hxx> #endif #include <vcl/toolbox.hxx> namespace framework { class ToolBar; class ToolBarManager : public ::com::sun::star::frame::XFrameActionListener , public ::com::sun::star::frame::XStatusListener , public ::com::sun::star::lang::XComponent , public ::com::sun::star::lang::XTypeProvider , public ::drafts::com::sun::star::ui::XUIConfigurationListener, public ThreadHelpBase , public ::cppu::OWeakObject { public: ToolBarManager( const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >& rServicveManager, const com::sun::star::uno::Reference< com::sun::star::frame::XFrame >& rFrame, const rtl::OUString& rResourceName, ToolBar* pToolBar ); virtual ~ToolBarManager(); // XInterface, XTypeProvider, XServiceInfo DECLARE_XINTERFACE DECLARE_XTYPEPROVIDER ToolBox* GetToolBar() const; // XFrameActionListener virtual void SAL_CALL frameAction( const com::sun::star::frame::FrameActionEvent& Action ) throw ( ::com::sun::star::uno::RuntimeException ); // XStatusListener virtual void SAL_CALL statusChanged( const ::com::sun::star::frame::FeatureStateEvent& Event ) throw ( ::com::sun::star::uno::RuntimeException ); // XEventListener virtual void SAL_CALL disposing( const com::sun::star::lang::EventObject& Source ) throw ( ::com::sun::star::uno::RuntimeException ); // XUIConfigurationListener virtual void SAL_CALL elementInserted( const ::drafts::com::sun::star::ui::ConfigurationEvent& Event ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL elementRemoved( const ::drafts::com::sun::star::ui::ConfigurationEvent& Event ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL elementReplaced( const ::drafts::com::sun::star::ui::ConfigurationEvent& Event ) throw (::com::sun::star::uno::RuntimeException); // XComponent void SAL_CALL dispose() throw ( ::com::sun::star::uno::RuntimeException ); void SAL_CALL addEventListener( const com::sun::star::uno::Reference< XEventListener >& xListener ) throw( com::sun::star::uno::RuntimeException ); void SAL_CALL removeEventListener( const com::sun::star::uno::Reference< XEventListener >& xListener ) throw( com::sun::star::uno::RuntimeException ); void CheckAndUpdateImages(); void RefreshImages(); void FillToolbar( const ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexAccess >& rToolBarData ); void notifyRegisteredControllers( const rtl::OUString& aUIElementName, const rtl::OUString& aCommand ); static sal_Int16 GetCurrentSymbolSize(); protected: struct ControllerParams { sal_Int16 nWidth; }; typedef std::vector< ControllerParams > ControllerParamsVector; DECL_LINK( Click, ToolBox * ); DECL_LINK( DropdownClick, ToolBox * ); DECL_LINK( DoubleClick, ToolBox * ); DECL_LINK( Select, ToolBox * ); DECL_LINK( Highlight, ToolBox * ); DECL_LINK( Activate, ToolBox * ); DECL_LINK( Deactivate, ToolBox * ); DECL_LINK( StateChanged, StateChangedType* ); DECL_LINK( DataChanged, DataChangedEvent* ); DECL_LINK( MenuButton, ToolBox * ); DECL_LINK( MenuSelect, Menu * ); DECL_LINK( MenuDeactivate, Menu * ); void RemoveControllers(); rtl::OUString RetrieveLabelFromCommand( const rtl::OUString& aCmdURL ); void CreateControllers( const ControllerParamsVector& ); void UpdateControllers(); void AddFrameActionListener(); void AddImageOrientationListener(); void UpdateImageOrientation(); void ImplClearPopupMenu( ToolBox *pToolBar ); protected: struct CommandInfo { CommandInfo() : nId( 0 ), nImageInfo( 0 ), bMirrored( false ), bRotated( false ) {} USHORT nId; std::vector<USHORT> aIds; sal_Int16 nImageInfo; sal_Bool bMirrored : 1, bRotated : 1; }; typedef std::vector< ::com::sun::star::uno::Reference< com::sun::star::frame::XStatusListener > > ToolBarControllerVector; typedef ::std::vector< ::com::sun::star::uno::Reference< ::com::sun::star::frame::XSubToolbarController > > SubToolBarControllerVector; typedef BaseHash< CommandInfo > CommandToInfoMap; typedef BaseHash< SubToolBarControllerVector > SubToolBarToSubToolBarControllerMap; sal_Bool m_bDisposed : 1, m_bIsHiContrast : 1, m_bSmallSymbols : 1, m_bModuleIdentified : 1, m_bAddedToTaskPaneList : 1, m_bVerticalTextEnabled : 1, m_bFrameActionRegistered : 1, m_bUpdateControllers : 1; sal_Bool m_bImageOrientationRegistered : 1, m_bImageMirrored : 1, m_bCanBeCustomized : 1; long m_lImageRotation; ToolBar* m_pToolBar; rtl::OUString m_aModuleIdentifier; rtl::OUString m_aResourceName; com::sun::star::uno::Reference< com::sun::star::frame::XFrame > m_xFrame; com::sun::star::uno::Reference< com::sun::star::container::XNameAccess > m_xUICommandLabels; ToolBarControllerVector m_aControllerVector; ::cppu::OMultiTypeInterfaceContainerHelper m_aListenerContainer; /// container for ALL Listener ::com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory > m_xServiceManager; ::com::sun::star::uno::Reference< ::drafts::com::sun::star::frame::XUIControllerRegistration > m_xToolbarControllerRegistration; ::com::sun::star::uno::Reference< ::drafts::com::sun::star::ui::XImageManager > m_xModuleImageManager; ::com::sun::star::uno::Reference< ::drafts::com::sun::star::ui::XImageManager > m_xDocImageManager; ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent > m_xImageOrientationListener; CommandToInfoMap m_aCommandMap; SubToolBarToSubToolBarControllerMap m_aSubToolBarControllerMap; }; } #endif // __FRAMEWORK_UIELEMENT_TOOLBARMANAGER_HXX_ <commit_msg>INTEGRATION: CWS fwkperf01 (1.4.20); FILE MERGED 2005/01/12 15:08:50 cd 1.4.20.1: #i37617# Improve performance switching Impress Views<commit_after>/************************************************************************* * * $RCSfile: toolbarmanager.hxx,v $ * * $Revision: 1.6 $ * * last change: $Author: kz $ $Date: 2005-01-21 09:50:35 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef __FRAMEWORK_UIELEMENT_TOOLBARMANAGER_HXX_ #define __FRAMEWORK_UIELEMENT_TOOLBARMANAGER_HXX_ //_________________________________________________________________________________________________________________ // my own includes //_________________________________________________________________________________________________________________ #ifndef __FRAMEWORK_THREADHELP_THREADHELPBASE_HXX_ #include <threadhelp/threadhelpbase.hxx> #endif #ifndef __FRAMEWORK_MACROS_GENERIC_HXX_ #include <macros/generic.hxx> #endif #ifndef __FRAMEWORK_MACROS_XINTERFACE_HXX_ #include <macros/xinterface.hxx> #endif #ifndef __FRAMEWORK_MACROS_XTYPEPROVIDER_HXX_ #include <macros/xtypeprovider.hxx> #endif #ifndef __FRAMEWORK_STDTYPES_H_ #include <stdtypes.h> #endif //_________________________________________________________________________________________________________________ // interface includes //_________________________________________________________________________________________________________________ #ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_ #include <com/sun/star/frame/XFrame.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_XSTATUSLISTENER_HPP_ #include <com/sun/star/frame/XStatusListener.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_ #include <com/sun/star/lang/XComponent.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XINDEXACCESS_HPP_ #include <com/sun/star/container/XIndexAccess.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_ #include <com/sun/star/container/XNameAccess.hpp> #endif #ifndef _DRAFTS_COM_SUN_STAR_FRAME_XMODULEMANAGER_HPP_ #include <drafts/com/sun/star/frame/XModuleManager.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef _DRAFTS_COM_SUN_STAR_FRAME_XUICONTROLLERREGISTRATION_HPP_ #include <drafts/com/sun/star/frame/XUIControllerRegistration.hpp> #endif #ifndef _DRAFTS_COM_SUN_STAR_UI_XIMAGEMANAGER_HPP_ #include <drafts/com/sun/star/ui/XImageManager.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_XSTATUSLISTENER_HPP_ #include <com/sun/star/frame/XStatusListener.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_XSUBTOOLBARCONTROLLER_HPP_ #include <com/sun/star/frame/XSubToolbarController.hpp> #endif //_________________________________________________________________________________________________________________ // other includes //_________________________________________________________________________________________________________________ #ifndef _RTL_USTRING_ #include <rtl/ustring.hxx> #endif #ifndef _CPPUHELPER_WEAK_HXX_ #include <cppuhelper/weak.hxx> #endif #ifndef _CPPUHELPER_INTERFACECONTAINER_HXX_ #include <cppuhelper/interfacecontainer.hxx> #endif #include <vcl/toolbox.hxx> namespace framework { class ToolBar; class ToolBarManager : public ::com::sun::star::frame::XFrameActionListener , public ::com::sun::star::frame::XStatusListener , public ::com::sun::star::lang::XComponent , public ::com::sun::star::lang::XTypeProvider , public ::drafts::com::sun::star::ui::XUIConfigurationListener, public ThreadHelpBase , public ::cppu::OWeakObject { public: ToolBarManager( const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >& rServicveManager, const com::sun::star::uno::Reference< com::sun::star::frame::XFrame >& rFrame, const rtl::OUString& rResourceName, ToolBar* pToolBar ); virtual ~ToolBarManager(); // XInterface, XTypeProvider, XServiceInfo DECLARE_XINTERFACE DECLARE_XTYPEPROVIDER ToolBox* GetToolBar() const; // XFrameActionListener virtual void SAL_CALL frameAction( const com::sun::star::frame::FrameActionEvent& Action ) throw ( ::com::sun::star::uno::RuntimeException ); // XStatusListener virtual void SAL_CALL statusChanged( const ::com::sun::star::frame::FeatureStateEvent& Event ) throw ( ::com::sun::star::uno::RuntimeException ); // XEventListener virtual void SAL_CALL disposing( const com::sun::star::lang::EventObject& Source ) throw ( ::com::sun::star::uno::RuntimeException ); // XUIConfigurationListener virtual void SAL_CALL elementInserted( const ::drafts::com::sun::star::ui::ConfigurationEvent& Event ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL elementRemoved( const ::drafts::com::sun::star::ui::ConfigurationEvent& Event ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL elementReplaced( const ::drafts::com::sun::star::ui::ConfigurationEvent& Event ) throw (::com::sun::star::uno::RuntimeException); // XComponent void SAL_CALL dispose() throw ( ::com::sun::star::uno::RuntimeException ); void SAL_CALL addEventListener( const com::sun::star::uno::Reference< XEventListener >& xListener ) throw( com::sun::star::uno::RuntimeException ); void SAL_CALL removeEventListener( const com::sun::star::uno::Reference< XEventListener >& xListener ) throw( com::sun::star::uno::RuntimeException ); void CheckAndUpdateImages(); void RefreshImages(); void FillToolbar( const ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexAccess >& rToolBarData ); void notifyRegisteredControllers( const rtl::OUString& aUIElementName, const rtl::OUString& aCommand ); static sal_Int16 GetCurrentSymbolSize(); protected: struct ControllerParams { sal_Int16 nWidth; }; typedef std::vector< ControllerParams > ControllerParamsVector; DECL_LINK( Click, ToolBox * ); DECL_LINK( DropdownClick, ToolBox * ); DECL_LINK( DoubleClick, ToolBox * ); DECL_LINK( Select, ToolBox * ); DECL_LINK( Highlight, ToolBox * ); DECL_LINK( Activate, ToolBox * ); DECL_LINK( Deactivate, ToolBox * ); DECL_LINK( StateChanged, StateChangedType* ); DECL_LINK( DataChanged, DataChangedEvent* ); DECL_LINK( MenuButton, ToolBox * ); DECL_LINK( MenuSelect, Menu * ); DECL_LINK( MenuDeactivate, Menu * ); DECL_LINK( AsyncUpdateControllersHdl, Timer * ); void RemoveControllers(); rtl::OUString RetrieveLabelFromCommand( const rtl::OUString& aCmdURL ); void CreateControllers( const ControllerParamsVector& ); void UpdateControllers(); void AddFrameActionListener(); void AddImageOrientationListener(); void UpdateImageOrientation(); void ImplClearPopupMenu( ToolBox *pToolBar ); void RequestImages(); protected: struct CommandInfo { CommandInfo() : nId( 0 ), nImageInfo( 0 ), bMirrored( false ), bRotated( false ) {} USHORT nId; std::vector<USHORT> aIds; sal_Int16 nImageInfo; sal_Bool bMirrored : 1, bRotated : 1; }; typedef std::vector< ::com::sun::star::uno::Reference< com::sun::star::frame::XStatusListener > > ToolBarControllerVector; typedef ::std::vector< ::com::sun::star::uno::Reference< ::com::sun::star::frame::XSubToolbarController > > SubToolBarControllerVector; typedef BaseHash< CommandInfo > CommandToInfoMap; typedef BaseHash< SubToolBarControllerVector > SubToolBarToSubToolBarControllerMap; sal_Bool m_bDisposed : 1, m_bIsHiContrast : 1, m_bSmallSymbols : 1, m_bModuleIdentified : 1, m_bAddedToTaskPaneList : 1, m_bVerticalTextEnabled : 1, m_bFrameActionRegistered : 1, m_bUpdateControllers : 1; sal_Bool m_bImageOrientationRegistered : 1, m_bImageMirrored : 1, m_bCanBeCustomized : 1; long m_lImageRotation; ToolBar* m_pToolBar; rtl::OUString m_aModuleIdentifier; rtl::OUString m_aResourceName; com::sun::star::uno::Reference< com::sun::star::frame::XFrame > m_xFrame; com::sun::star::uno::Reference< com::sun::star::container::XNameAccess > m_xUICommandLabels; ToolBarControllerVector m_aControllerVector; ::cppu::OMultiTypeInterfaceContainerHelper m_aListenerContainer; /// container for ALL Listener ::com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory > m_xServiceManager; ::com::sun::star::uno::Reference< ::drafts::com::sun::star::frame::XUIControllerRegistration > m_xToolbarControllerRegistration; ::com::sun::star::uno::Reference< ::drafts::com::sun::star::ui::XImageManager > m_xModuleImageManager; ::com::sun::star::uno::Reference< ::drafts::com::sun::star::ui::XImageManager > m_xDocImageManager; ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent > m_xImageOrientationListener; CommandToInfoMap m_aCommandMap; SubToolBarToSubToolBarControllerMap m_aSubToolBarControllerMap; Timer m_aAsyncUpdateControllersTimer; }; } #endif // __FRAMEWORK_UIELEMENT_TOOLBARMANAGER_HXX_ <|endoftext|>
<commit_before>/** * Clever programming language * Copyright (c) Clever Team * * This file is distributed under the MIT license. See LICENSE for details. */ #ifdef CLEVER_WIN32 # include <direct.h> # include <windows.h> #else # include <dirent.h> # include <unistd.h> # include <sys/resource.h> # include <sys/time.h> #endif #include "core/clever.h" #include "core/value.h" #include "modules/std/events/events.h" #include "types/type.h" #include "core/vm.h" namespace clever { namespace modules { namespace std { CLEVER_THREAD_FUNC(_events_handler) { EventData* intern = static_cast<EventData*>(arg); while (true) { intern->mutex.lock(); while (!intern->m_event_queue.empty()) { Signal u = intern->m_event_queue.front(); intern->m_event_queue.pop(); Actions& a = intern->m_event_map[u.first]; for (Actions::iterator it = a.begin(); it != a.end(); ++it) { intern->m_vm->runFunction(*it, &u.second)->delRef(); } if (u.first == "exit") { intern->mutex.unlock(); return NULL; } } intern->mutex.unlock(); #ifdef CLEVER_WIN32 SleepEx(intern->m_sleep_time, false); #else usleep(intern->m_sleep_time * 1000); #endif } return NULL; } TypeObject* Events::allocData(CLEVER_TYPE_CTOR_ARGS) const { EventData* intern = new EventData; if (args->size() > 0) { intern->m_sleep_time = static_cast<int>(args->at(0)->getInt()); } else { intern->m_sleep_time = 500; } intern->handler.create(_events_handler, intern); return intern; } EventData::~EventData() { if (handler.isRunning()) { mutex.lock(); Signal s; s.first = "exit"; m_event_queue.push(s); mutex.unlock(); handler.wait(); } if (m_vm) { delete m_vm; m_vm = 0; } } // Events.new([Int sleep_time]) // Constructs a new Events handler object to manage some events CLEVER_METHOD(Events::ctor) { if (!clever_check_args("|i")) { return; } EventData* intern = static_cast<EventData*>(allocData(&args)); intern->m_vm = new VM(); intern->m_vm->copy(vm, true); intern->m_vm->setChild(); result->setObj(this, intern); } // Events.connect(String name, Function func) CLEVER_METHOD(Events::connect) { if (!clever_check_args("sf")) { return; } EventData* intern = CLEVER_GET_OBJECT(EventData*, CLEVER_THIS()); intern->m_event_map[*args.at(0)->getStr()] .push_back(static_cast<Function*>(args.at(1)->getObj())); } // Events.emit(String name, ...) CLEVER_METHOD(Events::emit) { if (!clever_check_args("s*")) { return; } EventData* intern = CLEVER_GET_OBJECT(EventData*, CLEVER_THIS()); intern->mutex.lock(); Signal s; s.first = *args.at(0)->getStr(); for (size_t i = 1, j = args.size(); i < j; ++i) { s.second.push_back(args.at(i)); } intern->m_event_queue.push(s); intern->mutex.unlock(); } // Events.wait() CLEVER_METHOD(Events::wait) { if (!clever_check_no_args()) { return; } EventData* intern = CLEVER_GET_OBJECT(EventData*, CLEVER_THIS()); intern->handler.wait(); } // Events.finalize() CLEVER_METHOD(Events::finalize) { if (!clever_check_no_args()) { return; } EventData* intern = CLEVER_GET_OBJECT(EventData*, CLEVER_THIS()); intern->mutex.lock(); Signal s; s.first = "exit"; intern->m_event_queue.push(s); intern->mutex.unlock(); intern->handler.wait(); } // Events type initialization CLEVER_TYPE_INIT(Events::init) { setConstructor((MethodPtr)&Events::ctor); addMethod(new Function("connect", (MethodPtr)&Events::connect)); addMethod(new Function("emit", (MethodPtr)&Events::emit)); addMethod(new Function("wait", (MethodPtr)&Events::wait)); addMethod(new Function("finalize", (MethodPtr)&Events::finalize)); } // FFI module initialization CLEVER_MODULE_INIT(EventsModule) { addType(new Events); } }}} // clever::modules::std <commit_msg>- Cosmetics<commit_after>/** * Clever programming language * Copyright (c) Clever Team * * This file is distributed under the MIT license. See LICENSE for details. */ #ifdef CLEVER_WIN32 # include <direct.h> # include <windows.h> #else # include <dirent.h> # include <unistd.h> # include <sys/resource.h> # include <sys/time.h> #endif #include "core/clever.h" #include "core/value.h" #include "modules/std/events/events.h" #include "types/type.h" #include "core/vm.h" namespace clever { namespace modules { namespace std { CLEVER_THREAD_FUNC(_events_handler) { EventData* intern = static_cast<EventData*>(arg); while (true) { intern->mutex.lock(); while (!intern->m_event_queue.empty()) { Signal u = intern->m_event_queue.front(); intern->m_event_queue.pop(); Actions& a = intern->m_event_map[u.first]; for (Actions::iterator it = a.begin(); it != a.end(); ++it) { intern->m_vm->runFunction(*it, &u.second)->delRef(); } if (u.first == "exit") { intern->mutex.unlock(); return NULL; } } intern->mutex.unlock(); #ifdef CLEVER_WIN32 SleepEx(intern->m_sleep_time, false); #else usleep(intern->m_sleep_time * 1000); #endif } return NULL; } TypeObject* Events::allocData(CLEVER_TYPE_CTOR_ARGS) const { EventData* intern = new EventData; if (args->size() > 0) { intern->m_sleep_time = static_cast<int>(args->at(0)->getInt()); } else { intern->m_sleep_time = 500; } intern->handler.create(_events_handler, intern); return intern; } EventData::~EventData() { if (handler.isRunning()) { mutex.lock(); Signal s; s.first = "exit"; m_event_queue.push(s); mutex.unlock(); handler.wait(); } if (m_vm) { delete m_vm; m_vm = 0; } } // Events.new([Int sleep_time]) // Constructs a new Events handler object to manage some events CLEVER_METHOD(Events::ctor) { if (!clever_check_args("|i")) { return; } EventData* intern = static_cast<EventData*>(allocData(&args)); intern->m_vm = new VM(); intern->m_vm->copy(vm, true); intern->m_vm->setChild(); result->setObj(this, intern); } // Events.connect(String name, Function func) CLEVER_METHOD(Events::connect) { if (!clever_check_args("sf")) { return; } EventData* intern = CLEVER_GET_OBJECT(EventData*, CLEVER_THIS()); intern->m_event_map[*args.at(0)->getStr()] .push_back(static_cast<Function*>(args.at(1)->getObj())); } // Events.emit(String name, ...) CLEVER_METHOD(Events::emit) { if (!clever_check_args("s*")) { return; } EventData* intern = CLEVER_GET_OBJECT(EventData*, CLEVER_THIS()); intern->mutex.lock(); Signal s; s.first = *args.at(0)->getStr(); for (size_t i = 1, j = args.size(); i < j; ++i) { s.second.push_back(args.at(i)); } intern->m_event_queue.push(s); intern->mutex.unlock(); } // Events.wait() CLEVER_METHOD(Events::wait) { if (!clever_check_no_args()) { return; } EventData* intern = CLEVER_GET_OBJECT(EventData*, CLEVER_THIS()); intern->handler.wait(); } // Events.finalize() CLEVER_METHOD(Events::finalize) { if (!clever_check_no_args()) { return; } EventData* intern = CLEVER_GET_OBJECT(EventData*, CLEVER_THIS()); intern->mutex.lock(); Signal s; s.first = "exit"; intern->m_event_queue.push(s); intern->mutex.unlock(); intern->handler.wait(); } // Events type initialization CLEVER_TYPE_INIT(Events::init) { setConstructor((MethodPtr)&Events::ctor); addMethod(new Function("connect", (MethodPtr)&Events::connect)); addMethod(new Function("emit", (MethodPtr)&Events::emit)); addMethod(new Function("wait", (MethodPtr)&Events::wait)); addMethod(new Function("finalize", (MethodPtr)&Events::finalize)); } // FFI module initialization CLEVER_MODULE_INIT(EventsModule) { addType(new Events); } }}} // clever::modules::std <|endoftext|>
<commit_before>#ifndef __FRAMEWORK_XML_TOOLBOXCONFIGURATION_HXX_ #define __FRAMEWORK_XML_TOOLBOXCONFIGURATION_HXX_ #ifndef _SVARRAY_HXX #include <svtools/svarray.hxx> #endif #ifndef _SV_BITMAP_HXX #include <vcl/bitmap.hxx> #endif #ifndef _STRING_HXX #include <tools/string.hxx> #endif #ifndef _COM_SUN_STAR_IO_XINPUTSTREAM_HPP_ #include <com/sun/star/io/XInputStream.hpp> #endif #ifndef _COM_SUN_STAR_IO_XOUPUTSTREAM_HPP_ #include <com/sun/star/io/XOutputStream.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XINDEXCONTAINER_HPP_ #include <com/sun/star/container/XIndexContainer.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XINDEXACCESS_HPP_ #include <com/sun/star/container/XIndexAccess.hpp> #endif // #110897# #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif namespace framework { class ToolBoxConfiguration { public: // #110897# static sal_Bool LoadToolBox( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceFactory, const ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >& rInputStream, const ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexContainer >& rToolbarConfiguration ); // #110897# static sal_Bool StoreToolBox( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceFactory, const ::com::sun::star::uno::Reference< ::com::sun::star::io::XOutputStream >& rOutputStream, const ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexAccess >& rToolbarConfiguration ); }; } // namespace framework #endif // __FRAMEWORK_XML_TOOLBOXCONFIGURATION_HXX_ <commit_msg>INTEGRATION: CWS changefileheader (1.4.738); FILE MERGED 2008/04/01 15:18:32 thb 1.4.738.2: #i85898# Stripping all external header guards 2008/04/01 10:58:00 thb 1.4.738.1: #i85898# Stripping all external header guards<commit_after>#ifndef __FRAMEWORK_XML_TOOLBOXCONFIGURATION_HXX_ #define __FRAMEWORK_XML_TOOLBOXCONFIGURATION_HXX_ #include <svtools/svarray.hxx> #include <vcl/bitmap.hxx> #include <tools/string.hxx> #include <com/sun/star/io/XInputStream.hpp> #ifndef _COM_SUN_STAR_IO_XOUPUTSTREAM_HPP_ #include <com/sun/star/io/XOutputStream.hpp> #endif #include <com/sun/star/container/XIndexContainer.hpp> #include <com/sun/star/container/XIndexAccess.hpp> // #110897# #include <com/sun/star/lang/XMultiServiceFactory.hpp> namespace framework { class ToolBoxConfiguration { public: // #110897# static sal_Bool LoadToolBox( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceFactory, const ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >& rInputStream, const ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexContainer >& rToolbarConfiguration ); // #110897# static sal_Bool StoreToolBox( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceFactory, const ::com::sun::star::uno::Reference< ::com::sun::star::io::XOutputStream >& rOutputStream, const ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexAccess >& rToolbarConfiguration ); }; } // namespace framework #endif // __FRAMEWORK_XML_TOOLBOXCONFIGURATION_HXX_ <|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 <helper/titlebarupdate.hxx> #include <pattern/window.hxx> #include <macros/generic.hxx> #include <services.h> #include <properties.h> #include <com/sun/star/awt/XWindow.hpp> #include <com/sun/star/lang/XServiceInfo.hpp> #include <com/sun/star/lang/IllegalArgumentException.hpp> #include <com/sun/star/frame/ModuleManager.hpp> #include <com/sun/star/container/XNameAccess.hpp> #include <com/sun/star/beans/XPropertySet.hpp> #include <com/sun/star/beans/XMaterialHolder.hpp> #include <com/sun/star/frame/XTitleChangeBroadcaster.hpp> #include <com/sun/star/beans/NamedValue.hpp> #include <comphelper/processfactory.hxx> #include <comphelper/sequenceashashmap.hxx> #include <unotools/configmgr.hxx> #include <unotools/bootstrap.hxx> #include <vcl/window.hxx> #include <vcl/syswin.hxx> #include <toolkit/helper/vclunohelper.hxx> #include <vcl/svapp.hxx> #include <vcl/wrkwin.hxx> #include <tools/diagnose_ex.h> namespace framework{ static const ::sal_Int32 INVALID_ICON_ID = -1; static const ::sal_Int32 DEFAULT_ICON_ID = 0; TitleBarUpdate::TitleBarUpdate(const css::uno::Reference< css::uno::XComponentContext >& xContext) : m_xContext (xContext ) , m_xFrame ( ) { } TitleBarUpdate::~TitleBarUpdate() { } void SAL_CALL TitleBarUpdate::initialize(const css::uno::Sequence< css::uno::Any >& lArguments) throw(css::uno::Exception , css::uno::RuntimeException, std::exception) { // check arguments css::uno::Reference< css::frame::XFrame > xFrame; if (lArguments.getLength() < 1) throw css::lang::IllegalArgumentException( "Empty argument list!", static_cast< ::cppu::OWeakObject* >(this), 1); lArguments[0] >>= xFrame; if (!xFrame.is()) throw css::lang::IllegalArgumentException( "No valid frame specified!", static_cast< ::cppu::OWeakObject* >(this), 1); { SolarMutexGuard g; // hold the frame as weak reference(!) so it can die everytimes :-) m_xFrame = xFrame; } // start listening xFrame->addFrameActionListener(this); css::uno::Reference< css::frame::XTitleChangeBroadcaster > xBroadcaster(xFrame, css::uno::UNO_QUERY); if (xBroadcaster.is ()) xBroadcaster->addTitleChangeListener (this); } void SAL_CALL TitleBarUpdate::frameAction(const css::frame::FrameActionEvent& aEvent) throw(css::uno::RuntimeException, std::exception) { // we are interested on events only, which must trigger a title bar update // because component was changed. if ( (aEvent.Action == css::frame::FrameAction_COMPONENT_ATTACHED ) || (aEvent.Action == css::frame::FrameAction_COMPONENT_REATTACHED) || (aEvent.Action == css::frame::FrameAction_COMPONENT_DETACHING ) ) { impl_forceUpdate (); } } void SAL_CALL TitleBarUpdate::titleChanged(const css::frame::TitleChangedEvent& /* aEvent */) throw (css::uno::RuntimeException, std::exception) { impl_forceUpdate (); } void SAL_CALL TitleBarUpdate::disposing(const css::lang::EventObject&) throw(css::uno::RuntimeException, std::exception) { // nothing todo here - because we hold the frame as weak reference only } //http://live.gnome.org/GnomeShell/ApplicationBased //See http://msdn.microsoft.com/en-us/library/dd378459(v=VS.85).aspx for future //Windows 7 equivalent support void TitleBarUpdate::impl_updateApplicationID(const css::uno::Reference< css::frame::XFrame >& xFrame) { css::uno::Reference< css::awt::XWindow > xWindow = xFrame->getContainerWindow (); if ( ! xWindow.is() ) return; OUString sApplicationID; #if !defined(MACOSX) try { css::uno::Reference< css::frame::XModuleManager2 > xModuleManager = css::frame::ModuleManager::create( m_xContext ); OUString sDesktopName; OUString aModuleId = xModuleManager->identify(xFrame); if ( aModuleId == "com.sun.star.text.TextDocument" || aModuleId == "com.sun.star.text.GlobalDocument" || aModuleId == "com.sun.star.text.WebDocument" || aModuleId == "com.sun.star.xforms.XMLFormDocument" ) sDesktopName = "Writer"; else if ( aModuleId == "com.sun.star.sheet.SpreadsheetDocument" ) sDesktopName = "Calc"; else if ( aModuleId == "com.sun.star.presentation.PresentationDocument" ) sDesktopName = "Impress"; else if ( aModuleId == "com.sun.star.drawing.DrawingDocument" ) sDesktopName = "Draw"; else if ( aModuleId == "com.sun.star.formula.FormulaProperties" ) sDesktopName = "Math"; else if ( aModuleId == "com.sun.star.sdb.DatabaseDocument" || aModuleId == "com.sun.star.sdb.OfficeDatabaseDocument" || aModuleId == "com.sun.star.sdb.RelationDesign" || aModuleId == "com.sun.star.sdb.QueryDesign" || aModuleId == "com.sun.star.sdb.TableDesign" || aModuleId == "com.sun.star.sdb.DataSourceBrowser" ) sDesktopName = "Base"; else sDesktopName = "Startcenter"; #if defined(WNT) // We use a hardcoded product name matching the registry keys so applications can be associated with file types sApplicationID = "TheDocumentFoundation.LibreOffice."; sApplicationID += sDesktopName; #else sApplicationID = utl::ConfigManager::getProductName().toAsciiLowerCase(); sApplicationID += "-"; sApplicationID += sDesktopName.toAsciiLowerCase(); #endif } catch(const css::uno::Exception&) { } #endif // VCL SYNCHRONIZED -> SolarMutexGuard aSolarGuard; vcl::Window* pWindow = (VCLUnoHelper::GetWindow( xWindow )); if ( ( pWindow ) && ( pWindow->GetType() == WINDOW_WORKWINDOW ) ) { WorkWindow* pWorkWindow = static_cast<WorkWindow*>(pWindow); pWorkWindow->SetApplicationID( sApplicationID ); } // <- VCL SYNCHRONIZED } bool TitleBarUpdate::implst_getModuleInfo(const css::uno::Reference< css::frame::XFrame >& xFrame, TModuleInfo& rInfo ) { if ( ! xFrame.is ()) return false; try { css::uno::Reference< css::frame::XModuleManager2 > xModuleManager = css::frame::ModuleManager::create( m_xContext ); rInfo.sID = xModuleManager->identify(xFrame); ::comphelper::SequenceAsHashMap lProps = xModuleManager->getByName (rInfo.sID); rInfo.sUIName = lProps.getUnpackedValueOrDefault (OFFICEFACTORY_PROPNAME_UINAME, OUString()); rInfo.nIcon = lProps.getUnpackedValueOrDefault (OFFICEFACTORY_PROPNAME_ICON , INVALID_ICON_ID ); // Note: If we could retrieve a module id ... everything is OK. // UIName and Icon ID are optional values ! bool bSuccess = !rInfo.sID.isEmpty(); return bSuccess; } catch(const css::uno::Exception&) {} return false; } void TitleBarUpdate::impl_forceUpdate() { css::uno::Reference< css::frame::XFrame > xFrame; { SolarMutexGuard g; xFrame.set(m_xFrame.get(), css::uno::UNO_QUERY); } // frame already gone ? We hold it weak only ... if ( ! xFrame.is()) return; // no window -> no chance to set/update title and icon css::uno::Reference< css::awt::XWindow > xWindow = xFrame->getContainerWindow(); if ( ! xWindow.is()) return; impl_updateIcon (xFrame); impl_updateTitle (xFrame); #if !defined(MACOSX) impl_updateApplicationID (xFrame); #endif } void TitleBarUpdate::impl_updateIcon(const css::uno::Reference< css::frame::XFrame >& xFrame) { css::uno::Reference< css::frame::XController > xController = xFrame->getController (); css::uno::Reference< css::awt::XWindow > xWindow = xFrame->getContainerWindow (); if ( ( ! xController.is() ) || ( ! xWindow.is() ) ) return; // a) set default value to an invalid one. So we can start further searches for right icon id, if // first steps failed! sal_Int32 nIcon = INVALID_ICON_ID; // b) try to find information on controller property set directly // Don't forget to catch possible exceptions - because these property is an optional one! css::uno::Reference< css::beans::XPropertySet > xSet( xController, css::uno::UNO_QUERY ); if ( xSet.is() ) { try { css::uno::Reference< css::beans::XPropertySetInfo > const xPSI( xSet->getPropertySetInfo(), css::uno::UNO_SET_THROW ); if ( xPSI->hasPropertyByName( "IconId" ) ) xSet->getPropertyValue( "IconId" ) >>= nIcon; } catch(const css::uno::Exception&) { DBG_UNHANDLED_EXCEPTION(); } } // c) if b) failed ... identify the used module and retrieve set icon from module config. // Tirck :-) Module was already specified outside and aInfo contains all needed information. if ( nIcon == INVALID_ICON_ID ) { TModuleInfo aInfo; if (implst_getModuleInfo(xFrame, aInfo)) nIcon = aInfo.nIcon; } // d) if all steps failed - use fallback :-) // ... means using the global staroffice icon if( nIcon == INVALID_ICON_ID ) nIcon = DEFAULT_ICON_ID; // e) set icon on container window now // Don't forget SolarMutex! We use vcl directly :-( // Check window pointer for right WorkWindow class too!!! // VCL SYNCHRONIZED -> SolarMutexGuard aSolarGuard; vcl::Window* pWindow = (VCLUnoHelper::GetWindow( xWindow )); if ( ( pWindow ) && ( pWindow->GetType() == WINDOW_WORKWINDOW ) ) { WorkWindow* pWorkWindow = static_cast<WorkWindow*>(pWindow); pWorkWindow->SetIcon( (sal_uInt16)nIcon ); css::uno::Reference< css::frame::XModel > xModel = xController->getModel(); OUString aURL; if( xModel.is() ) aURL = xModel->getURL(); pWorkWindow->SetRepresentedURL( aURL ); } // <- VCL SYNCHRONIZED } void TitleBarUpdate::impl_updateTitle(const css::uno::Reference< css::frame::XFrame >& xFrame) { // no window ... no chance to set any title -> return css::uno::Reference< css::awt::XWindow > xWindow = xFrame->getContainerWindow (); if ( ! xWindow.is() ) return; css::uno::Reference< css::frame::XTitle > xTitle(xFrame, css::uno::UNO_QUERY); if ( ! xTitle.is() ) return; const OUString sTitle = xTitle->getTitle (); // VCL SYNCHRONIZED -> SolarMutexGuard aSolarGuard; vcl::Window* pWindow = (VCLUnoHelper::GetWindow( xWindow )); if ( ( pWindow ) && ( pWindow->GetType() == WINDOW_WORKWINDOW ) ) { WorkWindow* pWorkWindow = static_cast<WorkWindow*>(pWindow); pWorkWindow->SetText( sTitle ); } // <- VCL SYNCHRONIZED } } // namespace framework /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>Resolves: rhbz#1204244 group sdb windows together as 'base'<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 <helper/titlebarupdate.hxx> #include <pattern/window.hxx> #include <macros/generic.hxx> #include <services.h> #include <properties.h> #include <com/sun/star/awt/XWindow.hpp> #include <com/sun/star/lang/XServiceInfo.hpp> #include <com/sun/star/lang/IllegalArgumentException.hpp> #include <com/sun/star/frame/ModuleManager.hpp> #include <com/sun/star/container/XNameAccess.hpp> #include <com/sun/star/beans/XPropertySet.hpp> #include <com/sun/star/beans/XMaterialHolder.hpp> #include <com/sun/star/frame/XTitleChangeBroadcaster.hpp> #include <com/sun/star/beans/NamedValue.hpp> #include <comphelper/processfactory.hxx> #include <comphelper/sequenceashashmap.hxx> #include <unotools/configmgr.hxx> #include <unotools/bootstrap.hxx> #include <vcl/window.hxx> #include <vcl/syswin.hxx> #include <toolkit/helper/vclunohelper.hxx> #include <vcl/svapp.hxx> #include <vcl/wrkwin.hxx> #include <tools/diagnose_ex.h> namespace framework{ static const ::sal_Int32 INVALID_ICON_ID = -1; static const ::sal_Int32 DEFAULT_ICON_ID = 0; TitleBarUpdate::TitleBarUpdate(const css::uno::Reference< css::uno::XComponentContext >& xContext) : m_xContext (xContext ) , m_xFrame ( ) { } TitleBarUpdate::~TitleBarUpdate() { } void SAL_CALL TitleBarUpdate::initialize(const css::uno::Sequence< css::uno::Any >& lArguments) throw(css::uno::Exception , css::uno::RuntimeException, std::exception) { // check arguments css::uno::Reference< css::frame::XFrame > xFrame; if (lArguments.getLength() < 1) throw css::lang::IllegalArgumentException( "Empty argument list!", static_cast< ::cppu::OWeakObject* >(this), 1); lArguments[0] >>= xFrame; if (!xFrame.is()) throw css::lang::IllegalArgumentException( "No valid frame specified!", static_cast< ::cppu::OWeakObject* >(this), 1); { SolarMutexGuard g; // hold the frame as weak reference(!) so it can die everytimes :-) m_xFrame = xFrame; } // start listening xFrame->addFrameActionListener(this); css::uno::Reference< css::frame::XTitleChangeBroadcaster > xBroadcaster(xFrame, css::uno::UNO_QUERY); if (xBroadcaster.is ()) xBroadcaster->addTitleChangeListener (this); } void SAL_CALL TitleBarUpdate::frameAction(const css::frame::FrameActionEvent& aEvent) throw(css::uno::RuntimeException, std::exception) { // we are interested on events only, which must trigger a title bar update // because component was changed. if ( (aEvent.Action == css::frame::FrameAction_COMPONENT_ATTACHED ) || (aEvent.Action == css::frame::FrameAction_COMPONENT_REATTACHED) || (aEvent.Action == css::frame::FrameAction_COMPONENT_DETACHING ) ) { impl_forceUpdate (); } } void SAL_CALL TitleBarUpdate::titleChanged(const css::frame::TitleChangedEvent& /* aEvent */) throw (css::uno::RuntimeException, std::exception) { impl_forceUpdate (); } void SAL_CALL TitleBarUpdate::disposing(const css::lang::EventObject&) throw(css::uno::RuntimeException, std::exception) { // nothing todo here - because we hold the frame as weak reference only } //http://live.gnome.org/GnomeShell/ApplicationBased //See http://msdn.microsoft.com/en-us/library/dd378459(v=VS.85).aspx for future //Windows 7 equivalent support void TitleBarUpdate::impl_updateApplicationID(const css::uno::Reference< css::frame::XFrame >& xFrame) { css::uno::Reference< css::awt::XWindow > xWindow = xFrame->getContainerWindow (); if ( ! xWindow.is() ) return; OUString sApplicationID; #if !defined(MACOSX) try { css::uno::Reference< css::frame::XModuleManager2 > xModuleManager = css::frame::ModuleManager::create( m_xContext ); OUString sDesktopName; OUString aModuleId = xModuleManager->identify(xFrame); if ( aModuleId.startsWith("com.sun.star.text.") || aModuleId.startsWith("com.sun.star.xforms.") ) sDesktopName = "Writer"; else if ( aModuleId.startsWith("com.sun.star.sheet.") ) sDesktopName = "Calc"; else if ( aModuleId.startsWith("com.sun.star.presentation.") ) sDesktopName = "Impress"; else if ( aModuleId.startsWith("com.sun.star.drawing." ) ) sDesktopName = "Draw"; else if ( aModuleId.startsWith("com.sun.star.formula." ) ) sDesktopName = "Math"; else if ( aModuleId.startsWith("com.sun.star.sdb.") ) sDesktopName = "Base"; else sDesktopName = "Startcenter"; #if defined(WNT) // We use a hardcoded product name matching the registry keys so applications can be associated with file types sApplicationID = "TheDocumentFoundation.LibreOffice."; sApplicationID += sDesktopName; #else sApplicationID = utl::ConfigManager::getProductName().toAsciiLowerCase(); sApplicationID += "-"; sApplicationID += sDesktopName.toAsciiLowerCase(); #endif } catch(const css::uno::Exception&) { } #endif // VCL SYNCHRONIZED -> SolarMutexGuard aSolarGuard; vcl::Window* pWindow = (VCLUnoHelper::GetWindow( xWindow )); if ( ( pWindow ) && ( pWindow->GetType() == WINDOW_WORKWINDOW ) ) { WorkWindow* pWorkWindow = static_cast<WorkWindow*>(pWindow); pWorkWindow->SetApplicationID( sApplicationID ); } // <- VCL SYNCHRONIZED } bool TitleBarUpdate::implst_getModuleInfo(const css::uno::Reference< css::frame::XFrame >& xFrame, TModuleInfo& rInfo ) { if ( ! xFrame.is ()) return false; try { css::uno::Reference< css::frame::XModuleManager2 > xModuleManager = css::frame::ModuleManager::create( m_xContext ); rInfo.sID = xModuleManager->identify(xFrame); ::comphelper::SequenceAsHashMap lProps = xModuleManager->getByName (rInfo.sID); rInfo.sUIName = lProps.getUnpackedValueOrDefault (OFFICEFACTORY_PROPNAME_UINAME, OUString()); rInfo.nIcon = lProps.getUnpackedValueOrDefault (OFFICEFACTORY_PROPNAME_ICON , INVALID_ICON_ID ); // Note: If we could retrieve a module id ... everything is OK. // UIName and Icon ID are optional values ! bool bSuccess = !rInfo.sID.isEmpty(); return bSuccess; } catch(const css::uno::Exception&) {} return false; } void TitleBarUpdate::impl_forceUpdate() { css::uno::Reference< css::frame::XFrame > xFrame; { SolarMutexGuard g; xFrame.set(m_xFrame.get(), css::uno::UNO_QUERY); } // frame already gone ? We hold it weak only ... if ( ! xFrame.is()) return; // no window -> no chance to set/update title and icon css::uno::Reference< css::awt::XWindow > xWindow = xFrame->getContainerWindow(); if ( ! xWindow.is()) return; impl_updateIcon (xFrame); impl_updateTitle (xFrame); #if !defined(MACOSX) impl_updateApplicationID (xFrame); #endif } void TitleBarUpdate::impl_updateIcon(const css::uno::Reference< css::frame::XFrame >& xFrame) { css::uno::Reference< css::frame::XController > xController = xFrame->getController (); css::uno::Reference< css::awt::XWindow > xWindow = xFrame->getContainerWindow (); if ( ( ! xController.is() ) || ( ! xWindow.is() ) ) return; // a) set default value to an invalid one. So we can start further searches for right icon id, if // first steps failed! sal_Int32 nIcon = INVALID_ICON_ID; // b) try to find information on controller property set directly // Don't forget to catch possible exceptions - because these property is an optional one! css::uno::Reference< css::beans::XPropertySet > xSet( xController, css::uno::UNO_QUERY ); if ( xSet.is() ) { try { css::uno::Reference< css::beans::XPropertySetInfo > const xPSI( xSet->getPropertySetInfo(), css::uno::UNO_SET_THROW ); if ( xPSI->hasPropertyByName( "IconId" ) ) xSet->getPropertyValue( "IconId" ) >>= nIcon; } catch(const css::uno::Exception&) { DBG_UNHANDLED_EXCEPTION(); } } // c) if b) failed ... identify the used module and retrieve set icon from module config. // Tirck :-) Module was already specified outside and aInfo contains all needed information. if ( nIcon == INVALID_ICON_ID ) { TModuleInfo aInfo; if (implst_getModuleInfo(xFrame, aInfo)) nIcon = aInfo.nIcon; } // d) if all steps failed - use fallback :-) // ... means using the global staroffice icon if( nIcon == INVALID_ICON_ID ) nIcon = DEFAULT_ICON_ID; // e) set icon on container window now // Don't forget SolarMutex! We use vcl directly :-( // Check window pointer for right WorkWindow class too!!! // VCL SYNCHRONIZED -> SolarMutexGuard aSolarGuard; vcl::Window* pWindow = (VCLUnoHelper::GetWindow( xWindow )); if ( ( pWindow ) && ( pWindow->GetType() == WINDOW_WORKWINDOW ) ) { WorkWindow* pWorkWindow = static_cast<WorkWindow*>(pWindow); pWorkWindow->SetIcon( (sal_uInt16)nIcon ); css::uno::Reference< css::frame::XModel > xModel = xController->getModel(); OUString aURL; if( xModel.is() ) aURL = xModel->getURL(); pWorkWindow->SetRepresentedURL( aURL ); } // <- VCL SYNCHRONIZED } void TitleBarUpdate::impl_updateTitle(const css::uno::Reference< css::frame::XFrame >& xFrame) { // no window ... no chance to set any title -> return css::uno::Reference< css::awt::XWindow > xWindow = xFrame->getContainerWindow (); if ( ! xWindow.is() ) return; css::uno::Reference< css::frame::XTitle > xTitle(xFrame, css::uno::UNO_QUERY); if ( ! xTitle.is() ) return; const OUString sTitle = xTitle->getTitle (); // VCL SYNCHRONIZED -> SolarMutexGuard aSolarGuard; vcl::Window* pWindow = (VCLUnoHelper::GetWindow( xWindow )); if ( ( pWindow ) && ( pWindow->GetType() == WINDOW_WORKWINDOW ) ) { WorkWindow* pWorkWindow = static_cast<WorkWindow*>(pWindow); pWorkWindow->SetText( sTitle ); } // <- VCL SYNCHRONIZED } } // namespace framework /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: esdll.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2005-09-08 18:52:36 $ * * 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 STRICT #define _WIN32_WINNT 0x0400 #define _WIN32_DCOM #if defined(_MSC_VER) && (_MSC_VER >= 1300) #undef _DEBUG #endif #include <atlbase.h> CComModule _Module; #include <atlcom.h> BEGIN_OBJECT_MAP(ObjectMap) END_OBJECT_MAP() ///////////////////////////////////////////////////////////////////////////// // DLL Entry Point #include "syswinwrapper.hxx" #include "docholder.hxx" HINSTANCE DocumentHolder::m_hInstance; extern "C" BOOL WINAPI DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID /*lpReserved*/) { DocumentHolder::m_hInstance = hInstance; if (!winwrap::HatchWindowRegister(hInstance)) return FALSE; if (dwReason == DLL_PROCESS_ATTACH) { _Module.Init(ObjectMap, hInstance, NULL); DisableThreadLibraryCalls(hInstance); } else if (dwReason == DLL_PROCESS_DETACH) { _Module.Term(); } return TRUE; // ok } <commit_msg>INTEGRATION: CWS warnings01 (1.4.16); FILE MERGED 2006/02/20 15:31:44 cd 1.4.16.1: #i55991# Warning free code for Windows C++ compiler<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: esdll.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: hr $ $Date: 2006-06-20 05:40:26 $ * * 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 STRICT #define _WIN32_WINNT 0x0400 #define _WIN32_DCOM #if defined(_MSC_VER) && (_MSC_VER >= 1300) #undef _DEBUG #endif #include "stdafx.h" #include <atlbase.h> #pragma warning( push ) #pragma warning( disable: 4710 ) CComModule _Module; #pragma warning( pop ) #include <atlcom.h> BEGIN_OBJECT_MAP(ObjectMap) END_OBJECT_MAP() ///////////////////////////////////////////////////////////////////////////// // DLL Entry Point #include "syswinwrapper.hxx" #include "docholder.hxx" HINSTANCE DocumentHolder::m_hInstance; extern "C" BOOL WINAPI DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID /*lpReserved*/) { DocumentHolder::m_hInstance = hInstance; if (!winwrap::HatchWindowRegister(hInstance)) return FALSE; if (dwReason == DLL_PROCESS_ATTACH) { _Module.Init(ObjectMap, hInstance, NULL); DisableThreadLibraryCalls(hInstance); } else if (dwReason == DLL_PROCESS_DETACH) { _Module.Term(); } return TRUE; // ok } // Fix strange warnings about some // ATL::CAxHostWindow::QueryInterface|AddRef|Releae functions. // warning C4505: 'xxx' : unreferenced local function has been removed #if defined(_MSC_VER) #pragma warning(disable: 4505) #endif <|endoftext|>
<commit_before>/* * main.cpp (Tutorial04_Query) * * This file is part of the "LLGL" project (Copyright (c) 2015 by Lukas Hermanns) * See "LICENSE.txt" for license information. */ #include "../tutorial.h" class Tutorial04 : public Tutorial { LLGL::ShaderProgram* shaderProgram = nullptr; LLGL::GraphicsPipeline* occlusionPipeline = nullptr; LLGL::GraphicsPipeline* scenePipeline = nullptr; LLGL::VertexBuffer* vertexBuffer = nullptr; LLGL::IndexBuffer* indexBuffer = nullptr; LLGL::ConstantBuffer* constantBuffer = nullptr; LLGL::Query* occlusionQuery = nullptr; LLGL::Query* geometryQuery = nullptr; struct Settings { Gs::Matrix4f wvpMatrix; LLGL::ColorRGBAf color; } settings; public: Tutorial04() : Tutorial( "Direct3D11", L"LLGL Tutorial 04: Query") { // Create all graphics objects auto vertexFormat = CreateBuffers(); shaderProgram = LoadStandardShaderProgram(vertexFormat); CreatePipelines(); CreateQueries(); } LLGL::VertexFormat CreateBuffers() { // Specify vertex format LLGL::VertexFormat vertexFormat; vertexFormat.AddAttribute("position", LLGL::DataType::Float, 3); // Create vertex, index, and constant buffer vertexBuffer = CreateVertexBuffer(GenerateCubeVertices(), vertexFormat); indexBuffer = CreateIndexBuffer(GenerateCubeTriangelIndices(), LLGL::DataType::UInt32); constantBuffer = CreateConstantBuffer(settings); return vertexFormat; } void CreatePipelines() { // Create graphics pipeline for occlusion query LLGL::GraphicsPipelineDescriptor pipelineDesc; { pipelineDesc.shaderProgram = shaderProgram; pipelineDesc.depth.testEnabled = true; pipelineDesc.rasterizer.multiSampleEnabled = true; pipelineDesc.rasterizer.samples = 8; LLGL::BlendTargetDescriptor blendDesc; { blendDesc.colorMask = LLGL::ColorRGBAb(false); } pipelineDesc.blend.targets.push_back(blendDesc); } occlusionPipeline = renderer->CreateGraphicsPipeline(pipelineDesc); // Create graphics pipeline for scene rendering { pipelineDesc.depth.testEnabled = true; pipelineDesc.depth.writeEnabled = true; pipelineDesc.blend.targets[0].colorMask = LLGL::ColorRGBAb(true); } scenePipeline = renderer->CreateGraphicsPipeline(pipelineDesc); } void CreateQueries() { // Create query to determine if any samples passed the depth test (occlusion query) LLGL::QueryDescriptor queryDesc; { queryDesc.type = LLGL::QueryType::AnySamplesPassed; queryDesc.renderCondition = true; } occlusionQuery = renderer->CreateQuery(queryDesc); // Create query to determine number of primitives that are sent to the rasterizer { queryDesc.type = LLGL::QueryType::PrimitivesGenerated; queryDesc.renderCondition = false; } geometryQuery = renderer->CreateQuery(queryDesc); } std::uint64_t GetAndSyncQueryResult(LLGL::Query* query) { // Wait until query result is available and return result std::uint64_t result = 0; while (!context->QueryResult(*query, result)) { /* wait */ } return result; } void PrintQueryResult() { std::cout << "geometry visible: " << (GetAndSyncQueryResult(occlusionQuery) != 0 ? "yes" : "no") << ", primitives generated: " << GetAndSyncQueryResult(geometryQuery) << " \r"; std::flush(std::cout); } void SetBoxColor(const LLGL::ColorRGBAf& color) { settings.color = color; UpdateConstantBuffer(constantBuffer, settings); } private: void OnDrawFrame() override { // Update matrices in constant buffer static float anim; anim += 0.01f; settings.wvpMatrix = projection; Gs::RotateFree(settings.wvpMatrix, { 0, 1, 0 }, Gs::Deg2Rad(std::sin(anim)*55.0f)); Gs::Translate(settings.wvpMatrix, { 0, 0, 5 }); Gs::RotateFree(settings.wvpMatrix, Gs::Vector3f(1).Normalized(), anim*3); SetBoxColor({ 1, 1, 1 }); // Clear color and depth buffers context->ClearBuffers(LLGL::ClearBuffersFlags::Color | LLGL::ClearBuffersFlags::Depth); // Set buffers context->SetVertexBuffer(*vertexBuffer); context->SetIndexBuffer(*indexBuffer); context->SetConstantBuffer(*constantBuffer, 0); // Start with qeometry query context->BeginQuery(*geometryQuery); { // Draw box for occlusion query context->SetGraphicsPipeline(*occlusionPipeline); context->BeginQuery(*occlusionQuery); { context->DrawIndexed(36, 0); } context->EndQuery(*occlusionQuery); // Draw scene context->SetGraphicsPipeline(*scenePipeline); SetBoxColor({ 0, 1, 0 }); context->BeginRenderCondition(*occlusionQuery, LLGL::RenderConditionMode::Wait); { context->DrawIndexed(36, 0); } context->EndRenderCondition(); } context->EndQuery(*geometryQuery); PrintQueryResult(); // Present result on the screen context->Present(); } }; LLGL_IMPLEMENT_TUTORIAL(Tutorial04); <commit_msg>Added user input to Tutorial04.<commit_after>/* * main.cpp (Tutorial04_Query) * * This file is part of the "LLGL" project (Copyright (c) 2015 by Lukas Hermanns) * See "LICENSE.txt" for license information. */ #include "../tutorial.h" class Tutorial04 : public Tutorial { LLGL::ShaderProgram* shaderProgram = nullptr; LLGL::GraphicsPipeline* occlusionPipeline = nullptr; LLGL::GraphicsPipeline* scenePipeline = nullptr; LLGL::VertexBuffer* vertexBuffer = nullptr; LLGL::IndexBuffer* indexBuffer = nullptr; LLGL::ConstantBuffer* constantBuffer = nullptr; LLGL::Query* occlusionQuery = nullptr; LLGL::Query* geometryQuery = nullptr; bool occlusionCullingEnabled = true; struct Settings { Gs::Matrix4f wvpMatrix; LLGL::ColorRGBAf color; } settings; public: Tutorial04() : Tutorial( "Direct3D11", L"LLGL Tutorial 04: Query") { // Create all graphics objects auto vertexFormat = CreateBuffers(); shaderProgram = LoadStandardShaderProgram(vertexFormat); CreatePipelines(); CreateQueries(); // Print some information std::cout << "press TAB KEY to enable/disable occlusion culling" << std::endl; } LLGL::VertexFormat CreateBuffers() { // Specify vertex format LLGL::VertexFormat vertexFormat; vertexFormat.AddAttribute("position", LLGL::DataType::Float, 3); // Create vertex, index, and constant buffer vertexBuffer = CreateVertexBuffer(GenerateCubeVertices(), vertexFormat); indexBuffer = CreateIndexBuffer(GenerateCubeTriangelIndices(), LLGL::DataType::UInt32); constantBuffer = CreateConstantBuffer(settings); return vertexFormat; } void CreatePipelines() { // Create graphics pipeline for occlusion query LLGL::GraphicsPipelineDescriptor pipelineDesc; { pipelineDesc.shaderProgram = shaderProgram; pipelineDesc.depth.testEnabled = true; pipelineDesc.rasterizer.multiSampleEnabled = true; pipelineDesc.rasterizer.samples = 8; LLGL::BlendTargetDescriptor blendDesc; { blendDesc.colorMask = LLGL::ColorRGBAb(false); } pipelineDesc.blend.targets.push_back(blendDesc); } occlusionPipeline = renderer->CreateGraphicsPipeline(pipelineDesc); // Create graphics pipeline for scene rendering { pipelineDesc.depth.testEnabled = true; pipelineDesc.depth.writeEnabled = true; pipelineDesc.blend.targets[0].colorMask = LLGL::ColorRGBAb(true); } scenePipeline = renderer->CreateGraphicsPipeline(pipelineDesc); } void CreateQueries() { // Create query to determine if any samples passed the depth test (occlusion query) LLGL::QueryDescriptor queryDesc; { queryDesc.type = LLGL::QueryType::AnySamplesPassed; queryDesc.renderCondition = true; } occlusionQuery = renderer->CreateQuery(queryDesc); // Create query to determine number of primitives that are sent to the rasterizer { queryDesc.type = LLGL::QueryType::PrimitivesGenerated; queryDesc.renderCondition = false; } geometryQuery = renderer->CreateQuery(queryDesc); } std::uint64_t GetAndSyncQueryResult(LLGL::Query* query) { // Wait until query result is available and return result std::uint64_t result = 0; while (!context->QueryResult(*query, result)) { /* wait */ } return result; } void PrintQueryResult() { std::cout << "occlusion culling: " << (occlusionCullingEnabled ? "enabled" : "disabled"); std::cout << ", primitives generated: " << GetAndSyncQueryResult(geometryQuery); if (occlusionCullingEnabled) std::cout << ", geometry visible: " << (GetAndSyncQueryResult(occlusionQuery) != 0 ? "yes" : "no"); std::cout << " \r"; std::flush(std::cout); } void SetBoxColor(const LLGL::ColorRGBAf& color) { settings.color = color; UpdateConstantBuffer(constantBuffer, settings); } private: void OnDrawFrame() override { // Update user input if (input->KeyDown(LLGL::Key::Tab)) occlusionCullingEnabled = !occlusionCullingEnabled; // Update matrices in constant buffer static float anim; anim += 0.01f; settings.wvpMatrix = projection; Gs::RotateFree(settings.wvpMatrix, { 0, 1, 0 }, Gs::Deg2Rad(std::sin(anim)*55.0f)); Gs::Translate(settings.wvpMatrix, { 0, 0, 5 }); Gs::RotateFree(settings.wvpMatrix, Gs::Vector3f(1).Normalized(), anim*3); // Clear color and depth buffers context->ClearBuffers(LLGL::ClearBuffersFlags::Color | LLGL::ClearBuffersFlags::Depth); // Set buffers context->SetVertexBuffer(*vertexBuffer); context->SetIndexBuffer(*indexBuffer); context->SetConstantBuffer(*constantBuffer, 0, LLGL::ShaderStageFlags::VertexStage | LLGL::ShaderStageFlags::FragmentStage); // Start with qeometry query context->BeginQuery(*geometryQuery); { if (occlusionCullingEnabled) { // Draw box for occlusion query context->SetGraphicsPipeline(*occlusionPipeline); SetBoxColor({ 1, 1, 1 }); context->BeginQuery(*occlusionQuery); { context->DrawIndexed(36, 0); } context->EndQuery(*occlusionQuery); // Draw scene context->SetGraphicsPipeline(*scenePipeline); SetBoxColor({ 0, 1, 0 }); context->BeginRenderCondition(*occlusionQuery, LLGL::RenderConditionMode::Wait); { context->DrawIndexed(36, 0); } context->EndRenderCondition(); } else { // Draw scene without occlusion query context->SetGraphicsPipeline(*scenePipeline); SetBoxColor({ 0, 1, 0 }); context->DrawIndexed(36, 0); } } context->EndQuery(*geometryQuery); PrintQueryResult(); // Present result on the screen context->Present(); } }; LLGL_IMPLEMENT_TUTORIAL(Tutorial04); <|endoftext|>
<commit_before><commit_msg>Patch 3137408 - Optimization and bug fix for OgrePose<commit_after><|endoftext|>
<commit_before>#ifdef HAVE_CONFIG_H #include <sys_config.h> #endif #include "simreadline.h" #include "commands.h" #include <arch/MGSystem.h> #include <sim/config.h> #ifdef ENABLE_MONITOR # include <sim/monitor.h> #endif #include <sstream> #include <iostream> #include <limits> #ifdef USE_SDL #include <SDL.h> #endif #include <argp.h> using namespace Simulator; using namespace std; struct ProgramConfig { unsigned int m_areaTech; string m_configFile; bool m_enableMonitor; bool m_interactive; bool m_terminate; bool m_dumpconf; bool m_quiet; bool m_dumpvars; vector<string> m_printvars; bool m_earlyquit; ConfigMap m_overrides; vector<string> m_extradevs; vector<pair<RegAddr, string> > m_loads; vector<pair<RegAddr, RegValue> > m_regs; bool m_dumptopo; string m_topofile; bool m_dumpnodeprops; bool m_dumpedgeprops; vector<string> m_argv; }; extern "C" { const char *argp_program_version = "mgsim " PACKAGE_VERSION "\n" "Copyright (C) 2008,2009,2010,2011 Universiteit van Amsterdam.\n" "\n" "Written by Mike Lankamp. Maintained by the Microgrid project."; const char *argp_program_bug_address = PACKAGE_BUGREPORT; } static const char *mgsim_doc = "This program simulates Microgrid-based systems." "\v" /* separates top and bottom part of --help generated by argp. */ "The first non-option argument is treated as a file to load as " "a bootable ROM. All non-option arguments are also stored as strings " "in a data ROM. For more advanced code/data arrangements, use " "configuration options to set up ROM devices and memory ranges." "\n\n" "For more information, see mgsimdoc(1)."; static const struct argp_option mgsim_options[] = { { "interactive", 'i', 0, 0, "Start the simulator in interactive mode.", 0 }, { 0, 'R', "NUM VALUE", 0, "Store the integer VALUE in the specified register of the initial thread.", 1 }, { 0, 'F', "NUM VALUE", 0, "Store the float VALUE in the specified FP register of the initial thread.", 1 }, { 0, 'L', "NUM FILE", 0, "Create an ActiveROM component with the contents of FILE and store the address in the specified register of the initial thread.", 1 }, { "config", 'c', "FILE", 0, "Read configuration from FILE.", 2 }, { "dump-configuration", 'd', 0, 0, "Dump configuration to standard error prior to program startup.", 2 }, { "override", 'o', "NAME=VAL", 0, "Overrides the configuration option NAME with value VAL. Can be specified multiple times.", 2 }, { "do-nothing", 'n', 0, 0, "Exit before the program starts, but after the system is configured.", 3 }, { "quiet", 'q', 0, 0, "Do not print simulation statistics after execution.", 3 }, { "terminate", 't', 0, 0, "Terminate the simulator upon an exception, instead of dropping to the interactive prompt.", 3 }, #ifdef ENABLE_CACTI { "area", 'a', "VAL", 0, "Dump area information prior to program startup using CACTI. Assume technology is VAL nanometers.", 4 }, #endif { "list-mvars", 'l', 0, 0, "Dump list of monitor variables prior to program startup.", 5 }, { "print-final-mvars", 'p', "PATTERN", 0, "Print the value of all monitoring variables matching PATTERN. Can be specified multiple times.", 5 }, { "dump-topology", 'T', "FILE", 0, "Dump the grid topology to FILE prior to program startup.", 6 }, { "no-node-properties", 10, 0, 0, "Do not print component properties in the topology dump.", 6 }, { "no-edge-properties", 11, 0, 0, "Do not print link properties in the topology output.", 6 }, #ifdef ENABLE_MONITOR { "monitor", 'm', 0, 0, "Enable asynchronous simulation monitoring (configure with -o MonitorSampleVariables).", 7 }, #endif { 0, 's', 0, 0, "(obsolete; symbols are now read automatically from ELF)", 8 }, { 0, 0, 0, 0, 0, 0 } }; static error_t mgsim_parse_opt(int key, char *arg, struct argp_state *state) { struct ProgramConfig &config = *(struct ProgramConfig*)state->input; switch (key) { case 'a': { char* endptr; unsigned int tech = strtoul(arg, &endptr, 0); if (*endptr != '\0') { throw runtime_error("Error: unable to parse technology size"); } else if (tech < 1) { throw runtime_error("Error: technology size must be >= 1 nm"); } else { config.m_areaTech = tech; } } break; case 'c': config.m_configFile = arg; break; case 'i': config.m_interactive = true; break; case 't': config.m_terminate = true; break; case 'q': config.m_quiet = true; break; case 's': cerr << "# Warning: ignoring obsolete flag '-s'" << endl; break; case 'd': config.m_dumpconf = true; break; case 'm': config.m_enableMonitor = true; break; case 'l': config.m_dumpvars = true; break; case 'p': config.m_printvars.push_back(arg); break; case 'T': config.m_dumptopo = true; config.m_topofile = arg; break; case 10 : config.m_dumpnodeprops = false; break; case 11 : config.m_dumpedgeprops = false; break; case 'n': config.m_earlyquit = true; break; case 'o': { string sarg = arg; string::size_type eq = sarg.find_first_of("="); if (eq == string::npos) { throw runtime_error("Error: malformed configuration override syntax: " + sarg); } string name = sarg.substr(0, eq); // push overrides in inverse order, so that the latest // specified in the command line has higher priority in // matching. config.m_overrides.insert(name, sarg.substr(eq + 1)); } break; case 'L': { if (state->next == state->argc) { throw runtime_error("Error: -L<N> expected filename"); } string filename(state->argv[state->next++]); string regnum(arg); char* endptr; unsigned long index = strtoul(regnum.c_str(), &endptr, 0); if (*endptr != '\0') { throw runtime_error("Error: invalid register specifier in option: " + regnum); } RegAddr regaddr = MAKE_REGADDR(RT_INTEGER, index); string devname = "file" + regnum; config.m_extradevs.push_back(devname); string cfgprefix = devname + ":"; config.m_overrides.append(cfgprefix + "Type", "AROM"); config.m_overrides.append(cfgprefix + "ROMContentSource", "RAW"); config.m_overrides.append(cfgprefix + "ROMFileName", filename); config.m_loads.push_back(make_pair(regaddr, devname)); } break; case 'R': case 'F': { if (state->next == state->argc) { throw runtime_error("Error: -R/-F expected register value"); } stringstream value; value << state->argv[state->next++]; RegAddr addr; RegValue val; char* endptr; unsigned long index = strtoul(arg, &endptr, 0); if (*endptr != '\0') { throw runtime_error("Error: invalid register specifier in option"); } if (key == 'R') { value >> *(SInteger*)&val.m_integer; addr = MAKE_REGADDR(RT_INTEGER, index); } else { double f; value >> f; val.m_float.fromfloat(f); addr = MAKE_REGADDR(RT_FLOAT, index); } if (value.fail()) { throw runtime_error("Error: invalid value for register"); } val.m_state = RST_FULL; config.m_regs.push_back(make_pair(addr, val)); } break; case ARGP_KEY_ARG: /* extra arguments */ { if (config.m_argv.empty()) { cerr << "Warning: converting first extra argument to -o *:ROMFileName=" << arg << endl; config.m_overrides.append("*:ROMFileName", arg); } config.m_argv.push_back(arg); } break; case ARGP_KEY_NO_ARGS: argp_usage (state); break; default: return ARGP_ERR_UNKNOWN; } return 0; } static struct argp argp = { mgsim_options /* options */, mgsim_parse_opt /* parser */, NULL /* args_doc */, mgsim_doc /* doc */, NULL /* children */, NULL /* help filter */, NULL /* argp domain */ }; void PrintFinalVariables(const ProgramConfig& cfg) { if (!cfg.m_printvars.empty()) { std::cout << "### begin end-of-simulation variables" << std::endl; for (size_t i = 0; i < cfg.m_printvars.size(); ++i) ReadSampleVariables(cout, cfg.m_printvars[i]); std::cout << "### end end-of-simulation variables" << std::endl; } } #ifdef USE_SDL extern "C" #endif int main(int argc, char** argv) { srand(time(NULL)); try { // Parse command line arguments ProgramConfig config; config.m_areaTech = 0; config.m_configFile = MGSIM_CONFIG_PATH; config.m_enableMonitor = false; config.m_interactive = false; config.m_terminate = false; config.m_dumpconf = false; config.m_quiet = false; config.m_dumpvars = false; config.m_earlyquit = false; config.m_dumptopo = false; config.m_dumpnodeprops = true; config.m_dumpedgeprops = true; argp_parse(&argp, argc, argv, 0, 0, &config); if (config.m_quiet) { config.m_overrides.append("*.ROMVerboseLoad", "false"); } if (config.m_interactive) { // Interactive mode std::clog << argp_program_version << std::endl; } // Read configuration from file Config configfile(config.m_configFile, config.m_overrides, config.m_argv); if (config.m_dumpconf) { // Printing the configuration early, in case constructing the // system (below) fails. std::clog << "### simulator version: " PACKAGE_VERSION << std::endl; configfile.dumpConfiguration(std::clog, config.m_configFile); } // Create the system MGSystem sys(configfile, config.m_regs, config.m_loads, config.m_extradevs, !config.m_interactive); #ifdef ENABLE_MONITOR string mo_mdfile = configfile.getValueOrDefault<string>("MonitorMetadataFile", "mgtrace.md"); string mo_tfile = configfile.getValueOrDefault<string>("MonitorTraceFile", "mgtrace.out"); Monitor mo(sys, config.m_enableMonitor, mo_mdfile, config.m_earlyquit ? "" : mo_tfile, !config.m_interactive); #endif if (config.m_dumpconf) { // we also print the cache, which expands all effectively // looked up configuration values after the system // was constructed successfully. configfile.dumpConfigurationCache(std::clog); } if (config.m_dumpvars) { std::clog << "### begin monitor variables" << std::endl; ListSampleVariables(std::clog); std::clog << "### end monitor variables" << std::endl; } if (config.m_areaTech > 0) { std::clog << "### begin area information" << std::endl; #ifdef ENABLE_CACTI sys.DumpArea(std::cout, config.m_areaTech); #else std::clog << "# Warning: CACTI not enabled; reconfigure with --enable-cacti" << std::endl; #endif std::clog << "### end area information" << std::endl; } if (config.m_dumptopo) { ofstream of(config.m_topofile.c_str(), ios::out); configfile.dumpComponentGraph(of, config.m_dumpnodeprops, config.m_dumpedgeprops); of.close(); } if (config.m_earlyquit) exit(0); bool interactive = config.m_interactive; if (!interactive) { // Non-interactive mode; run and dump cycle count try { #ifdef ENABLE_MONITOR mo.start(); #endif StepSystem(sys, INFINITE_CYCLES); #ifdef ENABLE_MONITOR mo.stop(); #endif if (!config.m_quiet) { clog << "### begin end-of-simulation statistics" << endl; sys.PrintAllStatistics(clog); clog << "### end end-of-simulation statistics" << endl; } } catch (const exception& e) { #ifdef ENABLE_MONITOR mo.stop(); #endif if (config.m_terminate) { // We do not want to go to interactive mode, // rethrow so it abort the program. PrintFinalVariables(config); throw; } PrintException(cerr, e); // When we get an exception in non-interactive mode, // jump into interactive mode interactive = true; } } if (interactive) { // Command loop cout << endl; CommandLineReader clr; cli_context ctx = { clr, sys #ifdef ENABLE_MONITOR , mo #endif }; while (HandleCommandLine(ctx) == false) /* just loop */; } PrintFinalVariables(config); } catch (const exception& e) { PrintException(cerr, e); return 1; } return 0; } <commit_msg>Prefix main's warning message with '#'.<commit_after>#ifdef HAVE_CONFIG_H #include <sys_config.h> #endif #include "simreadline.h" #include "commands.h" #include <arch/MGSystem.h> #include <sim/config.h> #ifdef ENABLE_MONITOR # include <sim/monitor.h> #endif #include <sstream> #include <iostream> #include <limits> #ifdef USE_SDL #include <SDL.h> #endif #include <argp.h> using namespace Simulator; using namespace std; struct ProgramConfig { unsigned int m_areaTech; string m_configFile; bool m_enableMonitor; bool m_interactive; bool m_terminate; bool m_dumpconf; bool m_quiet; bool m_dumpvars; vector<string> m_printvars; bool m_earlyquit; ConfigMap m_overrides; vector<string> m_extradevs; vector<pair<RegAddr, string> > m_loads; vector<pair<RegAddr, RegValue> > m_regs; bool m_dumptopo; string m_topofile; bool m_dumpnodeprops; bool m_dumpedgeprops; vector<string> m_argv; }; extern "C" { const char *argp_program_version = "mgsim " PACKAGE_VERSION "\n" "Copyright (C) 2008,2009,2010,2011 Universiteit van Amsterdam.\n" "\n" "Written by Mike Lankamp. Maintained by the Microgrid project."; const char *argp_program_bug_address = PACKAGE_BUGREPORT; } static const char *mgsim_doc = "This program simulates Microgrid-based systems." "\v" /* separates top and bottom part of --help generated by argp. */ "The first non-option argument is treated as a file to load as " "a bootable ROM. All non-option arguments are also stored as strings " "in a data ROM. For more advanced code/data arrangements, use " "configuration options to set up ROM devices and memory ranges." "\n\n" "For more information, see mgsimdoc(1)."; static const struct argp_option mgsim_options[] = { { "interactive", 'i', 0, 0, "Start the simulator in interactive mode.", 0 }, { 0, 'R', "NUM VALUE", 0, "Store the integer VALUE in the specified register of the initial thread.", 1 }, { 0, 'F', "NUM VALUE", 0, "Store the float VALUE in the specified FP register of the initial thread.", 1 }, { 0, 'L', "NUM FILE", 0, "Create an ActiveROM component with the contents of FILE and store the address in the specified register of the initial thread.", 1 }, { "config", 'c', "FILE", 0, "Read configuration from FILE.", 2 }, { "dump-configuration", 'd', 0, 0, "Dump configuration to standard error prior to program startup.", 2 }, { "override", 'o', "NAME=VAL", 0, "Overrides the configuration option NAME with value VAL. Can be specified multiple times.", 2 }, { "do-nothing", 'n', 0, 0, "Exit before the program starts, but after the system is configured.", 3 }, { "quiet", 'q', 0, 0, "Do not print simulation statistics after execution.", 3 }, { "terminate", 't', 0, 0, "Terminate the simulator upon an exception, instead of dropping to the interactive prompt.", 3 }, #ifdef ENABLE_CACTI { "area", 'a', "VAL", 0, "Dump area information prior to program startup using CACTI. Assume technology is VAL nanometers.", 4 }, #endif { "list-mvars", 'l', 0, 0, "Dump list of monitor variables prior to program startup.", 5 }, { "print-final-mvars", 'p', "PATTERN", 0, "Print the value of all monitoring variables matching PATTERN. Can be specified multiple times.", 5 }, { "dump-topology", 'T', "FILE", 0, "Dump the grid topology to FILE prior to program startup.", 6 }, { "no-node-properties", 10, 0, 0, "Do not print component properties in the topology dump.", 6 }, { "no-edge-properties", 11, 0, 0, "Do not print link properties in the topology output.", 6 }, #ifdef ENABLE_MONITOR { "monitor", 'm', 0, 0, "Enable asynchronous simulation monitoring (configure with -o MonitorSampleVariables).", 7 }, #endif { 0, 's', 0, 0, "(obsolete; symbols are now read automatically from ELF)", 8 }, { 0, 0, 0, 0, 0, 0 } }; static error_t mgsim_parse_opt(int key, char *arg, struct argp_state *state) { struct ProgramConfig &config = *(struct ProgramConfig*)state->input; switch (key) { case 'a': { char* endptr; unsigned int tech = strtoul(arg, &endptr, 0); if (*endptr != '\0') { throw runtime_error("Error: unable to parse technology size"); } else if (tech < 1) { throw runtime_error("Error: technology size must be >= 1 nm"); } else { config.m_areaTech = tech; } } break; case 'c': config.m_configFile = arg; break; case 'i': config.m_interactive = true; break; case 't': config.m_terminate = true; break; case 'q': config.m_quiet = true; break; case 's': cerr << "# Warning: ignoring obsolete flag '-s'" << endl; break; case 'd': config.m_dumpconf = true; break; case 'm': config.m_enableMonitor = true; break; case 'l': config.m_dumpvars = true; break; case 'p': config.m_printvars.push_back(arg); break; case 'T': config.m_dumptopo = true; config.m_topofile = arg; break; case 10 : config.m_dumpnodeprops = false; break; case 11 : config.m_dumpedgeprops = false; break; case 'n': config.m_earlyquit = true; break; case 'o': { string sarg = arg; string::size_type eq = sarg.find_first_of("="); if (eq == string::npos) { throw runtime_error("Error: malformed configuration override syntax: " + sarg); } string name = sarg.substr(0, eq); // push overrides in inverse order, so that the latest // specified in the command line has higher priority in // matching. config.m_overrides.insert(name, sarg.substr(eq + 1)); } break; case 'L': { if (state->next == state->argc) { throw runtime_error("Error: -L<N> expected filename"); } string filename(state->argv[state->next++]); string regnum(arg); char* endptr; unsigned long index = strtoul(regnum.c_str(), &endptr, 0); if (*endptr != '\0') { throw runtime_error("Error: invalid register specifier in option: " + regnum); } RegAddr regaddr = MAKE_REGADDR(RT_INTEGER, index); string devname = "file" + regnum; config.m_extradevs.push_back(devname); string cfgprefix = devname + ":"; config.m_overrides.append(cfgprefix + "Type", "AROM"); config.m_overrides.append(cfgprefix + "ROMContentSource", "RAW"); config.m_overrides.append(cfgprefix + "ROMFileName", filename); config.m_loads.push_back(make_pair(regaddr, devname)); } break; case 'R': case 'F': { if (state->next == state->argc) { throw runtime_error("Error: -R/-F expected register value"); } stringstream value; value << state->argv[state->next++]; RegAddr addr; RegValue val; char* endptr; unsigned long index = strtoul(arg, &endptr, 0); if (*endptr != '\0') { throw runtime_error("Error: invalid register specifier in option"); } if (key == 'R') { value >> *(SInteger*)&val.m_integer; addr = MAKE_REGADDR(RT_INTEGER, index); } else { double f; value >> f; val.m_float.fromfloat(f); addr = MAKE_REGADDR(RT_FLOAT, index); } if (value.fail()) { throw runtime_error("Error: invalid value for register"); } val.m_state = RST_FULL; config.m_regs.push_back(make_pair(addr, val)); } break; case ARGP_KEY_ARG: /* extra arguments */ { if (config.m_argv.empty()) { cerr << "# Warning: converting first extra argument to -o *:ROMFileName=" << arg << endl; config.m_overrides.append("*:ROMFileName", arg); } config.m_argv.push_back(arg); } break; case ARGP_KEY_NO_ARGS: argp_usage (state); break; default: return ARGP_ERR_UNKNOWN; } return 0; } static struct argp argp = { mgsim_options /* options */, mgsim_parse_opt /* parser */, NULL /* args_doc */, mgsim_doc /* doc */, NULL /* children */, NULL /* help filter */, NULL /* argp domain */ }; void PrintFinalVariables(const ProgramConfig& cfg) { if (!cfg.m_printvars.empty()) { std::cout << "### begin end-of-simulation variables" << std::endl; for (size_t i = 0; i < cfg.m_printvars.size(); ++i) ReadSampleVariables(cout, cfg.m_printvars[i]); std::cout << "### end end-of-simulation variables" << std::endl; } } #ifdef USE_SDL extern "C" #endif int main(int argc, char** argv) { srand(time(NULL)); try { // Parse command line arguments ProgramConfig config; config.m_areaTech = 0; config.m_configFile = MGSIM_CONFIG_PATH; config.m_enableMonitor = false; config.m_interactive = false; config.m_terminate = false; config.m_dumpconf = false; config.m_quiet = false; config.m_dumpvars = false; config.m_earlyquit = false; config.m_dumptopo = false; config.m_dumpnodeprops = true; config.m_dumpedgeprops = true; argp_parse(&argp, argc, argv, 0, 0, &config); if (config.m_quiet) { config.m_overrides.append("*.ROMVerboseLoad", "false"); } if (config.m_interactive) { // Interactive mode std::clog << argp_program_version << std::endl; } // Read configuration from file Config configfile(config.m_configFile, config.m_overrides, config.m_argv); if (config.m_dumpconf) { // Printing the configuration early, in case constructing the // system (below) fails. std::clog << "### simulator version: " PACKAGE_VERSION << std::endl; configfile.dumpConfiguration(std::clog, config.m_configFile); } // Create the system MGSystem sys(configfile, config.m_regs, config.m_loads, config.m_extradevs, !config.m_interactive); #ifdef ENABLE_MONITOR string mo_mdfile = configfile.getValueOrDefault<string>("MonitorMetadataFile", "mgtrace.md"); string mo_tfile = configfile.getValueOrDefault<string>("MonitorTraceFile", "mgtrace.out"); Monitor mo(sys, config.m_enableMonitor, mo_mdfile, config.m_earlyquit ? "" : mo_tfile, !config.m_interactive); #endif if (config.m_dumpconf) { // we also print the cache, which expands all effectively // looked up configuration values after the system // was constructed successfully. configfile.dumpConfigurationCache(std::clog); } if (config.m_dumpvars) { std::clog << "### begin monitor variables" << std::endl; ListSampleVariables(std::clog); std::clog << "### end monitor variables" << std::endl; } if (config.m_areaTech > 0) { std::clog << "### begin area information" << std::endl; #ifdef ENABLE_CACTI sys.DumpArea(std::cout, config.m_areaTech); #else std::clog << "# Warning: CACTI not enabled; reconfigure with --enable-cacti" << std::endl; #endif std::clog << "### end area information" << std::endl; } if (config.m_dumptopo) { ofstream of(config.m_topofile.c_str(), ios::out); configfile.dumpComponentGraph(of, config.m_dumpnodeprops, config.m_dumpedgeprops); of.close(); } if (config.m_earlyquit) exit(0); bool interactive = config.m_interactive; if (!interactive) { // Non-interactive mode; run and dump cycle count try { #ifdef ENABLE_MONITOR mo.start(); #endif StepSystem(sys, INFINITE_CYCLES); #ifdef ENABLE_MONITOR mo.stop(); #endif if (!config.m_quiet) { clog << "### begin end-of-simulation statistics" << endl; sys.PrintAllStatistics(clog); clog << "### end end-of-simulation statistics" << endl; } } catch (const exception& e) { #ifdef ENABLE_MONITOR mo.stop(); #endif if (config.m_terminate) { // We do not want to go to interactive mode, // rethrow so it abort the program. PrintFinalVariables(config); throw; } PrintException(cerr, e); // When we get an exception in non-interactive mode, // jump into interactive mode interactive = true; } } if (interactive) { // Command loop cout << endl; CommandLineReader clr; cli_context ctx = { clr, sys #ifdef ENABLE_MONITOR , mo #endif }; while (HandleCommandLine(ctx) == false) /* just loop */; } PrintFinalVariables(config); } catch (const exception& e) { PrintException(cerr, e); return 1; } return 0; } <|endoftext|>
<commit_before>#include "webcam.hpp" using namespace cv; using namespace std; Mat ellipticKernel(int width, int height = -1) { if (height==-1) { return getStructuringElement(MORPH_ELLIPSE,Size(width,width), Point(width/2, width/2)); } else { return getStructuringElement(MORPH_ELLIPSE,Size(width,height), Point(width/2, height/2)); } } void morphFast(Mat inout, int smallsize = 100, int factor = 25, int eq = 1, int diler = 0) { int width, height; width = inout.size().width; height = inout.size().height; Mat downsample; resize(inout, downsample, Size(smallsize,smallsize)); Mat kernel = ellipticKernel(factor); if (diler) { erode(downsample, downsample, kernel); } else { dilate(downsample, downsample, kernel); } if (eq) { equalizeHist(downsample, downsample); } resize(downsample, inout, Size(width, height)); } int main (int argc, char** argv) { int tracker1, tracker2, tracker3; namedWindow("s",1); createTrackbar("1","s",&tracker1,100); createTrackbar("2","s",&tracker2,100); createTrackbar("3","s",&tracker3,100); CvCapture* capture = 0; int width, height, fps; capture = cvCaptureFromCAM(0); if (!capture) { printf("No camera detected!"); return -1; } ifstream configFile (".config"); if (configFile.is_open()) { //probably want to support corrupted .config string line; getline(configFile, line); istringstream(line)>>width; getline(configFile, line); istringstream(line)>>height; cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, width); cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, height); configFile.close(); } else { initResolutions(); for (int i=36; i<150; i++) { cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, resolutions[i].width); cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, resolutions[i].height); } width = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH); height = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT); ofstream configFileOut(".config"); configFileOut << width; configFileOut << "\n"; configFileOut << height; configFileOut << "\n"; configFileOut.close(); } bool keepGoing = true; // srand(890);//not interested in good randomness for (int i = 0; i < 30; i++) { // capture some frames so exposure correction takes place cvQueryFrame(capture); } Mat background = cvQueryFrame(capture); background = background.clone(); blur(background, background, Size(50,50)); Mat image; Mat channel[3]; while (keepGoing) { image = cvQueryFrame(capture); // preprocess by rotating according to OVR roll // imshow("webcam", image); // let's make multiple masks where 0=not mouth, 1=uncertain // then multiply them together and multiply that with image // and run haar classifier on image Mat gray, blurred_img; cvtColor(image, gray, CV_RGB2GRAY); blur(image, blurred_img, Size(50,50)); // this mask filters out areas with too many edges // removed for now; it didn't generalize well /* Mat canny; Canny(gray, canny, 50, 50, 3); blur(canny, canny, Size(width/20,height/20)); bitwise_not(canny, canny); threshold(canny, canny, 200, 1, THRESH_BINARY); blur(canny*255, canny, Size(width/10, height/10)); threshold(canny, canny, 220, 1, THRESH_BINARY); imshow("canny mask", gray.mul(canny)); */ // this mask filters out areas which have not changed much // background needs to be updated when person is not in frame // use OVR SDK to do this later Mat flow; absdiff(blurred_img, background, flow); cvtColor(flow, flow, CV_RGB2GRAY); morphFast(flow); threshold(flow, flow, 60, 1, THRESH_BINARY); // imshow("flow mask", gray.mul(flow)); // this mask gets anything kind of dark (DK2) and dilates Mat kindofdark; equalizeHist(gray, kindofdark); threshold(kindofdark, kindofdark, 100, 1, THRESH_BINARY_INV); morphFast(kindofdark, 100, 17, 0); // imshow("dark mask", gray.mul(kindofdark)); Mat mask = flow.mul(kindofdark); // open the mask Mat smallMask; resize(mask, smallMask, Size(width/5,height/5)); Mat erodeKernel = ellipticKernel(,81); erode(smallMask, smallMask, erodeKernel); Mat dilateKernel = ellipticKernel(41,81); dilate(smallMask, smallMask, dilateKernel); resize(smallMask, smallMask, Size(width, height)); bitwise_and(smallMask,mask,mask); // imshow("morph mask", gray.mul(mask)); // update background with new morph mask // average what we know is background with prior background // erode it first since we really want to be sure it's bg // Mat erodeKernel = ellipticKernel(21); erode(mask, mask, erodeKernel); Mat mask_; subtract(1,mask,mask_); Mat mask3, mask3_; channel[0] = mask; channel[1] = mask; channel[2] = mask; merge(channel, 3, mask3); channel[0] = mask_; channel[1] = mask_; channel[2] = mask_; merge(channel, 3, mask3_); background = background.mul(mask3) + (background.mul(mask3_) + blurred_img.mul(mask3_))/2; imshow("background", background); Moments lol = moments(gray, 1); circle(image, Point(lol.m10/lol.m00,lol.m01/lol.m00),20,Scalar(128),30); imshow("leimage", image); CascadeClassifier mouth_cascade; mouth_cascade.load("Mouth.xml"); vector<Rect> mouths; int scale = tracker1+1; Mat classifyThis; resize(gray, classifyThis, Size(width/(tracker1+1),height/(tracker2+1)); // bilateralFilter(gray, classifyThis, 15, 10, 1); equalizeHist(classifyThis, classifyThis); classifyThis = classifyThis.mul(mask); mouth_cascade.detectMultiScale(classifyThis, mouths, 1.1, 5, CV_HAAR_SCALE_IMAGE); for (size_t i=0; i<mouths.size(); i++) { Point center( mouths[i].x + mouths[i].width*0.5, mouths[i].y + mouths[i].height*0.5 ); ellipse( image, center, Size( mouths[i].width*0.5, mouths[i].height*0.5), 0, 0, 360, Scalar( 255, 0, 255 ), 4, 8, 0 ); } imshow("MOUTH", image); keepGoing = (waitKey(25)<0); } cvReleaseCapture(&capture); return 0; } <commit_msg>hacking<commit_after>#include "webcam.hpp" using namespace cv; using namespace std; Mat ellipticKernel(int width, int height = -1) { if (height==-1) { return getStructuringElement(MORPH_ELLIPSE,Size(width,width), Point(width/2, width/2)); } else { return getStructuringElement(MORPH_ELLIPSE,Size(width,height), Point(width/2, height/2)); } } void morphFast(Mat inout, int smallsize = 100, int factor = 25, int eq = 1, int diler = 0) { int width, height; width = inout.size().width; height = inout.size().height; Mat downsample; resize(inout, downsample, Size(smallsize,smallsize)); Mat kernel = ellipticKernel(factor); if (diler) { erode(downsample, downsample, kernel); } else { dilate(downsample, downsample, kernel); } if (eq) { equalizeHist(downsample, downsample); } resize(downsample, inout, Size(width, height)); } int main (int argc, char** argv) { int tracker1, tracker2, tracker3; namedWindow("s",1); createTrackbar("1","s",&tracker1,100); createTrackbar("2","s",&tracker2,100); createTrackbar("3","s",&tracker3,100); CvCapture* capture = 0; int width, height, fps; capture = cvCaptureFromCAM(0); if (!capture) { printf("No camera detected!"); return -1; } ifstream configFile (".config"); if (configFile.is_open()) { //probably want to support corrupted .config string line; getline(configFile, line); istringstream(line)>>width; getline(configFile, line); istringstream(line)>>height; cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, width); cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, height); configFile.close(); } else { initResolutions(); for (int i=36; i<150; i++) { cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, resolutions[i].width); cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, resolutions[i].height); } width = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH); height = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT); ofstream configFileOut(".config"); configFileOut << width; configFileOut << "\n"; configFileOut << height; configFileOut << "\n"; configFileOut.close(); } bool keepGoing = true; // srand(890);//not interested in good randomness for (int i = 0; i < 30; i++) { // capture some frames so exposure correction takes place cvQueryFrame(capture); } Mat background = cvQueryFrame(capture); background = background.clone(); blur(background, background, Size(50,50)); Mat image; Mat channel[3]; while (keepGoing) { image = cvQueryFrame(capture); // preprocess by rotating according to OVR roll // imshow("webcam", image); // let's make multiple masks where 0=not mouth, 1=uncertain // then multiply them together and multiply that with image // and run haar classifier on image Mat gray, blurred_img; cvtColor(image, gray, CV_RGB2GRAY); blur(image, blurred_img, Size(50,50)); // this mask filters out areas with too many edges // removed for now; it didn't generalize well /* Mat canny; Canny(gray, canny, 50, 50, 3); blur(canny, canny, Size(width/20,height/20)); bitwise_not(canny, canny); threshold(canny, canny, 200, 1, THRESH_BINARY); blur(canny*255, canny, Size(width/10, height/10)); threshold(canny, canny, 220, 1, THRESH_BINARY); imshow("canny mask", gray.mul(canny)); */ // this mask filters out areas which have not changed much // background needs to be updated when person is not in frame // use OVR SDK to do this later Mat flow; absdiff(blurred_img, background, flow); cvtColor(flow, flow, CV_RGB2GRAY); morphFast(flow); threshold(flow, flow, 60, 1, THRESH_BINARY); // imshow("flow mask", gray.mul(flow)); // this mask gets anything kind of dark (DK2) and dilates Mat kindofdark; equalizeHist(gray, kindofdark); threshold(kindofdark, kindofdark, 100, 1, THRESH_BINARY_INV); morphFast(kindofdark, 100, 17, 0); // imshow("dark mask", gray.mul(kindofdark)); Mat mask = flow.mul(kindofdark); // open the mask Mat smallMask0, smallMask1; resize(mask, smallMask0, Size(width/5,height/5)); Mat erodeKernel = ellipticKernel(69,79); erode(smallMask0, smallMask1, erodeKernel); Mat dilateKernel = ellipticKernel(69,79); dilate(smallMask1, smallMask1, dilateKernel); bitwise_and(smallMask0, smallMask1, smallMask1); resize(smallMask1, mask, Size(width, height)); // imshow("morph mask", gray.mul(mask)); // update background with new morph mask // average what we know is background with prior background // erode it first since we really want to be sure it's bg // Mat erodeKernel = ellipticKernel(21); Mat erodedMask; erode(mask, erodedMask, erodeKernel); Mat mask_; subtract(1,erodedMask,mask_); Mat mask3, mask3_; channel[0] = erodedMask; channel[1] = erodedMask; channel[2] = erodedMask; merge(channel, 3, mask3); channel[0] = mask_; channel[1] = mask_; channel[2] = mask_; merge(channel, 3, mask3_); background = background.mul(mask3) + (background.mul(mask3_) + blurred_img.mul(mask3_))/2; imshow("background", background); Moments lol = moments(gray, 1); circle(image, Point(lol.m10/lol.m00,lol.m01/lol.m00),20,Scalar(128),30); imshow("leimage", image); CascadeClassifier mouth_cascade; mouth_cascade.load("Mouth.xml"); vector<Rect> mouths; int scale = tracker1+1; Mat classifyThis; equalizeHist(gray, gray);//ew; watch out not to use this later resize(gray.mul(mask), classifyThis, Size(width/scale,height/scale)); // bilateralFilter(gray, classifyThis, 15, 10, 1); mouth_cascade.detectMultiScale(classifyThis, mouths, 1.1, 5, CV_HAAR_SCALE_IMAGE); for (size_t i=0; i<mouths.size(); i++) { Rect scaled(mouths[i].x*scale, mouths[i].y*scale, mouths[i].width*scale,mouths[i].height*scale); rectangle(image, scaled, Scalar(255,0,0)); } imshow("MOUTH", image); keepGoing = (waitKey(25)<0); } cvReleaseCapture(&capture); return 0; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: poolhelp.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: er $ $Date: 2001-08-02 14:47:15 $ * * 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 SC_POOLHELP_HXX #define SC_POOLHELP_HXX #ifndef _VOS_REFERNCE_HXX_ #include <vos/refernce.hxx> #endif #ifndef _LINK_HXX #include <tools/link.hxx> #endif class ScDocument; class ScDocumentPool; class ScStyleSheetPool; class SvNumberFormatter; class SfxItemPool; class ScPoolHelper : public vos::OReference { private: ScDocumentPool* pDocPool; ScStyleSheetPool* pStylePool; SvNumberFormatter* pFormTable; SfxItemPool* pEditPool; // EditTextObjectPool SfxItemPool* pEnginePool; // EditEnginePool public: ScPoolHelper( ScDocument* pSourceDoc ); virtual ~ScPoolHelper(); // called in dtor of main document void SourceDocumentGone(); // access to pointers (are never 0): ScDocumentPool* GetDocPool() const { return pDocPool; } ScStyleSheetPool* GetStylePool() const { return pStylePool; } SvNumberFormatter* GetFormTable() const { return pFormTable; } SfxItemPool* GetEditPool() const { return pEditPool; } SfxItemPool* GetEnginePool() const { return pEnginePool; } }; #endif <commit_msg>INTEGRATION: CWS ooo19126 (1.3.926); FILE MERGED 2005/09/05 15:01:49 rt 1.3.926.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: poolhelp.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2005-09-08 18:34:56 $ * * 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 SC_POOLHELP_HXX #define SC_POOLHELP_HXX #ifndef _VOS_REFERNCE_HXX_ #include <vos/refernce.hxx> #endif #ifndef _LINK_HXX #include <tools/link.hxx> #endif class ScDocument; class ScDocumentPool; class ScStyleSheetPool; class SvNumberFormatter; class SfxItemPool; class ScPoolHelper : public vos::OReference { private: ScDocumentPool* pDocPool; ScStyleSheetPool* pStylePool; SvNumberFormatter* pFormTable; SfxItemPool* pEditPool; // EditTextObjectPool SfxItemPool* pEnginePool; // EditEnginePool public: ScPoolHelper( ScDocument* pSourceDoc ); virtual ~ScPoolHelper(); // called in dtor of main document void SourceDocumentGone(); // access to pointers (are never 0): ScDocumentPool* GetDocPool() const { return pDocPool; } ScStyleSheetPool* GetStylePool() const { return pStylePool; } SvNumberFormatter* GetFormTable() const { return pFormTable; } SfxItemPool* GetEditPool() const { return pEditPool; } SfxItemPool* GetEnginePool() const { return pEnginePool; } }; #endif <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: xeroot.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2003-04-08 16:28:32 $ * * 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 SC_XEROOT_HXX #define SC_XEROOT_HXX #ifndef SC_XLROOT_HXX #include "xlroot.hxx" #endif // Global data ================================================================ class XclExpSst; class XclExpPalette; class XclExpFontBuffer; class XclExpNumFmtBuffer; class XclExpXFBuffer; class XclExpTabIdBuffer; class XclExpLinkManager; /** Stores global buffers and data needed for Excel export filter. */ struct XclExpRootData : public XclRootData { typedef ::std::auto_ptr< XclExpSst > XclExpSstPtr; typedef ::std::auto_ptr< XclExpPalette > XclExpPalettePtr; typedef ::std::auto_ptr< XclExpFontBuffer > XclExpFontBufferPtr; typedef ::std::auto_ptr< XclExpNumFmtBuffer > XclExpNumFmtBufferPtr; typedef ::std::auto_ptr< XclExpXFBuffer > XclExpXFBufferPtr; typedef ::std::auto_ptr< XclExpTabIdBuffer > XclExpTabIdBufferPtr; typedef ::std::auto_ptr< XclExpLinkManager > XclExpLinkManagerPtr; XclExpSstPtr mpSst; /// The shared string table. XclExpPalettePtr mpPalette; /// The color buffer. XclExpFontBufferPtr mpFontBuffer; /// All fonts in the file. XclExpNumFmtBufferPtr mpNumFmtBuffer; /// All number formats in the file. XclExpXFBufferPtr mpXFBuffer; /// All XF records in the file. XclExpTabIdBufferPtr mpTabIdBuffer; /// Calc->Excel sheet index conversion. XclExpLinkManagerPtr mpLinkManager; /// Manager for internal/external links. bool mbRelUrl; /// true = Store URLs relative. explicit XclExpRootData( XclBiff eBiff, ScDocument& rDocument, const String& rBasePath, CharSet eCharSet, bool bRelUrl ); virtual ~XclExpRootData(); }; // ---------------------------------------------------------------------------- /** Access to global data from other classes. */ class XclExpRoot : public XclRoot { mutable XclExpRootData& mrExpData; /// Reference to the global export data struct. public: XclExpRoot( const XclExpRoot& rRoot ); XclExpRoot& operator=( const XclExpRoot& rRoot ); /** Returns this root instance - for code readability in derived classes. */ inline const XclExpRoot& GetRoot() const { return *this; } /** Returns true, if URLs should be stored relative to the document location. */ inline bool IsRelUrl() const { return mrExpData.mbRelUrl; } /** Returns the shared string table. */ XclExpSst& GetSst() const; /** Returns the color buffer. */ XclExpPalette& GetPalette() const; /** Returns the font buffer. */ XclExpFontBuffer& GetFontBuffer() const; /** Returns the number format buffer. */ XclExpNumFmtBuffer& GetNumFmtBuffer() const; /** Returns the cell formatting attributes buffer. */ XclExpXFBuffer& GetXFBuffer() const; /** Returns the buffer for Calc->Excel sheet index conversion. */ XclExpTabIdBuffer& GetTabIdBuffer() const; /** Returns the link manager. */ XclExpLinkManager& GetLinkManager() const; /** Checks if the passed cell address is a valid Excel cell position. @descr See XclRoot::CheckCellAddress for details. */ bool CheckCellAddress( const ScAddress& rPos ) const; /** Checks and eventually crops the cell range to valid Excel dimensions. @descr See XclRoot::CheckCellRange for details. */ bool CheckCellRange( ScRange& rRange ) const; /** Checks and eventually crops the cell ranges to valid Excel dimensions. @descr See XclRoot::CheckCellRangeList for details. */ void CheckCellRangeList( ScRangeList& rRanges ) const; protected: explicit XclExpRoot( XclExpRootData& rExpRootData ); }; // ============================================================================ #endif <commit_msg>INTEGRATION: CWS calc07 (1.4.10); FILE MERGED 2003/04/17 12:26:18 dr 1.4.10.1: #i13399# export document language<commit_after>/************************************************************************* * * $RCSfile: xeroot.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: hr $ $Date: 2003-04-23 17:30:56 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ // ============================================================================ #ifndef SC_XEROOT_HXX #define SC_XEROOT_HXX #ifndef SC_XLROOT_HXX #include "xlroot.hxx" #endif // Global data ================================================================ class XclExpSst; class XclExpPalette; class XclExpFontBuffer; class XclExpNumFmtBuffer; class XclExpXFBuffer; class XclExpTabIdBuffer; class XclExpLinkManager; /** Stores global buffers and data needed for Excel export filter. */ struct XclExpRootData : public XclRootData { typedef ::std::auto_ptr< XclExpSst > XclExpSstPtr; typedef ::std::auto_ptr< XclExpPalette > XclExpPalettePtr; typedef ::std::auto_ptr< XclExpFontBuffer > XclExpFontBufferPtr; typedef ::std::auto_ptr< XclExpNumFmtBuffer > XclExpNumFmtBufferPtr; typedef ::std::auto_ptr< XclExpXFBuffer > XclExpXFBufferPtr; typedef ::std::auto_ptr< XclExpTabIdBuffer > XclExpTabIdBufferPtr; typedef ::std::auto_ptr< XclExpLinkManager > XclExpLinkManagerPtr; XclExpSstPtr mpSst; /// The shared string table. XclExpPalettePtr mpPalette; /// The color buffer. XclExpFontBufferPtr mpFontBuffer; /// All fonts in the file. XclExpNumFmtBufferPtr mpNumFmtBuffer; /// All number formats in the file. XclExpXFBufferPtr mpXFBuffer; /// All XF records in the file. XclExpTabIdBufferPtr mpTabIdBuffer; /// Calc->Excel sheet index conversion. XclExpLinkManagerPtr mpLinkManager; /// Manager for internal/external links. bool mbRelUrl; /// true = Store URLs relative. explicit XclExpRootData( XclBiff eBiff, ScDocument& rDocument, const String& rBasePath, CharSet eCharSet, bool bRelUrl ); virtual ~XclExpRootData(); }; // ---------------------------------------------------------------------------- /** Access to global data from other classes. */ class XclExpRoot : public XclRoot { mutable XclExpRootData& mrExpData; /// Reference to the global export data struct. public: XclExpRoot( const XclExpRoot& rRoot ); XclExpRoot& operator=( const XclExpRoot& rRoot ); /** Returns this root instance - for code readability in derived classes. */ inline const XclExpRoot& GetRoot() const { return *this; } /** Returns true, if URLs should be stored relative to the document location. */ inline bool IsRelUrl() const { return mrExpData.mbRelUrl; } /** Returns the shared string table. */ XclExpSst& GetSst() const; /** Returns the color buffer. */ XclExpPalette& GetPalette() const; /** Returns the font buffer. */ XclExpFontBuffer& GetFontBuffer() const; /** Returns the number format buffer. */ XclExpNumFmtBuffer& GetNumFmtBuffer() const; /** Returns the cell formatting attributes buffer. */ XclExpXFBuffer& GetXFBuffer() const; /** Returns the buffer for Calc->Excel sheet index conversion. */ XclExpTabIdBuffer& GetTabIdBuffer() const; /** Returns the link manager. */ XclExpLinkManager& GetLinkManager() const; /** Returns the Excel add-in function name for a Calc function name. */ String GetXclAddInName( const String& rScName ) const; /** Checks if the passed cell address is a valid Excel cell position. @descr See XclRoot::CheckCellAddress for details. */ bool CheckCellAddress( const ScAddress& rPos ) const; /** Checks and eventually crops the cell range to valid Excel dimensions. @descr See XclRoot::CheckCellRange for details. */ bool CheckCellRange( ScRange& rRange ) const; /** Checks and eventually crops the cell ranges to valid Excel dimensions. @descr See XclRoot::CheckCellRangeList for details. */ void CheckCellRangeList( ScRangeList& rRanges ) const; protected: explicit XclExpRoot( XclExpRootData& rExpRootData ); }; // ============================================================================ #endif <|endoftext|>
<commit_before>/*===========================================================================*\ * * * OpenMesh * * Copyright (C) 2001-2012 by Computer Graphics Group, RWTH Aachen * * www.openmesh.org * * * *---------------------------------------------------------------------------* * This file is part of OpenMesh. * * * * OpenMesh is free software: you can redistribute it and/or modify * * it under the terms of the GNU Lesser General Public License as * * published by the Free Software Foundation, either version 3 of * * the License, or (at your option) any later version with the * * following exceptions: * * * * If other files instantiate templates or use macros * * or inline functions from this file, or you compile this file and * * link it with other files to produce an executable, this file does * * not by itself cause the resulting executable to be covered by the * * GNU Lesser General Public License. This exception does not however * * invalidate any other reasons why the executable file might be * * covered by the GNU Lesser General Public License. * * * * OpenMesh 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 LesserGeneral Public * * License along with OpenMesh. If not, * * see <http://www.gnu.org/licenses/>. * * * \*===========================================================================*/ /*===========================================================================*\ * * * $Revision: 693 $ * * $Date: 2012-09-23 16:25:16 +0200 (So, 23 Sep 2012) $ * * * \*===========================================================================*/ //============================================================================= // // Helper Functions for generating a random number between 0.0 and 1.0 with // a garantueed resolution // //============================================================================= #ifndef OPENMESH_UTILS_RANDOMNUMBERGENERATOR_HH #define OPENMESH_UTILS_RANDOMNUMBERGENERATOR_HH //== INCLUDES ================================================================= #include <OpenMesh/Core/System/config.h> #include <cstdlib> //== NAMESPACES =============================================================== namespace OpenMesh { //============================================================================= /** Generate a random number between 0.0 and 1.0 with a guaranteed resolution * ( Number of possible values ) * * Especially useful on windows, as there MAX_RAND is often only 32k which is * not enough resolution for a lot of applications */ class OPENMESHDLLEXPORT RandomNumberGenerator { public: /** \brief Constructor * * @param _resolution specifies the desired resolution for the random number generated */ RandomNumberGenerator(const size_t _resolution); /// returns a random double between 0.0 and 1.0 with a guaranteed resolution double getRand() const; size_t resolution() const; private: /// desired resolution const size_t resolution_; /// number of "blocks" of RAND_MAX that make up the desired _resolution size_t iterations_; /// maximum random number generated, which is used for normalization double maxNum_; }; //============================================================================= } // namespace OpenMesh //============================================================================= #endif // OPENMESH_UTILS_RANDOMNUMBERGENERATOR_HH defined //============================================================================= <commit_msg>Random number generator now works with size_t<commit_after>/*===========================================================================*\ * * * OpenMesh * * Copyright (C) 2001-2012 by Computer Graphics Group, RWTH Aachen * * www.openmesh.org * * * *---------------------------------------------------------------------------* * This file is part of OpenMesh. * * * * OpenMesh is free software: you can redistribute it and/or modify * * it under the terms of the GNU Lesser General Public License as * * published by the Free Software Foundation, either version 3 of * * the License, or (at your option) any later version with the * * following exceptions: * * * * If other files instantiate templates or use macros * * or inline functions from this file, or you compile this file and * * link it with other files to produce an executable, this file does * * not by itself cause the resulting executable to be covered by the * * GNU Lesser General Public License. This exception does not however * * invalidate any other reasons why the executable file might be * * covered by the GNU Lesser General Public License. * * * * OpenMesh 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 LesserGeneral Public * * License along with OpenMesh. If not, * * see <http://www.gnu.org/licenses/>. * * * \*===========================================================================*/ /*===========================================================================*\ * * * $Revision: 693 $ * * $Date: 2012-09-23 16:25:16 +0200 (So, 23 Sep 2012) $ * * * \*===========================================================================*/ //============================================================================= // // Helper Functions for generating a random number between 0.0 and 1.0 with // a garantueed resolution // //============================================================================= #ifndef OPENMESH_UTILS_RANDOMNUMBERGENERATOR_HH #define OPENMESH_UTILS_RANDOMNUMBERGENERATOR_HH //== INCLUDES ================================================================= #include <OpenMesh/Core/System/config.h> #include <cstdlib> //== NAMESPACES =============================================================== namespace OpenMesh { //============================================================================= /** Generate a random number between 0.0 and 1.0 with a guaranteed resolution * ( Number of possible values ) * * Especially useful on windows, as there MAX_RAND is often only 32k which is * not enough resolution for a lot of applications */ class OPENMESHDLLEXPORT RandomNumberGenerator { public: /** \brief Constructor * * @param _resolution specifies the desired resolution for the random number generated */ RandomNumberGenerator(const size_t _resolution); /// returns a random double between 0.0 and 1.0 with a guaranteed resolution double getRand() const; size_t resolution() const; private: /// desired resolution const size_t resolution_; /// number of "blocks" of RAND_MAX that make up the desired _resolution size_t iterations_; /// maximum random number generated, which is used for normalization size_t maxNum_; }; //============================================================================= } // namespace OpenMesh //============================================================================= #endif // OPENMESH_UTILS_RANDOMNUMBERGENERATOR_HH defined //============================================================================= <|endoftext|>
<commit_before>/* jabbergroupchatmanager.cpp - Jabber Message Manager for groupchats Copyright (c) 2004 by Till Gerken <till@tantalo.net> Kopete (c) 2004 by the Kopete developers <kopete-devel@kde.org> ************************************************************************* * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ************************************************************************* */ #include "jabbergroupchatmanager.h" #include <kdebug.h> #include <klocale.h> #include "kopetechatsessionmanager.h" #include "kopeteview.h" #include "jabberprotocol.h" #include "jabberaccount.h" #include "jabberclient.h" #include "jabbercontact.h" JabberGroupChatManager::JabberGroupChatManager ( JabberProtocol *protocol, const JabberBaseContact *user, Kopete::ContactPtrList others, XMPP::Jid roomJid ) : Kopete::ChatSession ( user, others, protocol ) { kDebug ( JABBER_DEBUG_GLOBAL ) << "New message manager for " << user->contactId (); mRoomJid = roomJid; setMayInvite( true ); // make sure Kopete knows about this instance Kopete::ChatSessionManager::self()->registerChatSession ( this ); connect ( this, SIGNAL ( messageSent ( Kopete::Message &, Kopete::ChatSession * ) ), this, SLOT ( slotMessageSent ( Kopete::Message &, Kopete::ChatSession * ) ) ); updateDisplayName (); } JabberGroupChatManager::~JabberGroupChatManager() { } void JabberGroupChatManager::updateDisplayName () { kDebug ( JABBER_DEBUG_GLOBAL ) ; setDisplayName ( mRoomJid.full () ); } const JabberBaseContact *JabberGroupChatManager::user () const { return static_cast<const JabberBaseContact *>(Kopete::ChatSession::myself()); } JabberAccount *JabberGroupChatManager::account () const { return user()->account(); } void JabberGroupChatManager::slotMessageSent ( Kopete::Message &message, Kopete::ChatSession * ) { if( account()->isConnected () ) { XMPP::Message jabberMessage; //XMPP::Jid jid = static_cast<const JabberBaseContact*>(message.from())->rosterItem().jid() ; //jabberMessage.setFrom ( jid ); XMPP::Jid toJid ( mRoomJid ); jabberMessage.setTo ( toJid ); jabberMessage.setSubject ( message.subject () ); jabberMessage.setTimeStamp ( message.timestamp () ); if ( message.plainBody().contains ( "-----BEGIN PGP MESSAGE-----" ) ) { /* * This message is encrypted, so we need to set * a fake body indicating that this is an encrypted * message (for clients not implementing this * functionality) and then generate the encrypted * payload out of the old message body. */ // please don't translate the following string jabberMessage.setBody ( i18n ( "This message is encrypted." ) ); QString encryptedBody = message.plainBody (); // remove PGP header and footer from message encryptedBody.truncate ( encryptedBody.length () - QString("-----END PGP MESSAGE-----").length () - 2 ); encryptedBody = encryptedBody.right ( encryptedBody.length () - encryptedBody.indexOf ( "\n\n" ) - 2 ); // assign payload to message jabberMessage.setXEncrypted ( encryptedBody ); } else { // this message is not encrypted jabberMessage.setBody ( message.plainBody () ); } jabberMessage.setType ( "groupchat" ); // send the message account()->client()->sendMessage ( jabberMessage ); // tell the manager that we sent successfully messageSucceeded (); } else { account()->errorConnectFirst (); // FIXME: there is no messageFailed() yet, // but we need to stop the animation etc. messageSucceeded (); } } void JabberGroupChatManager::inviteContact( const QString & contactId ) { if( account()->isConnected () ) { //NOTE: this is the obsolete, NOT RECOMMENDED protocol. // iris doesn't implement groupchat yet //NOTE: This code is duplicated in JabberProtocol::handleURL XMPP::Message jabberMessage; // XMPP::Jid jid = static_cast<const JabberBaseContact*>(account()->myself())->rosterItem().jid() ; // jabberMessage.setFrom ( jid ); jabberMessage.setTo ( contactId ); jabberMessage.setInvite( mRoomJid.bare() ); jabberMessage.setBody( i18n("You have been invited to %1", mRoomJid.bare() ) ); // send the message account()->client()->sendMessage ( jabberMessage ); } else { account()->errorConnectFirst (); } } #include "jabbergroupchatmanager.moc" // vim: set noet ts=4 sts=4 sw=4: <commit_msg>Respect user setting of pgp inline format in jabber multichat Fix end of signed/encrypted message in jabber multichat<commit_after>/* jabbergroupchatmanager.cpp - Jabber Message Manager for groupchats Copyright (c) 2004 by Till Gerken <till@tantalo.net> Kopete (c) 2004 by the Kopete developers <kopete-devel@kde.org> ************************************************************************* * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ************************************************************************* */ #include "jabbergroupchatmanager.h" #include <kdebug.h> #include <klocale.h> #include "kopetechatsessionmanager.h" #include "kopeteview.h" #include "jabberprotocol.h" #include "jabberaccount.h" #include "jabberclient.h" #include "jabbercontact.h" JabberGroupChatManager::JabberGroupChatManager ( JabberProtocol *protocol, const JabberBaseContact *user, Kopete::ContactPtrList others, XMPP::Jid roomJid ) : Kopete::ChatSession ( user, others, protocol ) { kDebug ( JABBER_DEBUG_GLOBAL ) << "New message manager for " << user->contactId (); mRoomJid = roomJid; setMayInvite( true ); // make sure Kopete knows about this instance Kopete::ChatSessionManager::self()->registerChatSession ( this ); connect ( this, SIGNAL ( messageSent ( Kopete::Message &, Kopete::ChatSession * ) ), this, SLOT ( slotMessageSent ( Kopete::Message &, Kopete::ChatSession * ) ) ); updateDisplayName (); } JabberGroupChatManager::~JabberGroupChatManager() { } void JabberGroupChatManager::updateDisplayName () { kDebug ( JABBER_DEBUG_GLOBAL ) ; setDisplayName ( mRoomJid.full () ); } const JabberBaseContact *JabberGroupChatManager::user () const { return static_cast<const JabberBaseContact *>(Kopete::ChatSession::myself()); } JabberAccount *JabberGroupChatManager::account () const { return user()->account(); } void JabberGroupChatManager::slotMessageSent ( Kopete::Message &message, Kopete::ChatSession * ) { if( account()->isConnected () ) { XMPP::Message jabberMessage; //XMPP::Jid jid = static_cast<const JabberBaseContact*>(message.from())->rosterItem().jid() ; //jabberMessage.setFrom ( jid ); XMPP::Jid toJid ( mRoomJid ); jabberMessage.setTo ( toJid ); jabberMessage.setSubject ( message.subject () ); jabberMessage.setTimeStamp ( message.timestamp () ); if ( ! account()->oldEncrypted() && message.plainBody().indexOf ( "-----BEGIN PGP MESSAGE-----" ) != -1 ) { /* * This message is encrypted, so we need to set * a fake body indicating that this is an encrypted * message (for clients not implementing this * functionality) and then generate the encrypted * payload out of the old message body. */ // please don't translate the following string jabberMessage.setBody ( "This message is signed or encrypted." ); QString encryptedBody = message.plainBody().trimmed(); // remove PGP header and footer from message encryptedBody.truncate ( encryptedBody.length () - QString("-----END PGP MESSAGE-----").length () - 2 ); encryptedBody = encryptedBody.right ( encryptedBody.length () - encryptedBody.indexOf ( "\n\n" ) - 2 ); // assign payload to message jabberMessage.setXEncrypted ( encryptedBody ); } else { // this message is not encrypted jabberMessage.setBody ( message.plainBody () ); } jabberMessage.setType ( "groupchat" ); // send the message account()->client()->sendMessage ( jabberMessage ); // tell the manager that we sent successfully messageSucceeded (); } else { account()->errorConnectFirst (); // FIXME: there is no messageFailed() yet, // but we need to stop the animation etc. messageSucceeded (); } } void JabberGroupChatManager::inviteContact( const QString & contactId ) { if( account()->isConnected () ) { //NOTE: this is the obsolete, NOT RECOMMENDED protocol. // iris doesn't implement groupchat yet //NOTE: This code is duplicated in JabberProtocol::handleURL XMPP::Message jabberMessage; // XMPP::Jid jid = static_cast<const JabberBaseContact*>(account()->myself())->rosterItem().jid() ; // jabberMessage.setFrom ( jid ); jabberMessage.setTo ( contactId ); jabberMessage.setInvite( mRoomJid.bare() ); jabberMessage.setBody( i18n("You have been invited to %1", mRoomJid.bare() ) ); // send the message account()->client()->sendMessage ( jabberMessage ); } else { account()->errorConnectFirst (); } } #include "jabbergroupchatmanager.moc" // vim: set noet ts=4 sts=4 sw=4: <|endoftext|>
<commit_before>/* * Copyright (C) 2014 Cloudius Systems, Ltd. */ #pragma once #include <experimental/optional> #include <boost/any.hpp> #include <boost/functional/hash.hpp> #include <iostream> #include <sstream> #include "core/sstring.hh" #include "core/shared_ptr.hh" #include "utils/UUID.hh" #include "net/byteorder.hh" #include "db_clock.hh" namespace cql3 { class cql3_type; } // FIXME: should be int8_t using bytes = basic_sstring<char, uint32_t, 31>; using bytes_view = std::experimental::string_view; using bytes_opt = std::experimental::optional<bytes>; using sstring_view = std::experimental::string_view; sstring to_hex(const bytes& b); sstring to_hex(const bytes_opt& b); std::ostream& operator<<(std::ostream& os, const bytes& b); using object_opt = std::experimental::optional<boost::any>; class marshal_exception : public std::exception { sstring _why; public: marshal_exception() : _why("marshalling error") {} marshal_exception(sstring why) : _why(sstring("marshaling error: ") + why) {} virtual const char* why() const { return _why.c_str(); } }; struct runtime_exception : public std::exception { sstring _why; public: runtime_exception(sstring why) : _why(sstring("runtime error: ") + why) {} virtual const char* why() const { return _why.c_str(); } }; inline int32_t compare_unsigned(bytes_view v1, bytes_view v2) { auto n = memcmp(v1.begin(), v2.begin(), std::min(v1.size(), v2.size())); if (n) { return n; } return (int32_t) (v1.size() - v2.size()); } class abstract_type { sstring _name; public: abstract_type(sstring name) : _name(name) {} virtual ~abstract_type() {} virtual void serialize(const boost::any& value, std::ostream& out) = 0; virtual bool less(bytes_view v1, bytes_view v2) = 0; virtual size_t hash(bytes_view v) = 0; virtual bool equal(bytes_view v1, bytes_view v2) { if (is_byte_order_equal()) { return compare_unsigned(v1, v2) == 0; } return compare(v1, v2) == 0; } virtual int32_t compare(bytes_view v1, bytes_view v2) { if (less(v1, v2)) { return -1; } else if (less(v2, v1)) { return 1; } else { return 0; } } virtual object_opt deserialize(bytes_view v) = 0; virtual void validate(const bytes& v) { // FIXME } virtual void validate_collection_member(const bytes& v, const bytes& collection_name) { validate(v); } virtual bool is_compatible_with(abstract_type& previous) { // FIXME abort(); return false; } /* * Types which are wrappers over other types should override this. * For example the reversed_type returns the type it is reversing. */ virtual abstract_type& underlying_type() { return *this; } /** * Returns true if values of the other AbstractType can be read and "reasonably" interpreted by the this * AbstractType. Note that this is a weaker version of isCompatibleWith, as it does not require that both type * compare values the same way. * * The restriction on the other type being "reasonably" interpreted is to prevent, for example, IntegerType from * being compatible with all other types. Even though any byte string is a valid IntegerType value, it doesn't * necessarily make sense to interpret a UUID or a UTF8 string as an integer. * * Note that a type should be compatible with at least itself. */ bool is_value_compatible_with(abstract_type& other) { return is_value_compatible_with_internal(other.underlying_type()); } protected: /** * Needed to handle ReversedType in value-compatibility checks. Subclasses should implement this instead of * is_value_compatible_with(). */ virtual bool is_value_compatible_with_internal(abstract_type& other) { return is_compatible_with(other); } public: virtual object_opt compose(const bytes& v) { return deserialize(v); } bytes decompose(const boost::any& value) { // FIXME: optimize std::ostringstream oss; serialize(value, oss); auto s = oss.str(); return bytes(s.data(), s.size()); } sstring name() const { return _name; } virtual bool is_byte_order_comparable() const { return false; } /** * When returns true then equal values have the same byte representation and if byte * representation is different, the values are not equal. * * When returns false, nothing can be inferred. */ virtual bool is_byte_order_equal() const { // If we're byte order comparable, then we must also be byte order equal. return is_byte_order_comparable(); } virtual sstring get_string(const bytes& b) { validate(b); return to_string(b); } virtual sstring to_string(const bytes& b) = 0; virtual bytes from_string(sstring_view text) = 0; virtual bool is_counter() { return false; } virtual bool is_collection() { return false; } virtual bool is_multi_cell() { return false; } virtual ::shared_ptr<cql3::cql3_type> as_cql3_type() = 0; }; using data_type = shared_ptr<abstract_type>; inline size_t hash_value(const shared_ptr<abstract_type>& x) { return std::hash<abstract_type*>()(x.get()); } template <typename Type> shared_ptr<abstract_type> data_type_for(); class serialized_compare { data_type _type; public: serialized_compare(data_type type) : _type(type) {} bool operator()(const bytes& v1, const bytes& v2) const { return _type->less(v1, v2); } }; using key_compare = serialized_compare; // FIXME: add missing types extern thread_local shared_ptr<abstract_type> int32_type; extern thread_local shared_ptr<abstract_type> long_type; extern thread_local shared_ptr<abstract_type> ascii_type; extern thread_local shared_ptr<abstract_type> bytes_type; extern thread_local shared_ptr<abstract_type> utf8_type; extern thread_local shared_ptr<abstract_type> boolean_type; extern thread_local shared_ptr<abstract_type> date_type; extern thread_local shared_ptr<abstract_type> timeuuid_type; extern thread_local shared_ptr<abstract_type> timestamp_type; extern thread_local shared_ptr<abstract_type> uuid_type; extern thread_local shared_ptr<abstract_type> inet_addr_type; template <> inline shared_ptr<abstract_type> data_type_for<int32_t>() { return int32_type; } template <> inline shared_ptr<abstract_type> data_type_for<int64_t>() { return long_type; } template <> inline shared_ptr<abstract_type> data_type_for<sstring>() { return utf8_type; } namespace std { template <> struct hash<shared_ptr<abstract_type>> : boost::hash<shared_ptr<abstract_type>> { }; } inline bytes to_bytes(const char* x) { return bytes(reinterpret_cast<const char*>(x), std::strlen(x)); } inline bytes to_bytes(const std::string& x) { return bytes(reinterpret_cast<const char*>(x.data()), x.size()); } inline bytes to_bytes(sstring_view x) { return bytes(x.begin(), x.size()); } inline bytes to_bytes(const sstring& x) { return bytes(reinterpret_cast<const char*>(x.c_str()), x.size()); } inline bytes to_bytes(const utils::UUID& uuid) { struct { uint64_t msb; uint64_t lsb; } tmp = { net::hton(uint64_t(uuid.get_most_significant_bits())), net::hton(uint64_t(uuid.get_least_significant_bits())) }; return bytes(reinterpret_cast<char*>(&tmp), 16); } // This follows java.util.Comparator // FIXME: Choose a better place than database.hh template <typename T> struct comparator { comparator() = default; comparator(std::function<int32_t (T& v1, T& v2)> fn) : _compare_fn(std::move(fn)) { } int32_t compare() { return _compare_fn(); } private: std::function<int32_t (T& v1, T& v2)> _compare_fn; }; inline bool less_unsigned(bytes_view v1, bytes_view v2) { return compare_unsigned(v1, v2) < 0; } class serialized_hash { private: data_type _type; public: serialized_hash(data_type type) : _type(type) {} size_t operator()(const bytes& v) const { return _type->hash(v); } }; class serialized_equal { private: data_type _type; public: serialized_equal(data_type type) : _type(type) {} bool operator()(const bytes& v1, const bytes& v2) const { return _type->equal(v1, v2); } }; template<typename Type> static inline typename Type::value_type deserialize_value(Type& t, bytes_view v) { return t.deserialize_value(v); } template<typename Type> static inline bytes serialize_value(Type& t, const typename Type::value_type& value) { std::ostringstream oss; t.serialize_value(value, oss); auto s = oss.str(); return bytes(s.data(), s.size()); } template<typename T> T read_simple(bytes_view& v) { if (v.size() < sizeof(T)) { throw marshal_exception(); } auto p = v.begin(); v.remove_prefix(sizeof(T)); return net::ntoh(*reinterpret_cast<const T*>(p)); } template<typename T> T read_simple_exactly(bytes_view& v) { if (v.size() != sizeof(T)) { throw marshal_exception(); } auto p = v.begin(); v.remove_prefix(sizeof(T)); return net::ntoh(*reinterpret_cast<const T*>(p)); } template<typename T> object_opt read_simple_opt(bytes_view& v) { if (v.empty()) { return {}; } if (v.size() != sizeof(T)) { throw marshal_exception(); } auto p = v.begin(); v.remove_prefix(sizeof(T)); return boost::any(net::ntoh(*reinterpret_cast<const T*>(p))); } <commit_msg>types: Fix read_simple*() variants to work for unaligned positions<commit_after>/* * Copyright (C) 2014 Cloudius Systems, Ltd. */ #pragma once #include <experimental/optional> #include <boost/any.hpp> #include <boost/functional/hash.hpp> #include <iostream> #include <sstream> #include "core/sstring.hh" #include "core/shared_ptr.hh" #include "utils/UUID.hh" #include "net/byteorder.hh" #include "db_clock.hh" namespace cql3 { class cql3_type; } // FIXME: should be int8_t using bytes = basic_sstring<char, uint32_t, 31>; using bytes_view = std::experimental::string_view; using bytes_opt = std::experimental::optional<bytes>; using sstring_view = std::experimental::string_view; sstring to_hex(const bytes& b); sstring to_hex(const bytes_opt& b); std::ostream& operator<<(std::ostream& os, const bytes& b); using object_opt = std::experimental::optional<boost::any>; class marshal_exception : public std::exception { sstring _why; public: marshal_exception() : _why("marshalling error") {} marshal_exception(sstring why) : _why(sstring("marshaling error: ") + why) {} virtual const char* why() const { return _why.c_str(); } }; struct runtime_exception : public std::exception { sstring _why; public: runtime_exception(sstring why) : _why(sstring("runtime error: ") + why) {} virtual const char* why() const { return _why.c_str(); } }; inline int32_t compare_unsigned(bytes_view v1, bytes_view v2) { auto n = memcmp(v1.begin(), v2.begin(), std::min(v1.size(), v2.size())); if (n) { return n; } return (int32_t) (v1.size() - v2.size()); } class abstract_type { sstring _name; public: abstract_type(sstring name) : _name(name) {} virtual ~abstract_type() {} virtual void serialize(const boost::any& value, std::ostream& out) = 0; virtual bool less(bytes_view v1, bytes_view v2) = 0; virtual size_t hash(bytes_view v) = 0; virtual bool equal(bytes_view v1, bytes_view v2) { if (is_byte_order_equal()) { return compare_unsigned(v1, v2) == 0; } return compare(v1, v2) == 0; } virtual int32_t compare(bytes_view v1, bytes_view v2) { if (less(v1, v2)) { return -1; } else if (less(v2, v1)) { return 1; } else { return 0; } } virtual object_opt deserialize(bytes_view v) = 0; virtual void validate(const bytes& v) { // FIXME } virtual void validate_collection_member(const bytes& v, const bytes& collection_name) { validate(v); } virtual bool is_compatible_with(abstract_type& previous) { // FIXME abort(); return false; } /* * Types which are wrappers over other types should override this. * For example the reversed_type returns the type it is reversing. */ virtual abstract_type& underlying_type() { return *this; } /** * Returns true if values of the other AbstractType can be read and "reasonably" interpreted by the this * AbstractType. Note that this is a weaker version of isCompatibleWith, as it does not require that both type * compare values the same way. * * The restriction on the other type being "reasonably" interpreted is to prevent, for example, IntegerType from * being compatible with all other types. Even though any byte string is a valid IntegerType value, it doesn't * necessarily make sense to interpret a UUID or a UTF8 string as an integer. * * Note that a type should be compatible with at least itself. */ bool is_value_compatible_with(abstract_type& other) { return is_value_compatible_with_internal(other.underlying_type()); } protected: /** * Needed to handle ReversedType in value-compatibility checks. Subclasses should implement this instead of * is_value_compatible_with(). */ virtual bool is_value_compatible_with_internal(abstract_type& other) { return is_compatible_with(other); } public: virtual object_opt compose(const bytes& v) { return deserialize(v); } bytes decompose(const boost::any& value) { // FIXME: optimize std::ostringstream oss; serialize(value, oss); auto s = oss.str(); return bytes(s.data(), s.size()); } sstring name() const { return _name; } virtual bool is_byte_order_comparable() const { return false; } /** * When returns true then equal values have the same byte representation and if byte * representation is different, the values are not equal. * * When returns false, nothing can be inferred. */ virtual bool is_byte_order_equal() const { // If we're byte order comparable, then we must also be byte order equal. return is_byte_order_comparable(); } virtual sstring get_string(const bytes& b) { validate(b); return to_string(b); } virtual sstring to_string(const bytes& b) = 0; virtual bytes from_string(sstring_view text) = 0; virtual bool is_counter() { return false; } virtual bool is_collection() { return false; } virtual bool is_multi_cell() { return false; } virtual ::shared_ptr<cql3::cql3_type> as_cql3_type() = 0; }; using data_type = shared_ptr<abstract_type>; inline size_t hash_value(const shared_ptr<abstract_type>& x) { return std::hash<abstract_type*>()(x.get()); } template <typename Type> shared_ptr<abstract_type> data_type_for(); class serialized_compare { data_type _type; public: serialized_compare(data_type type) : _type(type) {} bool operator()(const bytes& v1, const bytes& v2) const { return _type->less(v1, v2); } }; using key_compare = serialized_compare; // FIXME: add missing types extern thread_local shared_ptr<abstract_type> int32_type; extern thread_local shared_ptr<abstract_type> long_type; extern thread_local shared_ptr<abstract_type> ascii_type; extern thread_local shared_ptr<abstract_type> bytes_type; extern thread_local shared_ptr<abstract_type> utf8_type; extern thread_local shared_ptr<abstract_type> boolean_type; extern thread_local shared_ptr<abstract_type> date_type; extern thread_local shared_ptr<abstract_type> timeuuid_type; extern thread_local shared_ptr<abstract_type> timestamp_type; extern thread_local shared_ptr<abstract_type> uuid_type; extern thread_local shared_ptr<abstract_type> inet_addr_type; template <> inline shared_ptr<abstract_type> data_type_for<int32_t>() { return int32_type; } template <> inline shared_ptr<abstract_type> data_type_for<int64_t>() { return long_type; } template <> inline shared_ptr<abstract_type> data_type_for<sstring>() { return utf8_type; } namespace std { template <> struct hash<shared_ptr<abstract_type>> : boost::hash<shared_ptr<abstract_type>> { }; } inline bytes to_bytes(const char* x) { return bytes(reinterpret_cast<const char*>(x), std::strlen(x)); } inline bytes to_bytes(const std::string& x) { return bytes(reinterpret_cast<const char*>(x.data()), x.size()); } inline bytes to_bytes(sstring_view x) { return bytes(x.begin(), x.size()); } inline bytes to_bytes(const sstring& x) { return bytes(reinterpret_cast<const char*>(x.c_str()), x.size()); } inline bytes to_bytes(const utils::UUID& uuid) { struct { uint64_t msb; uint64_t lsb; } tmp = { net::hton(uint64_t(uuid.get_most_significant_bits())), net::hton(uint64_t(uuid.get_least_significant_bits())) }; return bytes(reinterpret_cast<char*>(&tmp), 16); } // This follows java.util.Comparator // FIXME: Choose a better place than database.hh template <typename T> struct comparator { comparator() = default; comparator(std::function<int32_t (T& v1, T& v2)> fn) : _compare_fn(std::move(fn)) { } int32_t compare() { return _compare_fn(); } private: std::function<int32_t (T& v1, T& v2)> _compare_fn; }; inline bool less_unsigned(bytes_view v1, bytes_view v2) { return compare_unsigned(v1, v2) < 0; } class serialized_hash { private: data_type _type; public: serialized_hash(data_type type) : _type(type) {} size_t operator()(const bytes& v) const { return _type->hash(v); } }; class serialized_equal { private: data_type _type; public: serialized_equal(data_type type) : _type(type) {} bool operator()(const bytes& v1, const bytes& v2) const { return _type->equal(v1, v2); } }; template<typename Type> static inline typename Type::value_type deserialize_value(Type& t, bytes_view v) { return t.deserialize_value(v); } template<typename Type> static inline bytes serialize_value(Type& t, const typename Type::value_type& value) { std::ostringstream oss; t.serialize_value(value, oss); auto s = oss.str(); return bytes(s.data(), s.size()); } template<typename T> T read_simple(bytes_view& v) { if (v.size() < sizeof(T)) { throw marshal_exception(); } auto p = v.begin(); v.remove_prefix(sizeof(T)); return net::ntoh(*reinterpret_cast<const net::packed<T>*>(p)); } template<typename T> T read_simple_exactly(bytes_view& v) { if (v.size() != sizeof(T)) { throw marshal_exception(); } auto p = v.begin(); v.remove_prefix(sizeof(T)); return net::ntoh(*reinterpret_cast<const net::packed<T>*>(p)); } template<typename T> object_opt read_simple_opt(bytes_view& v) { if (v.empty()) { return {}; } if (v.size() != sizeof(T)) { throw marshal_exception(); } auto p = v.begin(); v.remove_prefix(sizeof(T)); return boost::any(net::ntoh(*reinterpret_cast<const net::packed<T>*>(p))); } <|endoftext|>
<commit_before><commit_msg>Service Directory: fail to listen if one of the endpoints failed to bind<commit_after><|endoftext|>
<commit_before>/****************************************************************************** * Copyright (C) 2015 Felix Rohrbach <kde@fxrh.de> * * 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 "user.h" #include "connection.h" #include "room.h" #include "avatar.h" #include "events/event.h" #include "events/roommemberevent.h" #include "jobs/setroomstatejob.h" #include "jobs/generated/profile.h" #include "jobs/generated/content-repo.h" #include <QtCore/QTimer> #include <QtCore/QRegularExpression> #include <QtCore/QPointer> #include <QtCore/QStringBuilder> #include <QtCore/QElapsedTimer> #include <functional> #include <unordered_set> using namespace QMatrixClient; using namespace std::placeholders; using std::move; class User::Private { public: static Avatar* makeAvatar(QUrl url); Private(QString userId, Connection* connection) : userId(move(userId)), connection(connection) { } ~Private() { for (auto a: otherAvatars) delete a; } QString userId; Connection* connection; QString mostUsedName; QString bridged; const std::unique_ptr<Avatar> mostUsedAvatar { makeAvatar({}) }; QMultiHash<QString, const Room*> otherNames; QHash<QUrl, Avatar*> otherAvatars; QMultiHash<QUrl, const Room*> avatarsToRooms; mutable int totalRooms = 0; QString nameForRoom(const Room* r, const QString& hint = {}) const; void setNameForRoom(const Room* r, QString newName, QString oldName); QUrl avatarUrlForRoom(const Room* r, const QUrl& hint = {}) const; void setAvatarForRoom(const Room* r, const QUrl& newUrl, const QUrl& oldUrl); void setAvatarOnServer(QString contentUri, User* q); }; Avatar* User::Private::makeAvatar(QUrl url) { static const QIcon icon { QIcon::fromTheme(QStringLiteral("user-available")) }; return new Avatar(move(url), icon); } QString User::Private::nameForRoom(const Room* r, const QString& hint) const { // If the hint is accurate, this function is O(1) instead of O(n) if (hint == mostUsedName || otherNames.contains(hint, r)) return hint; return otherNames.key(r, mostUsedName); } static constexpr int MIN_JOINED_ROOMS_TO_LOG = 20; void User::Private::setNameForRoom(const Room* r, QString newName, QString oldName) { Q_ASSERT(oldName != newName); Q_ASSERT(oldName == mostUsedName || otherNames.contains(oldName, r)); if (totalRooms < 2) { Q_ASSERT_X(totalRooms > 0 && otherNames.empty(), __FUNCTION__, "Internal structures inconsistency"); mostUsedName = move(newName); return; } otherNames.remove(oldName, r); if (newName != mostUsedName) { // Check if the newName is about to become most used. if (otherNames.count(newName) >= totalRooms - otherNames.size()) { Q_ASSERT(totalRooms > 1); QElapsedTimer et; if (totalRooms > MIN_JOINED_ROOMS_TO_LOG) { qCDebug(MAIN) << "Switching the most used name of user" << userId << "from" << mostUsedName << "to" << newName; qCDebug(MAIN) << "The user is in" << totalRooms << "rooms"; et.start(); } for (auto* r1: connection->roomMap()) if (nameForRoom(r1) == mostUsedName) otherNames.insert(mostUsedName, r1); mostUsedName = newName; otherNames.remove(newName); if (totalRooms > MIN_JOINED_ROOMS_TO_LOG) qCDebug(PROFILER) << et << "to switch the most used name"; } else otherNames.insert(newName, r); } } QUrl User::Private::avatarUrlForRoom(const Room* r, const QUrl& hint) const { // If the hint is accurate, this function is O(1) instead of O(n) if (hint == mostUsedAvatar->url() || avatarsToRooms.contains(hint, r)) return hint; auto it = std::find(avatarsToRooms.begin(), avatarsToRooms.end(), r); return it == avatarsToRooms.end() ? mostUsedAvatar->url() : it.key(); } void User::Private::setAvatarForRoom(const Room* r, const QUrl& newUrl, const QUrl& oldUrl) { Q_ASSERT(oldUrl != newUrl); Q_ASSERT(oldUrl == mostUsedAvatar->url() || avatarsToRooms.contains(oldUrl, r)); if (totalRooms < 2) { Q_ASSERT_X(totalRooms > 0 && otherAvatars.empty(), __FUNCTION__, "Internal structures inconsistency"); mostUsedAvatar->updateUrl(newUrl); return; } avatarsToRooms.remove(oldUrl, r); if (!avatarsToRooms.contains(oldUrl)) { delete otherAvatars.value(oldUrl); otherAvatars.remove(oldUrl); } if (newUrl != mostUsedAvatar->url()) { // Check if the new avatar is about to become most used. if (avatarsToRooms.count(newUrl) >= totalRooms - avatarsToRooms.size()) { QElapsedTimer et; if (totalRooms > MIN_JOINED_ROOMS_TO_LOG) { qCDebug(MAIN) << "Switching the most used avatar of user" << userId << "from" << mostUsedAvatar->url().toDisplayString() << "to" << newUrl.toDisplayString(); et.start(); } avatarsToRooms.remove(newUrl); auto* nextMostUsed = otherAvatars.take(newUrl); std::swap(*mostUsedAvatar, *nextMostUsed); otherAvatars.insert(nextMostUsed->url(), nextMostUsed); for (const auto* r1: connection->roomMap()) if (avatarUrlForRoom(r1) == nextMostUsed->url()) avatarsToRooms.insert(nextMostUsed->url(), r1); if (totalRooms > MIN_JOINED_ROOMS_TO_LOG) qCDebug(PROFILER) << et << "to switch the most used avatar"; } else { otherAvatars.insert(newUrl, makeAvatar(newUrl)); avatarsToRooms.insert(newUrl, r); } } } User::User(QString userId, Connection* connection) : QObject(connection), d(new Private(move(userId), connection)) { setObjectName(userId); } User::~User() = default; QString User::id() const { return d->userId; } bool User::isGuest() const { Q_ASSERT(!d->userId.isEmpty() && d->userId.startsWith('@')); auto it = std::find_if_not(d->userId.begin() + 1, d->userId.end(), [] (QChar c) { return c.isDigit(); }); Q_ASSERT(it != d->userId.end()); return *it == ':'; } QString User::name(const Room* room) const { return d->nameForRoom(room); } void User::updateName(const QString& newName, const Room* room) { updateName(newName, d->nameForRoom(room), room); } void User::updateName(const QString& newName, const QString& oldName, const Room* room) { Q_ASSERT(oldName == d->mostUsedName || d->otherNames.contains(oldName, room)); if (newName != oldName) { emit nameAboutToChange(newName, oldName, room); d->setNameForRoom(room, newName, oldName); setObjectName(displayname()); emit nameChanged(newName, oldName, room); } } void User::updateAvatarUrl(const QUrl& newUrl, const QUrl& oldUrl, const Room* room) { Q_ASSERT(oldUrl == d->mostUsedAvatar->url() || d->avatarsToRooms.contains(oldUrl, room)); if (newUrl != oldUrl) { d->setAvatarForRoom(room, newUrl, oldUrl); setObjectName(displayname()); emit avatarChanged(this, room); } } void User::rename(const QString& newName) { auto job = d->connection->callApi<SetDisplayNameJob>(id(), newName); connect(job, &BaseJob::success, this, [=] { updateName(newName); }); } void User::rename(const QString& newName, const Room* r) { if (!r) { qCWarning(MAIN) << "Passing a null room to two-argument User::rename()" "is incorrect; client developer, please fix it"; rename(newName); } Q_ASSERT_X(r->memberJoinState(this) == JoinState::Join, __FUNCTION__, "Attempt to rename a user that's not a room member"); MemberEventContent evtC; evtC.displayName = newName; auto job = d->connection->callApi<SetRoomStateJob>( r->id(), id(), RoomMemberEvent(move(evtC))); connect(job, &BaseJob::success, this, [=] { updateName(newName, r); }); } bool User::setAvatar(const QString& fileName) { return avatarObject().upload(d->connection, fileName, std::bind(&Private::setAvatarOnServer, d.data(), _1, this)); } bool User::setAvatar(QIODevice* source) { return avatarObject().upload(d->connection, source, std::bind(&Private::setAvatarOnServer, d.data(), _1, this)); } void User::Private::setAvatarOnServer(QString contentUri, User* q) { auto* j = connection->callApi<SetAvatarUrlJob>(userId, contentUri); connect(j, &BaseJob::success, q, [=] { q->updateAvatarUrl(contentUri, avatarUrlForRoom(nullptr)); }); } QString User::displayname(const Room* room) const { auto name = d->nameForRoom(room); return name.isEmpty() ? d->userId : room ? room->roomMembername(name) : name; } QString User::fullName(const Room* room) const { auto name = d->nameForRoom(room); return name.isEmpty() ? d->userId : name % " (" % d->userId % ')'; } QString User::bridged() const { return d->bridged; } const Avatar& User::avatarObject(const Room* room) const { return *d->otherAvatars.value(d->avatarUrlForRoom(room), d->mostUsedAvatar.get()); } QImage User::avatar(int dimension, const Room* room) { return avatar(dimension, dimension, room); } QImage User::avatar(int width, int height, const Room* room) { return avatar(width, height, room, []{}); } QImage User::avatar(int width, int height, const Room* room, Avatar::get_callback_t callback) { return avatarObject(room).get(d->connection, width, height, [=] { emit avatarChanged(this, room); callback(); }); } QString User::avatarMediaId(const Room* room) const { return avatarObject(room).mediaId(); } QUrl User::avatarUrl(const Room* room) const { return avatarObject(room).url(); } void User::processEvent(RoomMemberEvent* event, const Room* room) { if (event->membership() != MembershipType::Invite && event->membership() != MembershipType::Join) return; auto aboutToEnter = room->memberJoinState(this) == JoinState::Leave && (event->membership() == MembershipType::Join || event->membership() == MembershipType::Invite); if (aboutToEnter) ++d->totalRooms; auto newName = event->displayName(); // `bridged` value uses the same notification signal as the name; // it is assumed that first setting of the bridge occurs together with // the first setting of the name, and further bridge updates are // exceptionally rare (the only reasonable case being that the bridge // changes the naming convention). For the same reason room-specific // bridge tags are not supported at all. QRegularExpression reSuffix(" \\((IRC|Gitter|Telegram)\\)$"); auto match = reSuffix.match(newName); if (match.hasMatch()) { if (d->bridged != match.captured(1)) { if (!d->bridged.isEmpty()) qCWarning(MAIN) << "Bridge for user" << id() << "changed:" << d->bridged << "->" << match.captured(1); d->bridged = match.captured(1); } newName.truncate(match.capturedStart(0)); } if (event->prevContent()) { // FIXME: the hint doesn't work for bridged users auto oldNameHint = d->nameForRoom(room, event->prevContent()->displayName); updateName(event->displayName(), oldNameHint, room); updateAvatarUrl(event->avatarUrl(), d->avatarUrlForRoom(room, event->prevContent()->avatarUrl), room); } else { updateName(event->displayName(), room); updateAvatarUrl(event->avatarUrl(), d->avatarUrlForRoom(room), room); } } <commit_msg>User: Streamline Avatar storage<commit_after>/****************************************************************************** * Copyright (C) 2015 Felix Rohrbach <kde@fxrh.de> * * 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 "user.h" #include "connection.h" #include "room.h" #include "avatar.h" #include "events/event.h" #include "events/roommemberevent.h" #include "jobs/setroomstatejob.h" #include "jobs/generated/profile.h" #include "jobs/generated/content-repo.h" #include <QtCore/QTimer> #include <QtCore/QRegularExpression> #include <QtCore/QPointer> #include <QtCore/QStringBuilder> #include <QtCore/QElapsedTimer> #include <functional> using namespace QMatrixClient; using namespace std::placeholders; using std::move; class User::Private { public: static Avatar makeAvatar(QUrl url) { static const QIcon icon { QIcon::fromTheme(QStringLiteral("user-available")) }; return Avatar(move(url), icon); } Private(QString userId, Connection* connection) : userId(move(userId)), connection(connection) { } QString userId; Connection* connection; QString bridged; QString mostUsedName; QMultiHash<QString, const Room*> otherNames; Avatar mostUsedAvatar { makeAvatar({}) }; std::vector<Avatar> otherAvatars; auto otherAvatar(QUrl url) { return std::find_if(otherAvatars.begin(), otherAvatars.end(), [&url] (const auto& av) { return av.url() == url; }); } QMultiHash<QUrl, const Room*> avatarsToRooms; mutable int totalRooms = 0; QString nameForRoom(const Room* r, const QString& hint = {}) const; void setNameForRoom(const Room* r, QString newName, QString oldName); QUrl avatarUrlForRoom(const Room* r, const QUrl& hint = {}) const; void setAvatarForRoom(const Room* r, const QUrl& newUrl, const QUrl& oldUrl); void setAvatarOnServer(QString contentUri, User* q); }; QString User::Private::nameForRoom(const Room* r, const QString& hint) const { // If the hint is accurate, this function is O(1) instead of O(n) if (hint == mostUsedName || otherNames.contains(hint, r)) return hint; return otherNames.key(r, mostUsedName); } static constexpr int MIN_JOINED_ROOMS_TO_LOG = 20; void User::Private::setNameForRoom(const Room* r, QString newName, QString oldName) { Q_ASSERT(oldName != newName); Q_ASSERT(oldName == mostUsedName || otherNames.contains(oldName, r)); if (totalRooms < 2) { Q_ASSERT_X(totalRooms > 0 && otherNames.empty(), __FUNCTION__, "Internal structures inconsistency"); mostUsedName = move(newName); return; } otherNames.remove(oldName, r); if (newName != mostUsedName) { // Check if the newName is about to become most used. if (otherNames.count(newName) >= totalRooms - otherNames.size()) { Q_ASSERT(totalRooms > 1); QElapsedTimer et; if (totalRooms > MIN_JOINED_ROOMS_TO_LOG) { qCDebug(MAIN) << "Switching the most used name of user" << userId << "from" << mostUsedName << "to" << newName; qCDebug(MAIN) << "The user is in" << totalRooms << "rooms"; et.start(); } for (auto* r1: connection->roomMap()) if (nameForRoom(r1) == mostUsedName) otherNames.insert(mostUsedName, r1); mostUsedName = newName; otherNames.remove(newName); if (totalRooms > MIN_JOINED_ROOMS_TO_LOG) qCDebug(PROFILER) << et << "to switch the most used name"; } else otherNames.insert(newName, r); } } QUrl User::Private::avatarUrlForRoom(const Room* r, const QUrl& hint) const { // If the hint is accurate, this function is O(1) instead of O(n) if (hint == mostUsedAvatar.url() || avatarsToRooms.contains(hint, r)) return hint; auto it = std::find(avatarsToRooms.begin(), avatarsToRooms.end(), r); return it == avatarsToRooms.end() ? mostUsedAvatar.url() : it.key(); } void User::Private::setAvatarForRoom(const Room* r, const QUrl& newUrl, const QUrl& oldUrl) { Q_ASSERT(oldUrl != newUrl); Q_ASSERT(oldUrl == mostUsedAvatar.url() || avatarsToRooms.contains(oldUrl, r)); if (totalRooms < 2) { Q_ASSERT_X(totalRooms > 0 && otherAvatars.empty(), __FUNCTION__, "Internal structures inconsistency"); mostUsedAvatar.updateUrl(newUrl); return; } avatarsToRooms.remove(oldUrl, r); if (!avatarsToRooms.contains(oldUrl)) { auto it = otherAvatar(oldUrl); if (it != otherAvatars.end()) otherAvatars.erase(it); } if (newUrl != mostUsedAvatar.url()) { // Check if the new avatar is about to become most used. if (avatarsToRooms.count(newUrl) >= totalRooms - avatarsToRooms.size()) { QElapsedTimer et; if (totalRooms > MIN_JOINED_ROOMS_TO_LOG) { qCDebug(MAIN) << "Switching the most used avatar of user" << userId << "from" << mostUsedAvatar.url().toDisplayString() << "to" << newUrl.toDisplayString(); et.start(); } avatarsToRooms.remove(newUrl); auto nextMostUsedIt = otherAvatar(newUrl); Q_ASSERT(nextMostUsedIt != otherAvatars.end()); std::swap(mostUsedAvatar, *nextMostUsedIt); for (const auto* r1: connection->roomMap()) if (avatarUrlForRoom(r1) == nextMostUsedIt->url()) avatarsToRooms.insert(nextMostUsedIt->url(), r1); if (totalRooms > MIN_JOINED_ROOMS_TO_LOG) qCDebug(PROFILER) << et << "to switch the most used avatar"; } else { if (otherAvatar(newUrl) == otherAvatars.end()) otherAvatars.emplace_back(makeAvatar(newUrl)); avatarsToRooms.insert(newUrl, r); } } } User::User(QString userId, Connection* connection) : QObject(connection), d(new Private(move(userId), connection)) { setObjectName(userId); } User::~User() = default; QString User::id() const { return d->userId; } bool User::isGuest() const { Q_ASSERT(!d->userId.isEmpty() && d->userId.startsWith('@')); auto it = std::find_if_not(d->userId.begin() + 1, d->userId.end(), [] (QChar c) { return c.isDigit(); }); Q_ASSERT(it != d->userId.end()); return *it == ':'; } QString User::name(const Room* room) const { return d->nameForRoom(room); } void User::updateName(const QString& newName, const Room* room) { updateName(newName, d->nameForRoom(room), room); } void User::updateName(const QString& newName, const QString& oldName, const Room* room) { Q_ASSERT(oldName == d->mostUsedName || d->otherNames.contains(oldName, room)); if (newName != oldName) { emit nameAboutToChange(newName, oldName, room); d->setNameForRoom(room, newName, oldName); setObjectName(displayname()); emit nameChanged(newName, oldName, room); } } void User::updateAvatarUrl(const QUrl& newUrl, const QUrl& oldUrl, const Room* room) { Q_ASSERT(oldUrl == d->mostUsedAvatar.url() || d->avatarsToRooms.contains(oldUrl, room)); if (newUrl != oldUrl) { d->setAvatarForRoom(room, newUrl, oldUrl); setObjectName(displayname()); emit avatarChanged(this, room); } } void User::rename(const QString& newName) { auto job = d->connection->callApi<SetDisplayNameJob>(id(), newName); connect(job, &BaseJob::success, this, [=] { updateName(newName); }); } void User::rename(const QString& newName, const Room* r) { if (!r) { qCWarning(MAIN) << "Passing a null room to two-argument User::rename()" "is incorrect; client developer, please fix it"; rename(newName); } Q_ASSERT_X(r->memberJoinState(this) == JoinState::Join, __FUNCTION__, "Attempt to rename a user that's not a room member"); MemberEventContent evtC; evtC.displayName = newName; auto job = d->connection->callApi<SetRoomStateJob>( r->id(), id(), RoomMemberEvent(move(evtC))); connect(job, &BaseJob::success, this, [=] { updateName(newName, r); }); } bool User::setAvatar(const QString& fileName) { return avatarObject().upload(d->connection, fileName, std::bind(&Private::setAvatarOnServer, d.data(), _1, this)); } bool User::setAvatar(QIODevice* source) { return avatarObject().upload(d->connection, source, std::bind(&Private::setAvatarOnServer, d.data(), _1, this)); } void User::Private::setAvatarOnServer(QString contentUri, User* q) { auto* j = connection->callApi<SetAvatarUrlJob>(userId, contentUri); connect(j, &BaseJob::success, q, [=] { q->updateAvatarUrl(contentUri, avatarUrlForRoom(nullptr)); }); } QString User::displayname(const Room* room) const { auto name = d->nameForRoom(room); return name.isEmpty() ? d->userId : room ? room->roomMembername(name) : name; } QString User::fullName(const Room* room) const { auto name = d->nameForRoom(room); return name.isEmpty() ? d->userId : name % " (" % d->userId % ')'; } QString User::bridged() const { return d->bridged; } const Avatar& User::avatarObject(const Room* room) const { auto it = d->otherAvatar(d->avatarUrlForRoom(room)); return it != d->otherAvatars.end() ? *it : d->mostUsedAvatar; } QImage User::avatar(int dimension, const Room* room) { return avatar(dimension, dimension, room); } QImage User::avatar(int width, int height, const Room* room) { return avatar(width, height, room, []{}); } QImage User::avatar(int width, int height, const Room* room, Avatar::get_callback_t callback) { return avatarObject(room).get(d->connection, width, height, [=] { emit avatarChanged(this, room); callback(); }); } QString User::avatarMediaId(const Room* room) const { return avatarObject(room).mediaId(); } QUrl User::avatarUrl(const Room* room) const { return avatarObject(room).url(); } void User::processEvent(RoomMemberEvent* event, const Room* room) { if (event->membership() != MembershipType::Invite && event->membership() != MembershipType::Join) return; auto aboutToEnter = room->memberJoinState(this) == JoinState::Leave && (event->membership() == MembershipType::Join || event->membership() == MembershipType::Invite); if (aboutToEnter) ++d->totalRooms; auto newName = event->displayName(); // `bridged` value uses the same notification signal as the name; // it is assumed that first setting of the bridge occurs together with // the first setting of the name, and further bridge updates are // exceptionally rare (the only reasonable case being that the bridge // changes the naming convention). For the same reason room-specific // bridge tags are not supported at all. QRegularExpression reSuffix(" \\((IRC|Gitter|Telegram)\\)$"); auto match = reSuffix.match(newName); if (match.hasMatch()) { if (d->bridged != match.captured(1)) { if (!d->bridged.isEmpty()) qCWarning(MAIN) << "Bridge for user" << id() << "changed:" << d->bridged << "->" << match.captured(1); d->bridged = match.captured(1); } newName.truncate(match.capturedStart(0)); } if (event->prevContent()) { // FIXME: the hint doesn't work for bridged users auto oldNameHint = d->nameForRoom(room, event->prevContent()->displayName); updateName(event->displayName(), oldNameHint, room); updateAvatarUrl(event->avatarUrl(), d->avatarUrlForRoom(room, event->prevContent()->avatarUrl), room); } else { updateName(event->displayName(), room); updateAvatarUrl(event->avatarUrl(), d->avatarUrlForRoom(room), room); } } <|endoftext|>
<commit_before>#include "util.h" #include <iostream> #include <cstdarg> #include <cstdio> using namespace std; static int verbose_flag = 0; static int debug_flag = 0; const int BUFSIZE(200); static char TEMPOUT[BUFSIZE]; void set_verbose_on() { verbose_flag = 1; } void set_debug_on() { debug_flag = 1; } void verbose(const char * fmt, ...) { va_list argp; va_start(argp, fmt); vsnprintf(TEMPOUT, sizeof(TEMPOUT), fmt, argp); va_end(argp); if ( verbose_flag ) { cerr << TEMPOUT << endl; } } void debug(const char * fmt, ...) { va_list argp; va_start(argp, fmt); vsnprintf(TEMPOUT, sizeof(TEMPOUT), fmt, argp); va_end(argp); if ( debug_flag ) { cerr << TEMPOUT << endl; } } <commit_msg>Turn on verbose when debugging<commit_after>#include "util.h" #include <iostream> #include <cstdarg> #include <cstdio> using namespace std; static int verbose_flag = 0; static int debug_flag = 0; const int BUFSIZE(200); static char TEMPOUT[BUFSIZE]; void set_verbose_on() { verbose_flag = 1; } void set_debug_on() { debug_flag = 1; verbose_flag = 1; } void verbose(const char * fmt, ...) { va_list argp; va_start(argp, fmt); vsnprintf(TEMPOUT, sizeof(TEMPOUT), fmt, argp); va_end(argp); if ( verbose_flag ) { cerr << TEMPOUT << endl; } } void debug(const char * fmt, ...) { va_list argp; va_start(argp, fmt); vsnprintf(TEMPOUT, sizeof(TEMPOUT), fmt, argp); va_end(argp); if ( debug_flag ) { cerr << TEMPOUT << endl; } } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: unopool.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2005-09-09 06:53:44 $ * * 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 _ISOLANG_HXX #include <tools/isolang.hxx> #endif #ifndef _COMPHELPER_PROPERTSETINFO_HXX_ #include <comphelper/propertysetinfo.hxx> #endif #ifndef _EEITEM_HXX #include <svx/eeitem.hxx> #endif #ifndef _SVX_UNOPOOL_HXX_ #include <svx/unopool.hxx> #endif #include "drawdoc.hxx" using namespace ::com::sun::star; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::beans; using namespace ::rtl; using namespace ::cppu; using namespace ::comphelper; LanguageType SdUnoGetLanguage( const lang::Locale& rLocale ) { // empty language -> LANGUAGE_SYSTEM if ( rLocale.Language.getLength() == 0 ) return LANGUAGE_SYSTEM; String aLangStr = rLocale.Language; String aCtryStr = rLocale.Country; // Variant is ignored LanguageType eRet = ConvertIsoNamesToLanguage( aLangStr, aCtryStr ); if ( eRet == LANGUAGE_NONE ) eRet = LANGUAGE_SYSTEM; //! or throw an exception? return eRet; } class SdUnoDrawPool : public SvxUnoDrawPool { public: SdUnoDrawPool( SdDrawDocument* pModel ) throw(); virtual ~SdUnoDrawPool() throw(); protected: virtual void putAny( SfxItemPool* pPool, const PropertyMapEntry* pEntry, const Any& rValue ) throw( UnknownPropertyException, IllegalArgumentException); private: SdDrawDocument* mpDrawModel; }; SdUnoDrawPool::SdUnoDrawPool( SdDrawDocument* pModel ) throw() : SvxUnoDrawPool( pModel ), mpDrawModel( pModel ) { } SdUnoDrawPool::~SdUnoDrawPool() throw() { } void SdUnoDrawPool::putAny( SfxItemPool* pPool, const comphelper::PropertyMapEntry* pEntry, const Any& rValue ) throw(UnknownPropertyException, IllegalArgumentException) { switch( pEntry->mnHandle ) { case EE_CHAR_LANGUAGE: case EE_CHAR_LANGUAGE_CJK: case EE_CHAR_LANGUAGE_CTL: { lang::Locale aLocale; if( rValue >>= aLocale ) mpDrawModel->SetLanguage( SdUnoGetLanguage( aLocale ), (const USHORT)pEntry->mnHandle ); } } SvxUnoDrawPool::putAny( pPool, pEntry, rValue ); } Reference< XInterface > SdUnoCreatePool( SdDrawDocument* pDrawModel ) { return (uno::XAggregation*)new SdUnoDrawPool( pDrawModel ); } <commit_msg>INTEGRATION: CWS internatiodel (1.3.110); FILE MERGED 2006/02/10 19:30:26 er 1.3.110.1: #i52115# move LangIDs and ISO conversion from tools to i18npool; introduce class MsLangId and libi18nisolang<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: unopool.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: vg $ $Date: 2006-04-07 15:01:57 $ * * 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 INCLUDED_I18NPOOL_MSLANGID_HXX #include <i18npool/mslangid.hxx> #endif #ifndef _COMPHELPER_PROPERTSETINFO_HXX_ #include <comphelper/propertysetinfo.hxx> #endif #ifndef _EEITEM_HXX #include <svx/eeitem.hxx> #endif #ifndef _SVX_UNOPOOL_HXX_ #include <svx/unopool.hxx> #endif #include "drawdoc.hxx" using namespace ::com::sun::star; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::beans; using namespace ::rtl; using namespace ::cppu; using namespace ::comphelper; LanguageType SdUnoGetLanguage( const lang::Locale& rLocale ) { // empty language -> LANGUAGE_SYSTEM if ( rLocale.Language.getLength() == 0 ) return LANGUAGE_SYSTEM; LanguageType eRet = MsLangId::convertLocaleToLanguage( rLocale ); if ( eRet == LANGUAGE_NONE ) eRet = LANGUAGE_SYSTEM; //! or throw an exception? return eRet; } class SdUnoDrawPool : public SvxUnoDrawPool { public: SdUnoDrawPool( SdDrawDocument* pModel ) throw(); virtual ~SdUnoDrawPool() throw(); protected: virtual void putAny( SfxItemPool* pPool, const PropertyMapEntry* pEntry, const Any& rValue ) throw( UnknownPropertyException, IllegalArgumentException); private: SdDrawDocument* mpDrawModel; }; SdUnoDrawPool::SdUnoDrawPool( SdDrawDocument* pModel ) throw() : SvxUnoDrawPool( pModel ), mpDrawModel( pModel ) { } SdUnoDrawPool::~SdUnoDrawPool() throw() { } void SdUnoDrawPool::putAny( SfxItemPool* pPool, const comphelper::PropertyMapEntry* pEntry, const Any& rValue ) throw(UnknownPropertyException, IllegalArgumentException) { switch( pEntry->mnHandle ) { case EE_CHAR_LANGUAGE: case EE_CHAR_LANGUAGE_CJK: case EE_CHAR_LANGUAGE_CTL: { lang::Locale aLocale; if( rValue >>= aLocale ) mpDrawModel->SetLanguage( SdUnoGetLanguage( aLocale ), (const USHORT)pEntry->mnHandle ); } } SvxUnoDrawPool::putAny( pPool, pEntry, rValue ); } Reference< XInterface > SdUnoCreatePool( SdDrawDocument* pDrawModel ) { return (uno::XAggregation*)new SdUnoDrawPool( pDrawModel ); } <|endoftext|>
<commit_before>#include <algorithm> #include "huffman.hpp" #ifndef ENCODER_HPP #define ENCODER_HPP namespace cpr { namespace huffman { class Encoder { public: explicit Encoder(std::vector<unsigned char> const& raw) : raw_(raw), frequencies_(find_frequencies(raw)), huff_tree_(frequencies_.cbegin(), frequencies_.cend()) { } std::vector<unsigned char> get_result() const { } private: const std::vector<unsigned char> raw_; const std::vector<Node<long>> frequencies_; const HuffmanTree<unsigned long> huff_tree_; std::vector<Node<long>> find_frequencies(std::vector<unsigned char> const& raw) const { std::vector<Node<unsigned long>> frequencies; for (auto ch : raw) { auto it = std::find_if(frequencies.begin(), frequencies.end(), [ch](Node<unsigned long> const& node){ return node.character_ == ch; }); if (it != frequencies.cend()) ++it->freq_; else frequencies.push_back(Node<unsigned long>(ch, 1)); } return frequencies; } std::vector<unsigned char> encode() const { } unsigned char uchar_to_code(unsigned char uchar)const { unsigned char code = 0; using Lambda = std::function < void(unsigned char, const Node<unsigned long>*) >; Lambda search = [=, &search, &code](unsigned char first_part, const Node<unsigned long>* node) { if (!node) return; if (uchar == node->character_) { code = first_part; return; } else { search((first_part << 1) + 0, node->left_); search((first_part << 1) + 1, node->right_); } }; search(0, this->huff_tree_.root()); return code; } }; } } #endif // !ENCODER_HPP <commit_msg>UT need to be added<commit_after>#include <algorithm> #include "huffman.hpp" #ifndef ENCODER_HPP #define ENCODER_HPP namespace cpr { namespace huffman { class Encoder { public: explicit Encoder(std::vector<unsigned char> const& raw) : raw_(raw), frequencies_(find_frequencies(raw)), huff_tree_(frequencies_.cbegin(), frequencies_.cend()) { } private: const std::vector<unsigned char> raw_; const std::vector<Node<long>> frequencies_; const HuffmanTree<unsigned long> huff_tree_; std::vector<Node<long>> find_frequencies(std::vector<unsigned char> const& raw) const { std::vector<Node<unsigned long>> frequencies; for (auto ch : raw) { auto it = std::find_if(frequencies.begin(), frequencies.end(), [ch](Node<unsigned long> const& node){ return node.character_ == ch; }); if (it != frequencies.cend()) ++it->freq_; else frequencies.push_back(Node<unsigned long>(ch, 1)); } return frequencies; } //std::vector<unsigned char> encode() const //{ //} // // not tested yet // unsigned char uchar_to_code(unsigned char uchar)const { unsigned char code = 0; using Lambda = std::function < void(unsigned char, const Node<unsigned long>*) >; Lambda search = [=, &search, &code](unsigned char first_part, const Node<unsigned long>* node) { if (!node) return; if (uchar == node->character_) { code = first_part; return; } else { search((first_part << 1) + 0, node->left_); search((first_part << 1) + 1, node->right_); } }; search(0, this->huff_tree_.root()); return code; } }; } } #endif // !ENCODER_HPP <|endoftext|>
<commit_before>#ifndef SIMDIFY_VEC3 #define SIMDIFY_VEC3 #include "simdify.hpp" #include "util/inline.hpp" #define INL SIMDIFY_FORCE_INLINE namespace simd { template <typename T> struct basic_vec3 { using mm_t = typename T::mm_t; using fp_t = typename T::fp_t; using bitmask_t = typename T::bitmask_t; T x, y, z; INL basic_vec3() = default; INL basic_vec3(const basic_vec3& other) = default; INL basic_vec3& operator=(const basic_vec3& other) = default; INL explicit basic_vec3(const T& t) : x(t), y(t), z(t) {} INL basic_vec3(const T& tx, const T& ty, const T& tz) : x(tx), y(ty), z(tz) {} template <typename S> INL explicit basic_vec3(const S& other) : x(other.x), y(other.y), z(other.z) {} template <typename S> INL basic_vec3& operator=(const S& other) { x = T(other.x); y = T(other.y); z = T(other.z); return *this; } // the value received by subscript behaves as a triple of floats x, y, z struct view { fp_t& x; fp_t& y; fp_t& z; INL view(basic_vec3& v, std::size_t i) : x(v.x.f[i]), y(v.y.f[i]), z(v.z.f[i]) {} template <typename S> INL view& operator=(const S& other) { x = other.x; y = other.y; z = other.z; return *this; } template <typename S> INL explicit operator S() const { return S(x, y, z); } }; INL view operator[](std::size_t i) { return view(*this, i); } INL const view operator[](std::size_t i) const { return view(*this, i); } }; template <typename T> INL const basic_vec3<T> cross(const basic_vec3<T>& l, const basic_vec3<T>& r) { return{ l.y*r.z - l.z*r.y, l.z*r.x - l.x*r.z, l.x*r.y - l.y*r.x }; } template <typename T> INL const T dot(const basic_vec3<T>& l, const basic_vec3<T>& r) { return l.x*r.x + l.y*r.y + l.z*r.z; } // bitwise not with lazy evaluation template <typename T> struct bitwise_not<basic_vec3<T>> { using tp = basic_vec3<T>; tp neg; INL explicit bitwise_not(const tp& r) : neg(r) {} INL operator const tp() const { return{ ~neg.x, ~neg.y, ~neg.z }; } }; template <typename T> INL const basic_vec3<T> operator&(const basic_vec3<T>& l, const basic_vec3<T>& r) { return{ l.x & r.x, l.y & r.y, l.z & r.z }; } INL const basic_vec3<T> operator|(const basic_vec3<T>& l, const basic_vec3<T>& r) { return{ l.x | r.x, l.y | r.y, l.z | r.z }; } INL const basic_vec3<T> operator^(const basic_vec3<T>& l, const basic_vec3<T>& r) { return{ l.x ^ r.x, l.y ^ r.y, l.z ^ r.z }; } INL const bitwise_not<basic_vec3<T>> operator~(const basic_vec3<T>& l) { return bitwise_not<basic_vec3<T>>(l); } INL const basic_vec3<T> operator<(const basic_vec3<T>& l, const basic_vec3<T>& r) { return{ l.x < r.x, l.y < r.y, l.z < r.z }; } INL const basic_vec3<T> operator>(const basic_vec3<T>& l, const basic_vec3<T>& r) { return{ l.x > r.x, l.y > r.y, l.z > r.z }; } INL const basic_vec3<T> operator<=(const basic_vec3<T>& l, const basic_vec3<T>& r) { return{ l.x <= r.x, l.y <= r.y, l.z <= r.z }; } INL const basic_vec3<T> operator>=(const basic_vec3<T>& l, const basic_vec3<T>& r) { return{ l.x >= r.x, l.y >= r.y, l.z >= r.z }; } INL const basic_vec3<T> operator==(const basic_vec3<T>& l, const basic_vec3<T>& r) { return{ l.x == r.x, l.y == r.y, l.z == r.z }; } INL const basic_vec3<T> operator!=(const basic_vec3<T>& l, const basic_vec3<T>& r) { return{ l.x != r.x, l.y != r.y, l.z != r.z }; } INL const basic_vec3<T> operator+(const basic_vec3<T>& l, const basic_vec3<T>& r) { return{ l.x + r.x, l.y + r.y, l.z + r.z }; } INL const basic_vec3<T> operator-(const basic_vec3<T>& l, const basic_vec3<T>& r) { return{ l.x - r.x, l.y - r.y, l.z - r.z }; } INL const basic_vec3<T> operator*(const basic_vec3<T>& l, const basic_vec3<T>& r) { return{ l.x * r.x, l.y * r.y, l.z * r.z }; } INL const basic_vec3<T> operator/(const basic_vec3<T>& l, const basic_vec3<T>& r) { return{ l.x / r.x, l.y / r.y, l.z / r.z }; } INL const basic_vec3<T> min(const basic_vec3<T>& l, const basic_vec3<T>& r) { return{ min(l.x, r.x), min(l.y, r.y), min(l.z, r.z) }; } INL const basic_vec3<T> max(const basic_vec3<T>& l, const basic_vec3<T>& r) { return{ max(l.x, r.x), max(l.y, r.y), max(l.z, r.z) }; } using vec3 = basic_vec3<simd_t>; } #undef INL #endif // SIMDIFY_VEC3<commit_msg>Strange incident: template <typename T> suddenly missing on like 20 occasions. Bad merge?<commit_after>#ifndef SIMDIFY_VEC3 #define SIMDIFY_VEC3 #include "simdify.hpp" #include "util/inline.hpp" #define INL SIMDIFY_FORCE_INLINE namespace simd { template <typename T> struct basic_vec3 { using mm_t = typename T::mm_t; using fp_t = typename T::fp_t; using bitmask_t = typename T::bitmask_t; T x, y, z; INL basic_vec3() = default; INL basic_vec3(const basic_vec3& other) = default; INL basic_vec3& operator=(const basic_vec3& other) = default; INL explicit basic_vec3(const T& t) : x(t), y(t), z(t) {} INL basic_vec3(const T& tx, const T& ty, const T& tz) : x(tx), y(ty), z(tz) {} template <typename S> INL explicit basic_vec3(const S& other) : x(other.x), y(other.y), z(other.z) {} template <typename S> INL basic_vec3& operator=(const S& other) { x = T(other.x); y = T(other.y); z = T(other.z); return *this; } // the value received by subscript behaves as a triple of floats x, y, z struct view { fp_t& x; fp_t& y; fp_t& z; INL view(basic_vec3& v, std::size_t i) : x(v.x.f[i]), y(v.y.f[i]), z(v.z.f[i]) {} template <typename S> INL view& operator=(const S& other) { x = other.x; y = other.y; z = other.z; return *this; } template <typename S> INL explicit operator S() const { return S(x, y, z); } }; INL view operator[](std::size_t i) { return view(*this, i); } INL const view operator[](std::size_t i) const { return view(*this, i); } }; template <typename T> INL const basic_vec3<T> cross(const basic_vec3<T>& l, const basic_vec3<T>& r) { return{ l.y*r.z - l.z*r.y, l.z*r.x - l.x*r.z, l.x*r.y - l.y*r.x }; } template <typename T> INL const T dot(const basic_vec3<T>& l, const basic_vec3<T>& r) { return l.x*r.x + l.y*r.y + l.z*r.z; } // bitwise not with lazy evaluation template <typename T> struct bitwise_not<basic_vec3<T>> { using tp = basic_vec3<T>; tp neg; INL explicit bitwise_not(const tp& r) : neg(r) {} INL operator const tp() const { return{ ~neg.x, ~neg.y, ~neg.z }; } }; template <typename T> INL const basic_vec3<T> operator&(const basic_vec3<T>& l, const basic_vec3<T>& r) { return{ l.x & r.x, l.y & r.y, l.z & r.z }; } template <typename T> INL const basic_vec3<T> operator|(const basic_vec3<T>& l, const basic_vec3<T>& r) { return{ l.x | r.x, l.y | r.y, l.z | r.z }; } template <typename T> INL const basic_vec3<T> operator^(const basic_vec3<T>& l, const basic_vec3<T>& r) { return{ l.x ^ r.x, l.y ^ r.y, l.z ^ r.z }; } template <typename T> INL const bitwise_not<basic_vec3<T>> operator~(const basic_vec3<T>& l) { return bitwise_not<basic_vec3<T>>(l); } template <typename T> INL const basic_vec3<T> operator<(const basic_vec3<T>& l, const basic_vec3<T>& r) { return{ l.x < r.x, l.y < r.y, l.z < r.z }; } template <typename T> INL const basic_vec3<T> operator>(const basic_vec3<T>& l, const basic_vec3<T>& r) { return{ l.x > r.x, l.y > r.y, l.z > r.z }; } template <typename T> INL const basic_vec3<T> operator<=(const basic_vec3<T>& l, const basic_vec3<T>& r) { return{ l.x <= r.x, l.y <= r.y, l.z <= r.z }; } template <typename T> INL const basic_vec3<T> operator>=(const basic_vec3<T>& l, const basic_vec3<T>& r) { return{ l.x >= r.x, l.y >= r.y, l.z >= r.z }; } template <typename T> INL const basic_vec3<T> operator==(const basic_vec3<T>& l, const basic_vec3<T>& r) { return{ l.x == r.x, l.y == r.y, l.z == r.z }; } template <typename T> INL const basic_vec3<T> operator!=(const basic_vec3<T>& l, const basic_vec3<T>& r) { return{ l.x != r.x, l.y != r.y, l.z != r.z }; } template <typename T> INL const basic_vec3<T> operator+(const basic_vec3<T>& l, const basic_vec3<T>& r) { return{ l.x + r.x, l.y + r.y, l.z + r.z }; } template <typename T> INL const basic_vec3<T> operator-(const basic_vec3<T>& l, const basic_vec3<T>& r) { return{ l.x - r.x, l.y - r.y, l.z - r.z }; } template <typename T> INL const basic_vec3<T> operator*(const basic_vec3<T>& l, const basic_vec3<T>& r) { return{ l.x * r.x, l.y * r.y, l.z * r.z }; } template <typename T> INL const basic_vec3<T> operator/(const basic_vec3<T>& l, const basic_vec3<T>& r) { return{ l.x / r.x, l.y / r.y, l.z / r.z }; } template <typename T> INL const basic_vec3<T> min(const basic_vec3<T>& l, const basic_vec3<T>& r) { return{ min(l.x, r.x), min(l.y, r.y), min(l.z, r.z) }; } template <typename T> INL const basic_vec3<T> max(const basic_vec3<T>& l, const basic_vec3<T>& r) { return{ max(l.x, r.x), max(l.y, r.y), max(l.z, r.z) }; } using vec3 = basic_vec3<simd_t>; } #undef INL #endif // SIMDIFY_VEC3<|endoftext|>
<commit_before>#include <stdexcept> #include <string> #include "function.hxx" function::operator double () const { return _fptr(_num, _args); } void function::set_param(unsigned idx, double val) { if (idx >= _num) throw std::out_of_range("Index out of range, > than " + std::to_string(_num)); _args[idx] = val; } std::pair<int, double *> function::params() const { return std::pair<int, double *> (_num, _args); } <commit_msg>Temporarily comment out std::to_string()<commit_after>#include <stdexcept> #include <string> #include "function.hxx" function::operator double () const { return _fptr(_num, _args); } void function::set_param(unsigned idx, double val) { if (idx >= _num) throw std::out_of_range("Index out of range, > than \n" // + std::to_string(_num) ); _args[idx] = val; } std::pair<int, double *> function::params() const { return std::pair<int, double *> (_num, _args); } <|endoftext|>
<commit_before>// This file is part of the dune-stuff project: // https://github.com/wwu-numerik/dune-stuff/ // Copyright holders: Rene Milk, Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_STUFF_FUNCTIONS_SPE10_HH #define DUNE_STUFF_FUNCTIONS_SPE10_HH #include <iostream> #include <memory> #include <dune/stuff/common/exceptions.hh> #include <dune/stuff/common/configuration.hh> #include <dune/stuff/common/color.hh> #include <dune/stuff/common/string.hh> #include "checkerboard.hh" namespace Dune { namespace Stuff { namespace Exceptions { class spe10_data_file_missing : public Dune::IOError {}; } // namespace Exceptions namespace Functions { // default, to allow for specialization template< class EntityImp, class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDim, int rangeDimCols = 1 > class Spe10Model1 { public: Spe10Model1() = delete; }; // class FunctionSpe10Model1 /** * \note For dimRange 1 we only read the Kx values from the file. */ template< class EntityImp, class DomainFieldImp, class RangeFieldImp > class Spe10Model1< EntityImp, DomainFieldImp, 2, RangeFieldImp, 1, 1 > : public Checkerboard< EntityImp, DomainFieldImp, 2, RangeFieldImp, 1, 1 > { typedef Checkerboard< EntityImp, DomainFieldImp, 2, RangeFieldImp, 1, 1 > BaseType; typedef Spe10Model1< EntityImp, DomainFieldImp, 2, RangeFieldImp, 1, 1 > ThisType; public: typedef typename BaseType::EntityType EntityType; typedef typename BaseType::LocalfunctionType LocalfunctionType; typedef typename BaseType::DomainFieldType DomainFieldType; static const int dimDomain = BaseType::dimDomain; typedef typename BaseType::DomainType DomainType; typedef typename BaseType::RangeFieldType RangeFieldType; static const int dimRange = BaseType::dimRange; typedef typename BaseType::RangeType RangeType; static std::string static_id() { return BaseType::static_id() + ".spe10.model1"; } private: static const size_t numXelements; static const size_t numYelements; static const size_t numZelements; static const RangeFieldType minValue; static const RangeFieldType maxValue; static std::vector< RangeType > read_values_from_file(const std::string& filename, const RangeFieldType& min, const RangeFieldType& max) { if (!(max > min)) DUNE_THROW(Dune::RangeError, "max (is " << max << ") has to be larger than min (is " << min << ")!"); const RangeFieldType scale = (max - min) / (maxValue - minValue); const RangeType shift = min - scale*minValue; // read all the data from the file std::ifstream datafile(filename); if (datafile.is_open()) { static const size_t entriesPerDim = numXelements*numYelements*numZelements; // create storage (there should be exactly 6000 values in the file, but we onyl read the first 2000) std::vector< RangeType > data(entriesPerDim, RangeFieldType(0)); double tmp = 0; size_t counter = 0; while (datafile >> tmp && counter < entriesPerDim) { data[counter] = (tmp * scale) + shift; ++counter; } datafile.close(); if (counter != entriesPerDim) DUNE_THROW(Dune::IOError, "wrong number of entries in '" << filename << "' (are " << counter << ", should be " << entriesPerDim << ")!"); return data; } else DUNE_THROW(Exceptions::spe10_data_file_missing, "could not open '" << filename << "'!"); } // ... read_values_from_file(...) public: static Common::Configuration default_config(const std::string sub_name = "") { Common::Configuration config; config["filename"] = "perm_case1.dat"; config["lower_left"] = "[0.0 0.0]"; config["upper_right"] = "[762.0 15.24]"; config["min_value"] = "0.001"; config["max_value"] = "998.915"; config["name"] = static_id(); if (sub_name.empty()) return config; else { Common::Configuration tmp; tmp.add(config, sub_name); return tmp; } } // ... default_config(...) static std::unique_ptr< ThisType > create(const Common::Configuration config = default_config(), const std::string sub_name = static_id()) { // get correct config const Common::Configuration cfg = config.has_sub(sub_name) ? config.sub(sub_name) : config; const Common::Configuration default_cfg = default_config(); // create return Common::make_unique< ThisType >( cfg.get("filename", default_cfg.get< std::string >("filename")), cfg.get("lower_left", default_cfg.get< std::vector< DomainFieldType > >("lower_left"), dimDomain), cfg.get("upper_right", default_cfg.get< std::vector< DomainFieldType > >("upper_right"), dimDomain), cfg.get("min_val", minValue), cfg.get("max_val", maxValue), cfg.get("name", default_cfg.get< std::string >("name"))); } // ... create(...) Spe10Model1(const std::string& filename, std::vector< DomainFieldType >&& lowerLeft, std::vector< DomainFieldType >&& upperRight, const RangeFieldType min = minValue, const RangeFieldType max = maxValue, const std::string nm = static_id()) : BaseType(std::move(lowerLeft), std::move(upperRight), {numXelements, numZelements}, read_values_from_file(filename, min, max), nm) {} virtual std::string type() const DS_OVERRIDE { return BaseType::static_id() + ".spe10.model1"; } virtual ThisType* copy() const DS_OVERRIDE { return new ThisType(*this); } }; // class Spe10Model1< ..., 2, ..., 1, 1 > /** * We read only the Kx values from file and scale the unit matrix. Thus we should be the same as the scalar variant. */ template< class EntityImp, class DomainFieldImp, class RangeFieldImp > class Spe10Model1< EntityImp, DomainFieldImp, 2, RangeFieldImp, 2, 2 > : public Checkerboard< EntityImp, DomainFieldImp, 2, RangeFieldImp, 2, 2 > { typedef Checkerboard< EntityImp, DomainFieldImp, 2, RangeFieldImp, 2, 2 > BaseType; typedef Spe10Model1< EntityImp, DomainFieldImp, 2, RangeFieldImp, 2, 2 > ThisType; public: typedef typename BaseType::EntityType EntityType; typedef typename BaseType::LocalfunctionType LocalfunctionType; typedef typename BaseType::DomainFieldType DomainFieldType; static const int dimDomain = BaseType::dimDomain; typedef typename BaseType::DomainType DomainType; typedef typename BaseType::RangeFieldType RangeFieldType; static const int dimRange = BaseType::dimRange; typedef typename BaseType::RangeType RangeType; static std::string static_id() { return BaseType::static_id() + ".spe10.model1"; } private: static const size_t numXelements; static const size_t numYelements; static const size_t numZelements; static const RangeFieldType minValue; static const RangeFieldType maxValue; static std::vector< RangeType > read_values_from_file(const std::string& filename, const RangeFieldType& min, const RangeFieldType& max) { if (!(max > min)) DUNE_THROW(Dune::RangeError, "max (is " << max << ") has to be larger than min (is " << min << ")!"); const RangeFieldType scale = (max - min) / (maxValue - minValue); const RangeFieldType shift = min - scale*minValue; // read all the data from the file std::ifstream datafile(filename); if (datafile.is_open()) { static const size_t entriesPerDim = numXelements*numYelements*numZelements; // create storage (there should be exactly 6000 values in the file, but we onyl read the first 2000) RangeType unit_matrix(0.0); for (size_t dd = 0; dd < dimDomain; ++dd) unit_matrix[dd][dd] = 1.0; std::vector< RangeType > data(entriesPerDim, unit_matrix); double tmp = 0; size_t counter = 0; while (datafile >> tmp && counter < entriesPerDim) { data[counter] *= (tmp * scale) + shift; ++counter; } datafile.close(); if (counter != entriesPerDim) DUNE_THROW(Dune::IOError, "wrong number of entries in '" << filename << "' (are " << counter << ", should be " << entriesPerDim << ")!"); return data; } else DUNE_THROW(Exceptions::spe10_data_file_missing, "could not open '" << filename << "'!"); } // ... read_values_from_file(...) public: static Common::Configuration default_config(const std::string sub_name = "") { Common::Configuration config; config["filename"] = "perm_case1.dat"; config["lower_left"] = "[0.0 0.0]"; config["upper_right"] = "[762.0 15.24]"; config["min_value"] = "0.001"; config["max_value"] = "998.915"; config["name"] = static_id(); if (sub_name.empty()) return config; else { Common::Configuration tmp; tmp.add(config, sub_name); return tmp; } } // ... default_config(...) static std::unique_ptr< ThisType > create(const Common::Configuration config = default_config(), const std::string sub_name = static_id()) { // get correct config const Common::Configuration cfg = config.has_sub(sub_name) ? config.sub(sub_name) : config; const Common::Configuration default_cfg = default_config(); // create return Common::make_unique< ThisType >( cfg.get("filename", default_cfg.get< std::string >("filename")), cfg.get("lower_left", default_cfg.get< std::vector< DomainFieldType > >("lower_left"), dimDomain), cfg.get("upper_right", default_cfg.get< std::vector< DomainFieldType > >("upper_right"), dimDomain), cfg.get("min_val", minValue), cfg.get("max_val", maxValue), cfg.get("name", default_cfg.get< std::string >("name"))); } // ... create(...) Spe10Model1(const std::string& filename, std::vector< DomainFieldType >&& lowerLeft, std::vector< DomainFieldType >&& upperRight, const RangeFieldType min = minValue, const RangeFieldType max = maxValue, const std::string nm = static_id()) : BaseType(std::move(lowerLeft), std::move(upperRight), {numXelements, numZelements}, read_values_from_file(filename, min, max), nm) {} virtual std::string type() const DS_OVERRIDE { return BaseType::static_id() + ".spe10.model1"; } virtual ThisType* copy() const DS_OVERRIDE { return new ThisType(*this); } }; // class Spe10Model1< ..., 2, ..., 1, 1 > template< class E, class D, class R > const size_t Spe10Model1< E, D, 2, R, 1, 1 >::numXelements = 100; template< class E, class D, class R > const size_t Spe10Model1< E, D, 2, R, 1, 1 >::numYelements = 1; template< class E, class D, class R > const size_t Spe10Model1< E, D, 2, R, 1, 1 >::numZelements = 20; template< class E, class D, class R > const typename Spe10Model1< E, D, 2, R, 1, 1 >::RangeFieldType Spe10Model1< E, D, 2, R, 1, 1 >::minValue = 0.001; template< class E, class D, class R > const typename Spe10Model1< E, D, 2, R, 1, 1 >::RangeFieldType Spe10Model1< E, D, 2, R, 1, 1 >::maxValue = 998.915; template< class E, class D, class R > const size_t Spe10Model1< E, D, 2, R, 2, 2 >::numXelements = 100; template< class E, class D, class R > const size_t Spe10Model1< E, D, 2, R, 2, 2 >::numYelements = 1; template< class E, class D, class R > const size_t Spe10Model1< E, D, 2, R, 2, 2 >::numZelements = 20; template< class E, class D, class R > const typename Spe10Model1< E, D, 2, R, 2, 2 >::RangeFieldType Spe10Model1< E, D, 2, R, 2, 2 >::minValue = 0.001; template< class E, class D, class R > const typename Spe10Model1< E, D, 2, R, 2, 2 >::RangeFieldType Spe10Model1< E, D, 2, R, 2, 2 >::maxValue = 998.915; } // namespace Functions } // namespace Stuff } // namespace Dune #endif // DUNE_STUFF_FUNCTIONS_SPE10_HH <commit_msg>[functions.spe10] added ctor taking FieldVectors<commit_after>// This file is part of the dune-stuff project: // https://github.com/wwu-numerik/dune-stuff/ // Copyright holders: Rene Milk, Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_STUFF_FUNCTIONS_SPE10_HH #define DUNE_STUFF_FUNCTIONS_SPE10_HH #include <iostream> #include <memory> #include <dune/stuff/common/exceptions.hh> #include <dune/stuff/common/configuration.hh> #include <dune/stuff/common/color.hh> #include <dune/stuff/common/string.hh> #include "checkerboard.hh" namespace Dune { namespace Stuff { namespace Exceptions { class spe10_data_file_missing : public Dune::IOError {}; } // namespace Exceptions namespace Functions { // default, to allow for specialization template< class EntityImp, class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDim, int rangeDimCols = 1 > class Spe10Model1 { public: Spe10Model1() = delete; }; // class FunctionSpe10Model1 /** * \note For dimRange 1 we only read the Kx values from the file. */ template< class EntityImp, class DomainFieldImp, class RangeFieldImp > class Spe10Model1< EntityImp, DomainFieldImp, 2, RangeFieldImp, 1, 1 > : public Checkerboard< EntityImp, DomainFieldImp, 2, RangeFieldImp, 1, 1 > { typedef Checkerboard< EntityImp, DomainFieldImp, 2, RangeFieldImp, 1, 1 > BaseType; typedef Spe10Model1< EntityImp, DomainFieldImp, 2, RangeFieldImp, 1, 1 > ThisType; public: typedef typename BaseType::EntityType EntityType; typedef typename BaseType::LocalfunctionType LocalfunctionType; typedef typename BaseType::DomainFieldType DomainFieldType; static const int dimDomain = BaseType::dimDomain; typedef typename BaseType::DomainType DomainType; typedef typename BaseType::RangeFieldType RangeFieldType; static const int dimRange = BaseType::dimRange; typedef typename BaseType::RangeType RangeType; static std::string static_id() { return BaseType::static_id() + ".spe10.model1"; } private: static const size_t numXelements; static const size_t numYelements; static const size_t numZelements; static const RangeFieldType minValue; static const RangeFieldType maxValue; static std::vector< RangeType > read_values_from_file(const std::string& filename, const RangeFieldType& min, const RangeFieldType& max) { if (!(max > min)) DUNE_THROW(Dune::RangeError, "max (is " << max << ") has to be larger than min (is " << min << ")!"); const RangeFieldType scale = (max - min) / (maxValue - minValue); const RangeType shift = min - scale*minValue; // read all the data from the file std::ifstream datafile(filename); if (datafile.is_open()) { static const size_t entriesPerDim = numXelements*numYelements*numZelements; // create storage (there should be exactly 6000 values in the file, but we onyl read the first 2000) std::vector< RangeType > data(entriesPerDim, RangeFieldType(0)); double tmp = 0; size_t counter = 0; while (datafile >> tmp && counter < entriesPerDim) { data[counter] = (tmp * scale) + shift; ++counter; } datafile.close(); if (counter != entriesPerDim) DUNE_THROW(Dune::IOError, "wrong number of entries in '" << filename << "' (are " << counter << ", should be " << entriesPerDim << ")!"); return data; } else DUNE_THROW(Exceptions::spe10_data_file_missing, "could not open '" << filename << "'!"); } // ... read_values_from_file(...) public: static Common::Configuration default_config(const std::string sub_name = "") { Common::Configuration config; config["filename"] = "perm_case1.dat"; config["lower_left"] = "[0.0 0.0]"; config["upper_right"] = "[762.0 15.24]"; config["min_value"] = "0.001"; config["max_value"] = "998.915"; config["name"] = static_id(); if (sub_name.empty()) return config; else { Common::Configuration tmp; tmp.add(config, sub_name); return tmp; } } // ... default_config(...) static std::unique_ptr< ThisType > create(const Common::Configuration config = default_config(), const std::string sub_name = static_id()) { // get correct config const Common::Configuration cfg = config.has_sub(sub_name) ? config.sub(sub_name) : config; const Common::Configuration default_cfg = default_config(); // create return Common::make_unique< ThisType >( cfg.get("filename", default_cfg.get< std::string >("filename")), cfg.get("lower_left", default_cfg.get< std::vector< DomainFieldType > >("lower_left"), dimDomain), cfg.get("upper_right", default_cfg.get< std::vector< DomainFieldType > >("upper_right"), dimDomain), cfg.get("min_val", minValue), cfg.get("max_val", maxValue), cfg.get("name", default_cfg.get< std::string >("name"))); } // ... create(...) Spe10Model1(const std::string& filename, const std::vector< DomainFieldType >& lowerLeft, const std::vector< DomainFieldType >& upperRight, const RangeFieldType min = minValue, const RangeFieldType max = maxValue, const std::string nm = static_id()) : BaseType(lowerLeft, upperRight, {numXelements, numZelements}, read_values_from_file(filename, min, max), nm) {} Spe10Model1(const std::string& filename, const DomainType& lowerLeft, const DomainType& upperRight, const RangeFieldType min = minValue, const RangeFieldType max = maxValue, const std::string nm = static_id()) : BaseType(lowerLeft, upperRight, {numXelements, numZelements}, read_values_from_file(filename, min, max), nm) {} virtual std::string type() const DS_OVERRIDE { return BaseType::static_id() + ".spe10.model1"; } virtual ThisType* copy() const DS_OVERRIDE { return new ThisType(*this); } }; // class Spe10Model1< ..., 2, ..., 1, 1 > /** * We read only the Kx values from file and scale the unit matrix. Thus we should be the same as the scalar variant. */ template< class EntityImp, class DomainFieldImp, class RangeFieldImp > class Spe10Model1< EntityImp, DomainFieldImp, 2, RangeFieldImp, 2, 2 > : public Checkerboard< EntityImp, DomainFieldImp, 2, RangeFieldImp, 2, 2 > { typedef Checkerboard< EntityImp, DomainFieldImp, 2, RangeFieldImp, 2, 2 > BaseType; typedef Spe10Model1< EntityImp, DomainFieldImp, 2, RangeFieldImp, 2, 2 > ThisType; public: typedef typename BaseType::EntityType EntityType; typedef typename BaseType::LocalfunctionType LocalfunctionType; typedef typename BaseType::DomainFieldType DomainFieldType; static const int dimDomain = BaseType::dimDomain; typedef typename BaseType::DomainType DomainType; typedef typename BaseType::RangeFieldType RangeFieldType; static const int dimRange = BaseType::dimRange; typedef typename BaseType::RangeType RangeType; static std::string static_id() { return BaseType::static_id() + ".spe10.model1"; } private: static const size_t numXelements; static const size_t numYelements; static const size_t numZelements; static const RangeFieldType minValue; static const RangeFieldType maxValue; static std::vector< RangeType > read_values_from_file(const std::string& filename, const RangeFieldType& min, const RangeFieldType& max) { if (!(max > min)) DUNE_THROW(Dune::RangeError, "max (is " << max << ") has to be larger than min (is " << min << ")!"); const RangeFieldType scale = (max - min) / (maxValue - minValue); const RangeFieldType shift = min - scale*minValue; // read all the data from the file std::ifstream datafile(filename); if (datafile.is_open()) { static const size_t entriesPerDim = numXelements*numYelements*numZelements; // create storage (there should be exactly 6000 values in the file, but we onyl read the first 2000) RangeType unit_matrix(0.0); for (size_t dd = 0; dd < dimDomain; ++dd) unit_matrix[dd][dd] = 1.0; std::vector< RangeType > data(entriesPerDim, unit_matrix); double tmp = 0; size_t counter = 0; while (datafile >> tmp && counter < entriesPerDim) { data[counter] *= (tmp * scale) + shift; ++counter; } datafile.close(); if (counter != entriesPerDim) DUNE_THROW(Dune::IOError, "wrong number of entries in '" << filename << "' (are " << counter << ", should be " << entriesPerDim << ")!"); return data; } else DUNE_THROW(Exceptions::spe10_data_file_missing, "could not open '" << filename << "'!"); } // ... read_values_from_file(...) public: static Common::Configuration default_config(const std::string sub_name = "") { Common::Configuration config; config["filename"] = "perm_case1.dat"; config["lower_left"] = "[0.0 0.0]"; config["upper_right"] = "[762.0 15.24]"; config["min_value"] = "0.001"; config["max_value"] = "998.915"; config["name"] = static_id(); if (sub_name.empty()) return config; else { Common::Configuration tmp; tmp.add(config, sub_name); return tmp; } } // ... default_config(...) static std::unique_ptr< ThisType > create(const Common::Configuration config = default_config(), const std::string sub_name = static_id()) { // get correct config const Common::Configuration cfg = config.has_sub(sub_name) ? config.sub(sub_name) : config; const Common::Configuration default_cfg = default_config(); // create return Common::make_unique< ThisType >( cfg.get("filename", default_cfg.get< std::string >("filename")), cfg.get("lower_left", default_cfg.get< std::vector< DomainFieldType > >("lower_left"), dimDomain), cfg.get("upper_right", default_cfg.get< std::vector< DomainFieldType > >("upper_right"), dimDomain), cfg.get("min_val", minValue), cfg.get("max_val", maxValue), cfg.get("name", default_cfg.get< std::string >("name"))); } // ... create(...) Spe10Model1(const std::string& filename, const std::vector< DomainFieldType >& lowerLeft, const std::vector< DomainFieldType >& upperRight, const RangeFieldType min = minValue, const RangeFieldType max = maxValue, const std::string nm = static_id()) : BaseType(lowerLeft, upperRight, {numXelements, numZelements}, read_values_from_file(filename, min, max), nm) {} Spe10Model1(const std::string& filename, const DomainType& lowerLeft, const DomainType& upperRight, const RangeFieldType min = minValue, const RangeFieldType max = maxValue, const std::string nm = static_id()) : BaseType(lowerLeft, upperRight, {numXelements, numZelements}, read_values_from_file(filename, min, max), nm) {} virtual std::string type() const DS_OVERRIDE { return BaseType::static_id() + ".spe10.model1"; } virtual ThisType* copy() const DS_OVERRIDE { return new ThisType(*this); } }; // class Spe10Model1< ..., 2, ..., 1, 1 > template< class E, class D, class R > const size_t Spe10Model1< E, D, 2, R, 1, 1 >::numXelements = 100; template< class E, class D, class R > const size_t Spe10Model1< E, D, 2, R, 1, 1 >::numYelements = 1; template< class E, class D, class R > const size_t Spe10Model1< E, D, 2, R, 1, 1 >::numZelements = 20; template< class E, class D, class R > const typename Spe10Model1< E, D, 2, R, 1, 1 >::RangeFieldType Spe10Model1< E, D, 2, R, 1, 1 >::minValue = 0.001; template< class E, class D, class R > const typename Spe10Model1< E, D, 2, R, 1, 1 >::RangeFieldType Spe10Model1< E, D, 2, R, 1, 1 >::maxValue = 998.915; template< class E, class D, class R > const size_t Spe10Model1< E, D, 2, R, 2, 2 >::numXelements = 100; template< class E, class D, class R > const size_t Spe10Model1< E, D, 2, R, 2, 2 >::numYelements = 1; template< class E, class D, class R > const size_t Spe10Model1< E, D, 2, R, 2, 2 >::numZelements = 20; template< class E, class D, class R > const typename Spe10Model1< E, D, 2, R, 2, 2 >::RangeFieldType Spe10Model1< E, D, 2, R, 2, 2 >::minValue = 0.001; template< class E, class D, class R > const typename Spe10Model1< E, D, 2, R, 2, 2 >::RangeFieldType Spe10Model1< E, D, 2, R, 2, 2 >::maxValue = 998.915; } // namespace Functions } // namespace Stuff } // namespace Dune #endif // DUNE_STUFF_FUNCTIONS_SPE10_HH <|endoftext|>
<commit_before>// Solves a zero-sum game using lp_solve #include "zs_wrap.h" #include "lp_lib.h" #include <cstdlib> #include <iostream> double* zs_solve_(int nRows, int nCols, double *payoffMatrix) { lprec *lp; lp = make_lp(0, nCols); set_verbose(lp, IMPORTANT); // Objective function is simply the sum of all the variables double *tmp = reinterpret_cast<double *>(malloc((nCols + 1)*sizeof(double))); for (int i = 1; i < nCols + 1; ++i) { tmp[i] = 1; } set_obj_fn(lp, tmp); set_add_rowmode(lp, 1); for (int i = 0; i < nRows; ++i) { add_constraint(lp, payoffMatrix + (i * nCols) - 1, GE, 1); } set_add_rowmode(lp, 0); int ret = solve(lp); if (ret == 0) { get_variables(lp, tmp + 1); delete_lp(lp); tmp[0] = 0; for (int i = 1; i < nCols + 1; ++i) { tmp[0] += tmp[i]; } for (int i = 1; i < nCols + 1; ++i) { tmp[i] /= tmp[0]; } tmp[0] = 1 / tmp[0]; return tmp; } delete_lp(lp); free(tmp); // We need to be cleverer here return NULL; } double* zs_solve(int nRows, int nCols, double *payoffMatrix) { // reverse every row of the payoff matrix (i mean yeah, i could reverse // the columns too but there's not any point to it) // #totallytestedcode #yolo double *revPayoffMatrix = reinterpret_cast<double *>( malloc(nRows * nCols * sizeof(double))); for (int i = 0; i < nRows; ++i) { // copy reversed row to buffer for (int j = 0; j < nCols; ++j) { revPayoffMatrix[i * nCols + j] = payoffMatrix[(i + 1) * nCols - j - 1]; } } // send it off to already existing thing double *result = zs_solve_(nRows, nCols, revPayoffMatrix); free(revPayoffMatrix); // then reverse the probability distribution before sending it back double *revresult = reinterpret_cast<double *>( malloc((nCols + 1) * sizeof(double))); revresult[0] = result[0]; for (int i = 1; i <= nCols; ++i) { revresult[i] = result[nCols + 1 - i]; } free(result); return revresult; } <commit_msg>changed zs_wrap back to using system libraries<commit_after>// Solves a zero-sum game using lp_solve #include "zs_wrap.h" #include <lp_solve/lp_lib.h> #include <cstdlib> #include <iostream> double* zs_solve_(int nRows, int nCols, double *payoffMatrix) { lprec *lp; lp = make_lp(0, nCols); set_verbose(lp, IMPORTANT); // Objective function is simply the sum of all the variables double *tmp = reinterpret_cast<double *>(malloc((nCols + 1)*sizeof(double))); for (int i = 1; i < nCols + 1; ++i) { tmp[i] = 1; } set_obj_fn(lp, tmp); set_add_rowmode(lp, 1); for (int i = 0; i < nRows; ++i) { add_constraint(lp, payoffMatrix + (i * nCols) - 1, GE, 1); } set_add_rowmode(lp, 0); int ret = solve(lp); if (ret == 0) { get_variables(lp, tmp + 1); delete_lp(lp); tmp[0] = 0; for (int i = 1; i < nCols + 1; ++i) { tmp[0] += tmp[i]; } for (int i = 1; i < nCols + 1; ++i) { tmp[i] /= tmp[0]; } tmp[0] = 1 / tmp[0]; return tmp; } delete_lp(lp); free(tmp); // We need to be cleverer here return NULL; } double* zs_solve(int nRows, int nCols, double *payoffMatrix) { // reverse every row of the payoff matrix (i mean yeah, i could reverse // the columns too but there's not any point to it) // #totallytestedcode #yolo double *revPayoffMatrix = reinterpret_cast<double *>( malloc(nRows * nCols * sizeof(double))); for (int i = 0; i < nRows; ++i) { // copy reversed row to buffer for (int j = 0; j < nCols; ++j) { revPayoffMatrix[i * nCols + j] = payoffMatrix[(i + 1) * nCols - j - 1]; } } // send it off to already existing thing double *result = zs_solve_(nRows, nCols, revPayoffMatrix); free(revPayoffMatrix); // then reverse the probability distribution before sending it back double *revresult = reinterpret_cast<double *>( malloc((nCols + 1) * sizeof(double))); revresult[0] = result[0]; for (int i = 1; i <= nCols; ++i) { revresult[i] = result[nCols + 1 - i]; } free(result); return revresult; } <|endoftext|>
<commit_before>/* * ===================================================================================== * * Filename: warp.cpp * * Description: Demonstrate various projection of an image onto a flat screen * * Version: 0.0.1 * Created: 06/03/2014 13:38:27 * Revision: none * Compiler: gcc * * Author: Eugene Scherba * Organization: Livefyre * * ===================================================================================== */ #include <cmath> #include <opencv2/opencv.hpp> using namespace cv; cv::Vec4b getSubpix(const cv::Mat& src, cv::Point2f pt) { // Simple bilinear interpolation // const int x = (int)pt.x; const int y = (int)pt.y; const int x0 = cv::borderInterpolate(x, src.cols, cv::BORDER_REFLECT_101); const int x1 = cv::borderInterpolate(x + 1, src.cols, cv::BORDER_REFLECT_101); const int y0 = cv::borderInterpolate(y, src.rows, cv::BORDER_REFLECT_101); const int y1 = cv::borderInterpolate(y + 1, src.rows, cv::BORDER_REFLECT_101); const float a = pt.x - (float)x; const float c = pt.y - (float)y; const uchar b = (uchar)cvRound( (src.at<cv::Vec4b>(y0, x0)[0] * (1.f - a) + src.at<cv::Vec4b>(y0, x1)[0] * a) * (1.f - c) + (src.at<cv::Vec4b>(y1, x0)[0] * (1.f - a) + src.at<cv::Vec4b>(y1, x1)[0] * a) * c ); const uchar g = (uchar)cvRound( (src.at<cv::Vec4b>(y0, x0)[1] * (1.f - a) + src.at<cv::Vec4b>(y0, x1)[1] * a) * (1.f - c) + (src.at<cv::Vec4b>(y1, x0)[1] * (1.f - a) + src.at<cv::Vec4b>(y1, x1)[1] * a) * c ); const uchar r = (uchar)cvRound( (src.at<cv::Vec4b>(y0, x0)[2] * (1.f - a) + src.at<cv::Vec4b>(y0, x1)[2] * a) * (1.f - c) + (src.at<cv::Vec4b>(y1, x0)[2] * (1.f - a) + src.at<cv::Vec4b>(y1, x1)[2] * a) * c ); const uchar t = (uchar)cvRound( (src.at<cv::Vec4b>(y0, x0)[3] * (1.f - a) + src.at<cv::Vec4b>(y0, x1)[3] * a) * (1.f - c) + (src.at<cv::Vec4b>(y1, x0)[3] * (1.f - a) + src.at<cv::Vec4b>(y1, x1)[3] * a) * c ); return cv::Vec4b(b, g, r, t); } void project_identity(cv::Mat& dst, cv::Mat& src) { // Identity projection (no change) // const int height = dst.rows; const int width = dst.cols; for (int j = 0; j < height; j++) { const int j_src = j; for (int i = 0; i < width; i++) { const int i_src = i; dst.at<cv::Vec4b>(j, i) = src.at<cv::Vec4b>(j_src, i_src); } } } void project_flat(cv::Mat& dst, cv::Mat& src) { // Project from a flat background onto a flat screen // const int height = dst.rows; const int width = dst.cols; const float jf = (float)height * 0.75f; // distance from camera to ceiling const float zf = (float)height * 2.0f; // distance from camera to screen const float zb = (float)height * 0.5f; // distance from screen to image for (int j = 0; j < height; j++) { const float z_ratio = (zb + zf) / zf; const float j_src = jf + z_ratio * ((float)j - jf); for (int i = 0; i < width; i++){ const int i_src = i; if (i_src >= 0.0f && i_src <= (float)width && j_src >= 0.0f && j_src <= (float)height) { dst.at<cv::Vec4b>(j, i) = getSubpix(src, cv::Point2f(i_src, j_src)); } } } } void project_cylinder(cv::Mat& dst, cv::Mat& src) { // Project from a cylindrical background onto a flat screen // const int height = dst.rows; const int width = dst.cols; const float r = (float)width * 0.5f; // cylinder radius ((width / 2) <= r < inf) const float yf = (float)height * 0.75f; // distance from camera to ceiling const float zf = hypot((float)height, (float)width); // distance from camera to screen (default: hypothenuse) const float xf = (float)width * 0.50f; // distance from camera to left edge // precompute some constants const float half_width = (float)width * 0.50f; const float zfr = cos(half_width / r); // distance from cylinder center to projection plane const float x_scale = r * sin(half_width / r) / half_width; for (int i = 0; i < width; i++) { // X-axis (columns) // const float zb = r * (cos((half_width - (float)i) / r) - zfr); const float z_ratio = (zb + zf) / zf; const float i_src = r * asin(x_scale * ((float)i - xf) * z_ratio / r) + half_width; //const float i_src = xf + z_ratio * r * sin(((float)i - half_width) / r); for (int j = 0; j < height; j++) { // Y-axis (rows) const float j_src = yf + z_ratio * x_scale * ((float)j - yf); if (i_src >= 0.0f && i_src <= (float)width && j_src >= 0.0f && j_src <= (float)height) { dst.at<cv::Vec4b>(j, i) = getSubpix(src, cv::Point2f(i_src, j_src)); } } } } cv::Mat* project_cylinder2(cv::Mat& src) { // Project from a cylindrical background onto a flat screen // const int height = src.rows; const int width = src.cols; const float r = (float)width * 0.5f; // cylinder radius ((width / 2) <= r < inf) const float zf = hypot((float)height, (float)width); // distance from camera to screen (default: hypothenuse) const float xf = (float)width * 0.5f; // distance from camera to left edge const float yf = (float)height * 0.75f; // distance from camera to ceiling // precompute some constants const float half_width = (float)width * 0.5f; const float zfr = cos(half_width / r); // distance from cylinder center to projection plane const float xfr = sin(half_width / r); const float x_scale = r * xfr / half_width; const int adj_height = (int)ceil((float)height / x_scale); std::cout << "before height: " << height << ", after height: " << adj_height << std::endl; cv::Mat *dst = new cv::Mat(cv::Mat::zeros(adj_height, width, src.type())); for (int i = 0; i < width; i++) { // X-axis (columns) // const float zb = r * (cos((half_width - (float)i) / r) - zfr); const float z_ratio = (zb + zf) / zf; const float i_src = r * asin(x_scale * ((float)i - xf) * z_ratio / r) + half_width; //const float i_src = xf + z_ratio * r * sin(((float)i - half_width) / r); for (int j = 0; j < adj_height; j++) { // Y-axis (rows) const float j_src = yf + z_ratio * (x_scale * (float)j - yf); if (i_src >= 0.0f && i_src <= (float)width && j_src >= 0.0f && j_src <= (float)height) { dst->at<cv::Vec4b>(j, i) = getSubpix(src, cv::Point2f(i_src, j_src)); } } } return dst; } int main(int argc, char *argv[]) { cv::Mat src = cv::imread(argv[1], CV_LOAD_IMAGE_UNCHANGED); cv::cvtColor(src, src, CV_RGB2RGBA); src.convertTo(src, CV_8UC4); // convert to 8-bit BGRA // fix jaggies on top and bottom by adding a 2-px border cv::copyMakeBorder(src, src, 2, 2, 0, 0, cv::BORDER_CONSTANT, cv::Scalar::all(0)); cv::Mat *dst = project_cylinder2(src); cv::imwrite(argv[2], *dst); } <commit_msg>remove a print statement<commit_after>/* * ===================================================================================== * * Filename: warp.cpp * * Description: Demonstrate various projection of an image onto a flat screen * * Version: 0.0.1 * Created: 06/03/2014 13:38:27 * Revision: none * Compiler: gcc * * Author: Eugene Scherba * Organization: Livefyre * * ===================================================================================== */ #include <cmath> #include <opencv2/opencv.hpp> using namespace cv; cv::Vec4b getSubpix(const cv::Mat& src, cv::Point2f pt) { // Simple bilinear interpolation // const int x = (int)pt.x; const int y = (int)pt.y; const int x0 = cv::borderInterpolate(x, src.cols, cv::BORDER_REFLECT_101); const int x1 = cv::borderInterpolate(x + 1, src.cols, cv::BORDER_REFLECT_101); const int y0 = cv::borderInterpolate(y, src.rows, cv::BORDER_REFLECT_101); const int y1 = cv::borderInterpolate(y + 1, src.rows, cv::BORDER_REFLECT_101); const float a = pt.x - (float)x; const float c = pt.y - (float)y; const uchar b = (uchar)cvRound( (src.at<cv::Vec4b>(y0, x0)[0] * (1.f - a) + src.at<cv::Vec4b>(y0, x1)[0] * a) * (1.f - c) + (src.at<cv::Vec4b>(y1, x0)[0] * (1.f - a) + src.at<cv::Vec4b>(y1, x1)[0] * a) * c ); const uchar g = (uchar)cvRound( (src.at<cv::Vec4b>(y0, x0)[1] * (1.f - a) + src.at<cv::Vec4b>(y0, x1)[1] * a) * (1.f - c) + (src.at<cv::Vec4b>(y1, x0)[1] * (1.f - a) + src.at<cv::Vec4b>(y1, x1)[1] * a) * c ); const uchar r = (uchar)cvRound( (src.at<cv::Vec4b>(y0, x0)[2] * (1.f - a) + src.at<cv::Vec4b>(y0, x1)[2] * a) * (1.f - c) + (src.at<cv::Vec4b>(y1, x0)[2] * (1.f - a) + src.at<cv::Vec4b>(y1, x1)[2] * a) * c ); const uchar t = (uchar)cvRound( (src.at<cv::Vec4b>(y0, x0)[3] * (1.f - a) + src.at<cv::Vec4b>(y0, x1)[3] * a) * (1.f - c) + (src.at<cv::Vec4b>(y1, x0)[3] * (1.f - a) + src.at<cv::Vec4b>(y1, x1)[3] * a) * c ); return cv::Vec4b(b, g, r, t); } void project_identity(cv::Mat& dst, cv::Mat& src) { // Identity projection (no change) // const int height = dst.rows; const int width = dst.cols; for (int j = 0; j < height; j++) { const int j_src = j; for (int i = 0; i < width; i++) { const int i_src = i; dst.at<cv::Vec4b>(j, i) = src.at<cv::Vec4b>(j_src, i_src); } } } void project_flat(cv::Mat& dst, cv::Mat& src) { // Project from a flat background onto a flat screen // const int height = dst.rows; const int width = dst.cols; const float jf = (float)height * 0.75f; // distance from camera to ceiling const float zf = (float)height * 2.0f; // distance from camera to screen const float zb = (float)height * 0.5f; // distance from screen to image for (int j = 0; j < height; j++) { const float z_ratio = (zb + zf) / zf; const float j_src = jf + z_ratio * ((float)j - jf); for (int i = 0; i < width; i++){ const int i_src = i; if (i_src >= 0.0f && i_src <= (float)width && j_src >= 0.0f && j_src <= (float)height) { dst.at<cv::Vec4b>(j, i) = getSubpix(src, cv::Point2f(i_src, j_src)); } } } } void project_cylinder(cv::Mat& dst, cv::Mat& src) { // Project from a cylindrical background onto a flat screen // const int height = dst.rows; const int width = dst.cols; const float r = (float)width * 0.5f; // cylinder radius ((width / 2) <= r < inf) const float yf = (float)height * 0.75f; // distance from camera to ceiling const float zf = hypot((float)height, (float)width); // distance from camera to screen (default: hypothenuse) const float xf = (float)width * 0.50f; // distance from camera to left edge // precompute some constants const float half_width = (float)width * 0.50f; const float zfr = cos(half_width / r); // distance from cylinder center to projection plane const float x_scale = r * sin(half_width / r) / half_width; for (int i = 0; i < width; i++) { // X-axis (columns) // const float zb = r * (cos((half_width - (float)i) / r) - zfr); const float z_ratio = (zb + zf) / zf; const float i_src = r * asin(x_scale * ((float)i - xf) * z_ratio / r) + half_width; //const float i_src = xf + z_ratio * r * sin(((float)i - half_width) / r); for (int j = 0; j < height; j++) { // Y-axis (rows) const float j_src = yf + z_ratio * x_scale * ((float)j - yf); if (i_src >= 0.0f && i_src <= (float)width && j_src >= 0.0f && j_src <= (float)height) { dst.at<cv::Vec4b>(j, i) = getSubpix(src, cv::Point2f(i_src, j_src)); } } } } cv::Mat* project_cylinder2(cv::Mat& src) { // Project from a cylindrical background onto a flat screen // const int height = src.rows; const int width = src.cols; const float r = (float)width * 0.5f; // cylinder radius ((width / 2) <= r < inf) const float zf = hypot((float)height, (float)width); // distance from camera to screen (default: hypothenuse) const float xf = (float)width * 0.5f; // distance from camera to left edge const float yf = (float)height * 0.75f; // distance from camera to ceiling // precompute some constants const float half_width = (float)width * 0.5f; const float zfr = cos(half_width / r); // distance from cylinder center to projection plane const float xfr = sin(half_width / r); const float x_scale = r * xfr / half_width; const int adj_height = (int)ceil((float)height / x_scale); cv::Mat *dst = new cv::Mat(cv::Mat::zeros(adj_height, width, src.type())); for (int i = 0; i < width; i++) { // X-axis (columns) // const float zb = r * (cos((half_width - (float)i) / r) - zfr); const float z_ratio = (zb + zf) / zf; const float i_src = r * asin(x_scale * ((float)i - xf) * z_ratio / r) + half_width; //const float i_src = xf + z_ratio * r * sin(((float)i - half_width) / r); for (int j = 0; j < adj_height; j++) { // Y-axis (rows) const float j_src = yf + z_ratio * (x_scale * (float)j - yf); if (i_src >= 0.0f && i_src <= (float)width && j_src >= 0.0f && j_src <= (float)height) { dst->at<cv::Vec4b>(j, i) = getSubpix(src, cv::Point2f(i_src, j_src)); } } } return dst; } int main(int argc, char *argv[]) { cv::Mat src = cv::imread(argv[1], CV_LOAD_IMAGE_UNCHANGED); cv::cvtColor(src, src, CV_RGB2RGBA); src.convertTo(src, CV_8UC4); // convert to 8-bit BGRA // fix jaggies on top and bottom by adding a 2-px border cv::copyMakeBorder(src, src, 2, 2, 0, 0, cv::BORDER_CONSTANT, cv::Scalar::all(0)); cv::Mat *dst = project_cylinder2(src); cv::imwrite(argv[2], *dst); delete dst; } <|endoftext|>
<commit_before>#include "util/bit_packing.hh" #include "util/exception.hh" #include <string.h> namespace util { namespace { template <bool> struct StaticCheck {}; template <> struct StaticCheck<true> { typedef bool StaticAssertionPassed; }; // If your float isn't 4 bytes, we're hosed. //typedef StaticCheck<sizeof(float) == 4>::StaticAssertionPassed FloatSize; } // namespace uint8_t RequiredBits(uint64_t max_value) { if (!max_value) return 0; uint8_t ret = 1; while (max_value >>= 1) ++ret; return ret; } void BitPackingSanity() { const FloatEnc neg1 = { -1.0 }, pos1 = { 1.0 }; if ((neg1.i ^ pos1.i) != 0x80000000) UTIL_THROW(Exception, "Sign bit is not 0x80000000"); char mem[57+8]; memset(mem, 0, sizeof(mem)); const uint64_t test57 = 0x123456789abcdefULL; for (uint64_t b = 0; b < 57 * 8; b += 57) { WriteInt57(mem, b, 57, test57); } for (uint64_t b = 0; b < 57 * 8; b += 57) { if (test57 != ReadInt57(mem, b, 57, (1ULL << 57) - 1)) UTIL_THROW(Exception, "The bit packing routines are failing for your architecture. Please send a bug report with your architecture, operating system, and compiler."); } // TODO: more checks. } } // namespace util <commit_msg>Minor rollback<commit_after>#include "util/bit_packing.hh" #include "util/exception.hh" #include <string.h> namespace util { namespace { template <bool> struct StaticCheck {}; template <> struct StaticCheck<true> { typedef bool StaticAssertionPassed; }; // If your float isn't 4 bytes, we're hosed. typedef StaticCheck<sizeof(float) == 4>::StaticAssertionPassed FloatSize; } // namespace uint8_t RequiredBits(uint64_t max_value) { if (!max_value) return 0; uint8_t ret = 1; while (max_value >>= 1) ++ret; return ret; } void BitPackingSanity() { const FloatEnc neg1 = { -1.0 }, pos1 = { 1.0 }; if ((neg1.i ^ pos1.i) != 0x80000000) UTIL_THROW(Exception, "Sign bit is not 0x80000000"); char mem[57+8]; memset(mem, 0, sizeof(mem)); const uint64_t test57 = 0x123456789abcdefULL; for (uint64_t b = 0; b < 57 * 8; b += 57) { WriteInt57(mem, b, 57, test57); } for (uint64_t b = 0; b < 57 * 8; b += 57) { if (test57 != ReadInt57(mem, b, 57, (1ULL << 57) - 1)) UTIL_THROW(Exception, "The bit packing routines are failing for your architecture. Please send a bug report with your architecture, operating system, and compiler."); } // TODO: more checks. } } // namespace util <|endoftext|>
<commit_before>/** * Copyright 2013 Da Zheng * * This file is part of SAFSlib. * * SAFSlib 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. * * SAFSlib 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 SAFSlib. If not, see <http://www.gnu.org/licenses/>. */ #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <string> #include "io_interface.h" #include "native_file.h" #include "safs_file.h" const int BUF_SIZE = 1024 * 64 * PAGE_SIZE; const size_t DATA_SIZE = 10L * 1024 * 1024 * 1024; ssize_t complete_read(int fd, char *buf, size_t count) { ssize_t bytes = 0; do { ssize_t ret = read(fd, buf, count); if (ret < 0) return ret; if (ret == 0) return bytes; bytes += ret; count -= ret; buf += ret; } while (count > 0); return bytes; } int verify_bytes(const char *bs1, const char *bs2, int size) { for (int i = 0; i < size; i++) { assert(bs1[i] == bs2[i]); } return 0; } class data_source { public: virtual ssize_t get_data(off_t off, size_t size, char *buf) const = 0; virtual size_t get_size() const = 0; }; class file_data_source: public data_source { int fd; size_t file_size; public: file_data_source(const std::string &ext_file) { fd = open(ext_file.c_str(), O_RDONLY); if (fd < 0) { perror("open"); exit(-1); } native_file f(ext_file); file_size = f.get_size(); } virtual ssize_t get_data(off_t off, size_t size, char *buf) const { long new_off = lseek(fd, off, SEEK_SET); assert(new_off == off); ssize_t ret = complete_read(fd, buf, size); if (ret < 0) { perror("complete_read"); exit(-1); } return ret; } virtual size_t get_size() const { return file_size; } }; class synthetic_data_source: public data_source { size_t size; public: synthetic_data_source(size_t size) { this->size = size; } virtual ssize_t get_data(off_t off, size_t size, char *buf) const { off_t *long_pointer = (off_t *) buf; int num_longs = size / sizeof(off_t); long value = off / sizeof(off_t); for (int i = 0; i < num_longs; i++, value++) { long_pointer[i] = value; } return size; } virtual size_t get_size() const { return size; } }; class verify_callback: public callback { char *orig_buf; data_source *source; size_t verified_bytes; public: verify_callback(data_source *source) { this->source = source; orig_buf = (char *) malloc(BUF_SIZE); verified_bytes = 0; } ~verify_callback() { free(orig_buf); } int invoke(io_request *rqs[], int num) { size_t read_bytes = min<size_t>(rqs[0]->get_size(), source->get_size() - rqs[0]->get_offset()); assert(read_bytes > 0); size_t ret = source->get_data(rqs[0]->get_offset(), read_bytes, orig_buf); fprintf(stderr, "verify block %lx of %ld bytes\n", rqs[0]->get_offset(), read_bytes); assert(ret == read_bytes); verified_bytes += read_bytes; verify_bytes(rqs[0]->get_buf(), orig_buf, read_bytes); } size_t get_verified_bytes() const { return verified_bytes; } }; void comm_verify_file(int argc, char *argv[]) { if (argc < 1) { fprintf(stderr, "verify file_name [ext_file]"); fprintf(stderr, "file_name is the file name in the SA-FS file system\n"); fprintf(stderr, "ext_file is the file in the external file system\n"); exit(-1); } std::string int_file_name = argv[0]; std::string ext_file; if (argc >= 2) ext_file = argv[1]; file_io_factory *factory = create_io_factory(int_file_name, REMOTE_ACCESS); thread *curr_thread = thread::get_curr_thread(); assert(curr_thread); io_interface *io = factory->create_io(curr_thread); data_source *source; if (ext_file.empty()) source = new synthetic_data_source(DATA_SIZE); else source = new file_data_source(ext_file); verify_callback *cb = new verify_callback(source); io->set_callback(cb); size_t file_size = source->get_size(); assert(factory->get_file_size() >= file_size); file_size = ROUNDUP(file_size, BUF_SIZE); char *buf = (char *) valloc(BUF_SIZE); for (off_t off = 0; off < file_size; off += BUF_SIZE) { data_loc_t loc(io->get_file_id(), off); io_request req(buf, loc, BUF_SIZE, READ, io, 0); io->access(&req, 1); io->wait4complete(1); } printf("verify %ld bytes\n", cb->get_verified_bytes()); io->cleanup(); delete io->get_callback(); factory->destroy_io(io); } void comm_load_file2fs(int argc, char *argv[]) { if (argc < 1) { fprintf(stderr, "load file_name [ext_file]\n"); fprintf(stderr, "file_name is the file name in the SA-FS file system\n"); fprintf(stderr, "ext_file is the file in the external file system\n"); exit(-1); } std::string int_file_name = argv[0]; std::string ext_file; if (argc >= 2) ext_file = argv[1]; safs_file file(get_sys_RAID_conf(), int_file_name); if (!file.exist()) { fprintf(stderr, "%s doesn't exist\n", int_file_name.c_str()); return; } file_io_factory *factory = create_io_factory(int_file_name, REMOTE_ACCESS); assert(factory); thread *curr_thread = thread::get_curr_thread(); assert(curr_thread); io_interface *io = factory->create_io(curr_thread); data_source *source; if (ext_file.empty()) { printf("use synthetic data\n"); source = new synthetic_data_source(DATA_SIZE); } else { printf("use file %s\n", ext_file.c_str()); source = new file_data_source(ext_file); } assert(factory->get_file_size() >= source->get_size()); printf("source size: %ld\n", source->get_size()); char *buf = (char *) valloc(BUF_SIZE); off_t off = 0; while (off < source->get_size()) { size_t size = min<size_t>(BUF_SIZE, source->get_size() - off); size_t ret = source->get_data(off, size, buf); assert(ret == size); ssize_t write_bytes = ROUNDUP(ret, 512); data_loc_t loc(io->get_file_id(), off); io_request req(buf, loc, write_bytes, WRITE, io, 0); io->access(&req, 1); io->wait4complete(1); off += write_bytes; } printf("write all data\n"); io->cleanup(); factory->destroy_io(io); } void comm_create_file(int argc, char *argv[]) { if (argc < 2) { fprintf(stderr, "create file_name size\n"); fprintf(stderr, "file_name is the file name in the SA-FS file system\n"); exit(-1); } std::string file_name = argv[0]; size_t file_size = str2size(argv[1]); safs_file file(get_sys_RAID_conf(), file_name); file.create_file(file_size); printf("create file %s of %ld bytes\n", file_name.c_str(), file.get_file_size()); } void print_help(); void comm_help(int argc, char *argv[]) { print_help(); } void comm_list(int argc, char *argv[]) { std::set<std::string> files; const RAID_config &conf = get_sys_RAID_conf(); // First find all individual file names in the root directories. for (int i = 0; i < conf.get_num_disks(); i++) { std::string dir_name = conf.get_disk(i).name; native_dir dir(dir_name); std::vector<std::string> file_names; dir.read_all_files(file_names); files.insert(file_names.begin(), file_names.end()); } for (std::set<std::string>::const_iterator it = files.begin(); it != files.end(); it++) { safs_file file(conf, *it); if (file.exist()) { printf("%s: %ld bytes\n", file.get_name().c_str(), file.get_file_size()); } else { printf("%s is corrupted\n", file.get_name().c_str()); } } } void comm_delete_file(int argc, char *argv[]) { if (argc < 1) { fprintf(stderr, "delete file_name\n"); return; } std::string file_name = argv[0]; safs_file file(get_sys_RAID_conf(), file_name); if (!file.exist()) { fprintf(stderr, "%s doesn't exist\n", file_name.c_str()); return; } file.delete_file(); } typedef void (*command_func_t)(int argc, char *argv[]); struct command { std::string name; command_func_t func; std::string help_info; }; struct command commands[] = { {"create", comm_create_file, "create file_name size: create a file with the specified size"}, {"delete", comm_delete_file, "delete file_name: delete a file"}, {"help", comm_help, "help: print the help info"}, {"list", comm_list, "list: list existing files in SAFS"}, {"load", comm_load_file2fs, "load file_name [ext_file]: load data to the file"}, {"verify", comm_verify_file, "verify file_name [ext_file]: verify data in the file"}, }; int get_num_commands() { return sizeof(commands) / sizeof(commands[0]); } const command *get_command(const std::string &name) { int num_comms = get_num_commands(); for (int i = 0; i < num_comms; i++) { if (commands[i].name == name) return &commands[i]; } return NULL; } void print_help() { printf("SAFS-util conf_file command ...\n"); printf("The supported commands are\n"); int num_commands = get_num_commands(); for (int i =0; i < num_commands; i++) { printf("\t%s\n", commands[i].help_info.c_str()); } } /** * This is a utility tool for the SA-FS. */ int main(int argc, char *argv[]) { if (argc < 3) { print_help(); exit(-1); } std::string conf_file = argv[1]; std::string command = argv[2]; config_map configs(conf_file); init_io_system(configs); const struct command *comm = get_command(command); if (comm == NULL) { fprintf(stderr, "wrong command %s\n", comm->name.c_str()); print_help(); return -1; } comm->func(argc - 3, argv + 3); } <commit_msg>[SAFS]: write/verify the entire file in SAFS-util.<commit_after>/** * Copyright 2013 Da Zheng * * This file is part of SAFSlib. * * SAFSlib 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. * * SAFSlib 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 SAFSlib. If not, see <http://www.gnu.org/licenses/>. */ #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <string> #include "io_interface.h" #include "native_file.h" #include "safs_file.h" const int BUF_SIZE = 1024 * 64 * PAGE_SIZE; ssize_t complete_read(int fd, char *buf, size_t count) { ssize_t bytes = 0; do { ssize_t ret = read(fd, buf, count); if (ret < 0) return ret; if (ret == 0) return bytes; bytes += ret; count -= ret; buf += ret; } while (count > 0); return bytes; } int verify_bytes(const char *bs1, const char *bs2, int size) { for (int i = 0; i < size; i++) { assert(bs1[i] == bs2[i]); } return 0; } class data_source { public: virtual ssize_t get_data(off_t off, size_t size, char *buf) const = 0; virtual size_t get_size() const = 0; }; class file_data_source: public data_source { int fd; size_t file_size; public: file_data_source(const std::string &ext_file) { fd = open(ext_file.c_str(), O_RDONLY); if (fd < 0) { perror("open"); exit(-1); } native_file f(ext_file); file_size = f.get_size(); } virtual ssize_t get_data(off_t off, size_t size, char *buf) const { long new_off = lseek(fd, off, SEEK_SET); assert(new_off == off); ssize_t ret = complete_read(fd, buf, size); if (ret < 0) { perror("complete_read"); exit(-1); } return ret; } virtual size_t get_size() const { return file_size; } }; class synthetic_data_source: public data_source { size_t size; public: synthetic_data_source(size_t size) { this->size = size; } virtual ssize_t get_data(off_t off, size_t size, char *buf) const { off_t *long_pointer = (off_t *) buf; int num_longs = size / sizeof(off_t); long value = off / sizeof(off_t); for (int i = 0; i < num_longs; i++, value++) { long_pointer[i] = value; } return size; } virtual size_t get_size() const { return size; } }; class verify_callback: public callback { char *orig_buf; data_source *source; size_t verified_bytes; public: verify_callback(data_source *source) { this->source = source; orig_buf = (char *) malloc(BUF_SIZE); verified_bytes = 0; } ~verify_callback() { free(orig_buf); } int invoke(io_request *rqs[], int num) { size_t read_bytes = min<size_t>(rqs[0]->get_size(), source->get_size() - rqs[0]->get_offset()); assert(read_bytes > 0); size_t ret = source->get_data(rqs[0]->get_offset(), read_bytes, orig_buf); fprintf(stderr, "verify block %lx of %ld bytes\n", rqs[0]->get_offset(), read_bytes); assert(ret == read_bytes); verified_bytes += read_bytes; verify_bytes(rqs[0]->get_buf(), orig_buf, read_bytes); } size_t get_verified_bytes() const { return verified_bytes; } }; void comm_verify_file(int argc, char *argv[]) { if (argc < 1) { fprintf(stderr, "verify file_name [ext_file]"); fprintf(stderr, "file_name is the file name in the SA-FS file system\n"); fprintf(stderr, "ext_file is the file in the external file system\n"); exit(-1); } std::string int_file_name = argv[0]; std::string ext_file; if (argc >= 2) ext_file = argv[1]; file_io_factory *factory = create_io_factory(int_file_name, REMOTE_ACCESS); thread *curr_thread = thread::get_curr_thread(); assert(curr_thread); io_interface *io = factory->create_io(curr_thread); data_source *source; if (ext_file.empty()) source = new synthetic_data_source(factory->get_file_size()); else source = new file_data_source(ext_file); verify_callback *cb = new verify_callback(source); io->set_callback(cb); size_t file_size = source->get_size(); printf("verify %ld bytes\n", file_size); assert(factory->get_file_size() >= file_size); file_size = ROUNDUP(file_size, BUF_SIZE); char *buf = (char *) valloc(BUF_SIZE); for (off_t off = 0; off < file_size; off += BUF_SIZE) { data_loc_t loc(io->get_file_id(), off); io_request req(buf, loc, BUF_SIZE, READ, io, 0); io->access(&req, 1); io->wait4complete(1); } printf("verify %ld bytes\n", cb->get_verified_bytes()); io->cleanup(); delete io->get_callback(); factory->destroy_io(io); } void comm_load_file2fs(int argc, char *argv[]) { if (argc < 1) { fprintf(stderr, "load file_name [ext_file]\n"); fprintf(stderr, "file_name is the file name in the SA-FS file system\n"); fprintf(stderr, "ext_file is the file in the external file system\n"); exit(-1); } std::string int_file_name = argv[0]; std::string ext_file; if (argc >= 2) ext_file = argv[1]; safs_file file(get_sys_RAID_conf(), int_file_name); if (!file.exist()) { fprintf(stderr, "%s doesn't exist\n", int_file_name.c_str()); return; } file_io_factory *factory = create_io_factory(int_file_name, REMOTE_ACCESS); assert(factory); thread *curr_thread = thread::get_curr_thread(); assert(curr_thread); io_interface *io = factory->create_io(curr_thread); data_source *source; if (ext_file.empty()) { printf("use synthetic data\n"); source = new synthetic_data_source(factory->get_file_size()); } else { printf("use file %s\n", ext_file.c_str()); source = new file_data_source(ext_file); } assert(factory->get_file_size() >= source->get_size()); printf("source size: %ld\n", source->get_size()); char *buf = (char *) valloc(BUF_SIZE); off_t off = 0; while (off < source->get_size()) { size_t size = min<size_t>(BUF_SIZE, source->get_size() - off); size_t ret = source->get_data(off, size, buf); assert(ret == size); ssize_t write_bytes = ROUNDUP(ret, 512); data_loc_t loc(io->get_file_id(), off); io_request req(buf, loc, write_bytes, WRITE, io, 0); io->access(&req, 1); io->wait4complete(1); off += write_bytes; } printf("write all data\n"); io->cleanup(); factory->destroy_io(io); } void comm_create_file(int argc, char *argv[]) { if (argc < 2) { fprintf(stderr, "create file_name size\n"); fprintf(stderr, "file_name is the file name in the SA-FS file system\n"); exit(-1); } std::string file_name = argv[0]; size_t file_size = str2size(argv[1]); safs_file file(get_sys_RAID_conf(), file_name); file.create_file(file_size); printf("create file %s of %ld bytes\n", file_name.c_str(), file.get_file_size()); } void print_help(); void comm_help(int argc, char *argv[]) { print_help(); } void comm_list(int argc, char *argv[]) { std::set<std::string> files; const RAID_config &conf = get_sys_RAID_conf(); // First find all individual file names in the root directories. for (int i = 0; i < conf.get_num_disks(); i++) { std::string dir_name = conf.get_disk(i).name; native_dir dir(dir_name); std::vector<std::string> file_names; dir.read_all_files(file_names); files.insert(file_names.begin(), file_names.end()); } for (std::set<std::string>::const_iterator it = files.begin(); it != files.end(); it++) { safs_file file(conf, *it); if (file.exist()) { printf("%s: %ld bytes\n", file.get_name().c_str(), file.get_file_size()); } else { printf("%s is corrupted\n", file.get_name().c_str()); } } } void comm_delete_file(int argc, char *argv[]) { if (argc < 1) { fprintf(stderr, "delete file_name\n"); return; } std::string file_name = argv[0]; safs_file file(get_sys_RAID_conf(), file_name); if (!file.exist()) { fprintf(stderr, "%s doesn't exist\n", file_name.c_str()); return; } file.delete_file(); } typedef void (*command_func_t)(int argc, char *argv[]); struct command { std::string name; command_func_t func; std::string help_info; }; struct command commands[] = { {"create", comm_create_file, "create file_name size: create a file with the specified size"}, {"delete", comm_delete_file, "delete file_name: delete a file"}, {"help", comm_help, "help: print the help info"}, {"list", comm_list, "list: list existing files in SAFS"}, {"load", comm_load_file2fs, "load file_name [ext_file]: load data to the file"}, {"verify", comm_verify_file, "verify file_name [ext_file]: verify data in the file"}, }; int get_num_commands() { return sizeof(commands) / sizeof(commands[0]); } const command *get_command(const std::string &name) { int num_comms = get_num_commands(); for (int i = 0; i < num_comms; i++) { if (commands[i].name == name) return &commands[i]; } return NULL; } void print_help() { printf("SAFS-util conf_file command ...\n"); printf("The supported commands are\n"); int num_commands = get_num_commands(); for (int i =0; i < num_commands; i++) { printf("\t%s\n", commands[i].help_info.c_str()); } } /** * This is a utility tool for the SA-FS. */ int main(int argc, char *argv[]) { if (argc < 3) { print_help(); exit(-1); } std::string conf_file = argv[1]; std::string command = argv[2]; config_map configs(conf_file); init_io_system(configs); const struct command *comm = get_command(command); if (comm == NULL) { fprintf(stderr, "wrong command %s\n", comm->name.c_str()); print_help(); return -1; } comm->func(argc - 3, argv + 3); } <|endoftext|>
<commit_before>/** * Copyright 2013 Da Zheng * * This file is part of SAFSlib. * * SAFSlib 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. * * SAFSlib 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 SAFSlib. If not, see <http://www.gnu.org/licenses/>. */ #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <string> #include "io_interface.h" #include "native_file.h" #include "safs_file.h" const int BUF_SIZE = 1024 * 64 * PAGE_SIZE; const size_t DATA_SIZE = 10L * 1024 * 1024 * 1024; ssize_t complete_read(int fd, char *buf, size_t count) { ssize_t bytes = 0; do { ssize_t ret = read(fd, buf, count); if (ret < 0) return ret; if (ret == 0) return bytes; bytes += ret; count -= ret; buf += ret; } while (count > 0); return bytes; } int verify_bytes(const char *bs1, const char *bs2, int size) { for (int i = 0; i < size; i++) { assert(bs1[i] == bs2[i]); } return 0; } class data_source { public: virtual ssize_t get_data(off_t off, size_t size, char *buf) const = 0; virtual size_t get_size() const = 0; }; class file_data_source: public data_source { int fd; size_t file_size; public: file_data_source(const std::string &ext_file) { fd = open(ext_file.c_str(), O_RDONLY); if (fd < 0) { perror("open"); exit(-1); } native_file f(ext_file); file_size = f.get_size(); } virtual ssize_t get_data(off_t off, size_t size, char *buf) const { long new_off = lseek(fd, off, SEEK_SET); assert(new_off == off); ssize_t ret = complete_read(fd, buf, size); if (ret < 0) { perror("complete_read"); exit(-1); } return ret; } virtual size_t get_size() const { return file_size; } }; class synthetic_data_source: public data_source { size_t size; public: synthetic_data_source(size_t size) { this->size = size; } virtual ssize_t get_data(off_t off, size_t size, char *buf) const { off_t *long_pointer = (off_t *) buf; int num_longs = size / sizeof(off_t); long value = off / sizeof(off_t); for (int i = 0; i < num_longs; i++, value++) { long_pointer[i] = value; } return size; } virtual size_t get_size() const { return size; } }; class verify_callback: public callback { char *orig_buf; data_source *source; size_t verified_bytes; public: verify_callback(data_source *source) { this->source = source; orig_buf = (char *) malloc(BUF_SIZE); verified_bytes = 0; } ~verify_callback() { free(orig_buf); } int invoke(io_request *rqs[], int num) { size_t read_bytes = min<size_t>(rqs[0]->get_size(), source->get_size() - rqs[0]->get_offset()); assert(read_bytes > 0); size_t ret = source->get_data(rqs[0]->get_offset(), read_bytes, orig_buf); fprintf(stderr, "verify block %lx of %ld bytes\n", rqs[0]->get_offset(), read_bytes); assert(ret == read_bytes); verified_bytes += read_bytes; verify_bytes(rqs[0]->get_buf(), orig_buf, read_bytes); } size_t get_verified_bytes() const { return verified_bytes; } }; void comm_verify_file(int argc, char *argv[]) { if (argc < 1) { fprintf(stderr, "verify file_name [ext_file]"); fprintf(stderr, "file_name is the file name in the SA-FS file system\n"); fprintf(stderr, "ext_file is the file in the external file system\n"); exit(-1); } std::string int_file_name = argv[0]; std::string ext_file; if (argc >= 2) ext_file = argv[1]; file_io_factory *factory = create_io_factory(int_file_name, REMOTE_ACCESS); thread *curr_thread = thread::represent_thread(0); io_interface *io = factory->create_io(curr_thread); data_source *source; if (ext_file.empty()) source = new synthetic_data_source(DATA_SIZE); else source = new file_data_source(ext_file); verify_callback *cb = new verify_callback(source); io->set_callback(cb); size_t file_size = source->get_size(); assert(factory->get_file_size() >= file_size); file_size = ROUNDUP(file_size, BUF_SIZE); char *buf = (char *) valloc(BUF_SIZE); for (off_t off = 0; off < file_size; off += BUF_SIZE) { io_request req(buf, off, BUF_SIZE, READ, io, 0); io->access(&req, 1); io->wait4complete(1); } printf("verify %ld bytes\n", cb->get_verified_bytes()); io->cleanup(); delete io->get_callback(); factory->destroy_io(io); } void comm_load_file2fs(int argc, char *argv[]) { if (argc < 1) { fprintf(stderr, "load file_name [ext_file]\n"); fprintf(stderr, "file_name is the file name in the SA-FS file system\n"); fprintf(stderr, "ext_file is the file in the external file system\n"); exit(-1); } std::string int_file_name = argv[0]; std::string ext_file; if (argc >= 2) ext_file = argv[1]; file_io_factory *factory = create_io_factory(int_file_name, REMOTE_ACCESS); thread *curr_thread = thread::represent_thread(0); io_interface *io = factory->create_io(curr_thread); data_source *source; if (ext_file.empty()) { printf("use synthetic data\n"); source = new synthetic_data_source(DATA_SIZE); } else { printf("use file %s\n", ext_file.c_str()); source = new file_data_source(ext_file); } assert(factory->get_file_size() >= source->get_size()); printf("source size: %ld\n", source->get_size()); char *buf = (char *) valloc(BUF_SIZE); off_t off = 0; while (off < source->get_size()) { size_t size = min<size_t>(BUF_SIZE, source->get_size() - off); size_t ret = source->get_data(off, size, buf); assert(ret == size); ssize_t write_bytes = ROUNDUP(ret, 512); io_request req(buf, off, write_bytes, WRITE, io, 0); io->access(&req, 1); io->wait4complete(1); off += write_bytes; } printf("write all data\n"); io->cleanup(); factory->destroy_io(io); } void comm_create_file(int argc, char *argv[]) { if (argc < 2) { fprintf(stderr, "create file_name size\n"); fprintf(stderr, "file_name is the file name in the SA-FS file system\n"); exit(-1); } std::string file_name = argv[0]; size_t file_size = str2size(argv[1]); safs_file file(get_sys_RAID_conf(), file_name); file.create_file(file_size); printf("create file %s of %ld bytes\n", file_name.c_str(), file.get_file_size()); } /** * This is a utility tool for the SA-FS. */ int main(int argc, char *argv[]) { if (argc < 3) { fprintf(stderr, "util conf_file command ...\n"); exit(-1); } std::string conf_file = argv[1]; std::string command = argv[2]; config_map configs(conf_file); init_io_system(configs); if (command == "load") { comm_load_file2fs(argc - 3, argv + 3); } else if (command == "verify") { comm_verify_file(argc - 3, argv + 3); } else if (command == "create") { comm_create_file(argc - 3, argv + 3); } } <commit_msg>[SAFS]: restructure SAFS-util to make it more extensible.<commit_after>/** * Copyright 2013 Da Zheng * * This file is part of SAFSlib. * * SAFSlib 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. * * SAFSlib 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 SAFSlib. If not, see <http://www.gnu.org/licenses/>. */ #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <string> #include "io_interface.h" #include "native_file.h" #include "safs_file.h" const int BUF_SIZE = 1024 * 64 * PAGE_SIZE; const size_t DATA_SIZE = 10L * 1024 * 1024 * 1024; ssize_t complete_read(int fd, char *buf, size_t count) { ssize_t bytes = 0; do { ssize_t ret = read(fd, buf, count); if (ret < 0) return ret; if (ret == 0) return bytes; bytes += ret; count -= ret; buf += ret; } while (count > 0); return bytes; } int verify_bytes(const char *bs1, const char *bs2, int size) { for (int i = 0; i < size; i++) { assert(bs1[i] == bs2[i]); } return 0; } class data_source { public: virtual ssize_t get_data(off_t off, size_t size, char *buf) const = 0; virtual size_t get_size() const = 0; }; class file_data_source: public data_source { int fd; size_t file_size; public: file_data_source(const std::string &ext_file) { fd = open(ext_file.c_str(), O_RDONLY); if (fd < 0) { perror("open"); exit(-1); } native_file f(ext_file); file_size = f.get_size(); } virtual ssize_t get_data(off_t off, size_t size, char *buf) const { long new_off = lseek(fd, off, SEEK_SET); assert(new_off == off); ssize_t ret = complete_read(fd, buf, size); if (ret < 0) { perror("complete_read"); exit(-1); } return ret; } virtual size_t get_size() const { return file_size; } }; class synthetic_data_source: public data_source { size_t size; public: synthetic_data_source(size_t size) { this->size = size; } virtual ssize_t get_data(off_t off, size_t size, char *buf) const { off_t *long_pointer = (off_t *) buf; int num_longs = size / sizeof(off_t); long value = off / sizeof(off_t); for (int i = 0; i < num_longs; i++, value++) { long_pointer[i] = value; } return size; } virtual size_t get_size() const { return size; } }; class verify_callback: public callback { char *orig_buf; data_source *source; size_t verified_bytes; public: verify_callback(data_source *source) { this->source = source; orig_buf = (char *) malloc(BUF_SIZE); verified_bytes = 0; } ~verify_callback() { free(orig_buf); } int invoke(io_request *rqs[], int num) { size_t read_bytes = min<size_t>(rqs[0]->get_size(), source->get_size() - rqs[0]->get_offset()); assert(read_bytes > 0); size_t ret = source->get_data(rqs[0]->get_offset(), read_bytes, orig_buf); fprintf(stderr, "verify block %lx of %ld bytes\n", rqs[0]->get_offset(), read_bytes); assert(ret == read_bytes); verified_bytes += read_bytes; verify_bytes(rqs[0]->get_buf(), orig_buf, read_bytes); } size_t get_verified_bytes() const { return verified_bytes; } }; void comm_verify_file(int argc, char *argv[]) { if (argc < 1) { fprintf(stderr, "verify file_name [ext_file]"); fprintf(stderr, "file_name is the file name in the SA-FS file system\n"); fprintf(stderr, "ext_file is the file in the external file system\n"); exit(-1); } std::string int_file_name = argv[0]; std::string ext_file; if (argc >= 2) ext_file = argv[1]; file_io_factory *factory = create_io_factory(int_file_name, REMOTE_ACCESS); thread *curr_thread = thread::represent_thread(0); io_interface *io = factory->create_io(curr_thread); data_source *source; if (ext_file.empty()) source = new synthetic_data_source(DATA_SIZE); else source = new file_data_source(ext_file); verify_callback *cb = new verify_callback(source); io->set_callback(cb); size_t file_size = source->get_size(); assert(factory->get_file_size() >= file_size); file_size = ROUNDUP(file_size, BUF_SIZE); char *buf = (char *) valloc(BUF_SIZE); for (off_t off = 0; off < file_size; off += BUF_SIZE) { io_request req(buf, off, BUF_SIZE, READ, io, 0); io->access(&req, 1); io->wait4complete(1); } printf("verify %ld bytes\n", cb->get_verified_bytes()); io->cleanup(); delete io->get_callback(); factory->destroy_io(io); } void comm_load_file2fs(int argc, char *argv[]) { if (argc < 1) { fprintf(stderr, "load file_name [ext_file]\n"); fprintf(stderr, "file_name is the file name in the SA-FS file system\n"); fprintf(stderr, "ext_file is the file in the external file system\n"); exit(-1); } std::string int_file_name = argv[0]; std::string ext_file; if (argc >= 2) ext_file = argv[1]; file_io_factory *factory = create_io_factory(int_file_name, REMOTE_ACCESS); thread *curr_thread = thread::represent_thread(0); io_interface *io = factory->create_io(curr_thread); data_source *source; if (ext_file.empty()) { printf("use synthetic data\n"); source = new synthetic_data_source(DATA_SIZE); } else { printf("use file %s\n", ext_file.c_str()); source = new file_data_source(ext_file); } assert(factory->get_file_size() >= source->get_size()); printf("source size: %ld\n", source->get_size()); char *buf = (char *) valloc(BUF_SIZE); off_t off = 0; while (off < source->get_size()) { size_t size = min<size_t>(BUF_SIZE, source->get_size() - off); size_t ret = source->get_data(off, size, buf); assert(ret == size); ssize_t write_bytes = ROUNDUP(ret, 512); io_request req(buf, off, write_bytes, WRITE, io, 0); io->access(&req, 1); io->wait4complete(1); off += write_bytes; } printf("write all data\n"); io->cleanup(); factory->destroy_io(io); } void comm_create_file(int argc, char *argv[]) { if (argc < 2) { fprintf(stderr, "create file_name size\n"); fprintf(stderr, "file_name is the file name in the SA-FS file system\n"); exit(-1); } std::string file_name = argv[0]; size_t file_size = str2size(argv[1]); safs_file file(get_sys_RAID_conf(), file_name); file.create_file(file_size); printf("create file %s of %ld bytes\n", file_name.c_str(), file.get_file_size()); } typedef void (*command_func_t)(int argc, char *argv[]); struct command { std::string name; command_func_t func; std::string help_info; }; struct command commands[] = { {"create", comm_create_file, "create file_name size: create a file with the specified size"}, {"load", comm_load_file2fs, "load file_name [ext_file]: load data to the file"}, {"verify", comm_verify_file, "verify file_name [ext_file]: verify data in the file"}, }; int get_num_commands() { return sizeof(commands) / sizeof(commands[0]); } const command *get_command(const std::string &name) { int num_comms = get_num_commands(); for (int i = 0; i < num_comms; i++) { if (commands[i].name == name) return &commands[i]; } return NULL; } void print_help() { printf("SAFS-util conf_file command ...\n"); printf("The supported commands are\n"); int num_commands = get_num_commands(); for (int i =0; i < num_commands; i++) { printf("\t%s\n", commands[i].help_info.c_str()); } } /** * This is a utility tool for the SA-FS. */ int main(int argc, char *argv[]) { if (argc < 3) { print_help(); exit(-1); } std::string conf_file = argv[1]; std::string command = argv[2]; config_map configs(conf_file); init_io_system(configs); const struct command *comm = get_command(command); if (comm == NULL) { fprintf(stderr, "wrong command %s\n", comm->name.c_str()); print_help(); return -1; } comm->func(argc - 3, argv + 3); } <|endoftext|>
<commit_before>//===-- CommandObjectDisassemble.cpp ----------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "CommandObjectDisassemble.h" // C Includes // C++ Includes // Other libraries and framework includes // Project includes #include "lldb/Core/AddressRange.h" #include "lldb/Interpreter/Args.h" #include "lldb/Interpreter/CommandCompletions.h" #include "lldb/Interpreter/CommandInterpreter.h" #include "lldb/Interpreter/CommandReturnObject.h" #include "lldb/Core/Disassembler.h" #include "lldb/Interpreter/Options.h" #include "lldb/Core/SourceManager.h" #include "lldb/Target/StackFrame.h" #include "lldb/Symbol/Symbol.h" #include "lldb/Target/Process.h" #include "lldb/Target/Target.h" #define DEFAULT_DISASM_BYTE_SIZE 32 using namespace lldb; using namespace lldb_private; CommandObjectDisassemble::CommandOptions::CommandOptions () : Options(), m_func_name(), m_start_addr(), m_end_addr () { ResetOptionValues(); } CommandObjectDisassemble::CommandOptions::~CommandOptions () { } Error CommandObjectDisassemble::CommandOptions::SetOptionValue (int option_idx, const char *option_arg) { Error error; char short_option = (char) m_getopt_table[option_idx].val; switch (short_option) { case 'm': show_mixed = true; break; case 'c': num_lines_context = Args::StringToUInt32(option_arg, 0, 0); break; case 'b': show_bytes = true; break; case 's': m_start_addr = Args::StringToUInt64(optarg, LLDB_INVALID_ADDRESS, 0); if (m_start_addr == LLDB_INVALID_ADDRESS) m_start_addr = Args::StringToUInt64(optarg, LLDB_INVALID_ADDRESS, 16); if (m_start_addr == LLDB_INVALID_ADDRESS) error.SetErrorStringWithFormat ("Invalid start address string '%s'.\n", optarg); break; case 'e': m_end_addr = Args::StringToUInt64(optarg, LLDB_INVALID_ADDRESS, 0); if (m_end_addr == LLDB_INVALID_ADDRESS) m_end_addr = Args::StringToUInt64(optarg, LLDB_INVALID_ADDRESS, 16); if (m_end_addr == LLDB_INVALID_ADDRESS) error.SetErrorStringWithFormat ("Invalid end address string '%s'.\n", optarg); break; case 'n': m_func_name = option_arg; break; case 'r': raw = true; break; default: error.SetErrorStringWithFormat("Unrecognized short option '%c'.\n", short_option); break; } return error; } void CommandObjectDisassemble::CommandOptions::ResetOptionValues () { Options::ResetOptionValues(); show_mixed = false; show_bytes = false; num_lines_context = 0; m_func_name.clear(); m_start_addr = LLDB_INVALID_ADDRESS; m_end_addr = LLDB_INVALID_ADDRESS; raw = false; } const lldb::OptionDefinition* CommandObjectDisassemble::CommandOptions::GetDefinitions () { return g_option_table; } lldb::OptionDefinition CommandObjectDisassemble::CommandOptions::g_option_table[] = { { LLDB_OPT_SET_ALL, false, "bytes", 'b', no_argument, NULL, 0, eArgTypeNone, "Show opcode bytes when disassembling."}, { LLDB_OPT_SET_ALL, false, "context", 'c', required_argument, NULL, 0, eArgTypeNumLines, "Number of context lines of source to show."}, { LLDB_OPT_SET_ALL, false, "mixed", 'm', no_argument, NULL, 0, eArgTypeNone, "Enable mixed source and assembly display."}, { LLDB_OPT_SET_ALL, false, "raw", 'r', no_argument, NULL, 0, eArgTypeNone, "Print raw disassembly with no symbol information."}, { LLDB_OPT_SET_1, true, "start-address", 's', required_argument, NULL, 0, eArgTypeStartAddress, "Address at which to start disassembling."}, { LLDB_OPT_SET_1, false, "end-address", 'e', required_argument, NULL, 0, eArgTypeEndAddress, "Address at which to end disassembling."}, { LLDB_OPT_SET_2, true, "name", 'n', required_argument, NULL, CommandCompletions::eSymbolCompletion, eArgTypeFunctionName, "Disassemble entire contents of the given function name."}, { LLDB_OPT_SET_3, false, "current-frame", 'f', no_argument, NULL, 0, eArgTypeNone, "Disassemble entire contents of the current frame's function."}, { 0, false, NULL, 0, 0, NULL, 0, eArgTypeNone, NULL } }; //------------------------------------------------------------------------- // CommandObjectDisassemble //------------------------------------------------------------------------- CommandObjectDisassemble::CommandObjectDisassemble (CommandInterpreter &interpreter) : CommandObject (interpreter, "disassemble", "Disassemble bytes in the current function, or elsewhere in the executable program as specified by the user.", "disassemble [<cmd-options>]") { } CommandObjectDisassemble::~CommandObjectDisassemble() { } bool CommandObjectDisassemble::Execute ( Args& command, CommandReturnObject &result ) { Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); if (target == NULL) { result.AppendError ("invalid target, set executable file using 'file' command"); result.SetStatus (eReturnStatusFailed); return false; } ArchSpec arch(target->GetArchitecture()); if (!arch.IsValid()) { result.AppendError ("target needs valid architecure in order to be able to disassemble"); result.SetStatus (eReturnStatusFailed); return false; } Disassembler *disassembler = Disassembler::FindPlugin(arch); if (disassembler == NULL) { result.AppendErrorWithFormat ("Unable to find Disassembler plug-in for %s architecture.\n", arch.AsCString()); result.SetStatus (eReturnStatusFailed); return false; } result.SetStatus (eReturnStatusSuccessFinishResult); if (command.GetArgumentCount() != 0) { result.AppendErrorWithFormat ("\"disassemble\" arguments are specified as options.\n"); GetOptions()->GenerateOptionUsage (m_interpreter, result.GetErrorStream(), this); result.SetStatus (eReturnStatusFailed); return false; } ExecutionContext exe_ctx(m_interpreter.GetDebugger().GetExecutionContext()); if (m_options.show_mixed && m_options.num_lines_context == 0) m_options.num_lines_context = 1; if (!m_options.m_func_name.empty()) { ConstString name(m_options.m_func_name.c_str()); if (Disassembler::Disassemble (m_interpreter.GetDebugger(), arch, exe_ctx, name, NULL, // Module * m_options.show_mixed ? m_options.num_lines_context : 0, m_options.show_bytes, result.GetOutputStream())) { result.SetStatus (eReturnStatusSuccessFinishResult); } else { result.AppendErrorWithFormat ("Unable to find symbol with name '%s'.\n", name.GetCString()); result.SetStatus (eReturnStatusFailed); } } else { AddressRange range; if (m_options.m_start_addr != LLDB_INVALID_ADDRESS) { range.GetBaseAddress().SetOffset (m_options.m_start_addr); if (m_options.m_end_addr != LLDB_INVALID_ADDRESS) { if (m_options.m_end_addr < m_options.m_start_addr) { result.AppendErrorWithFormat ("End address before start address.\n"); result.SetStatus (eReturnStatusFailed); return false; } range.SetByteSize (m_options.m_end_addr - m_options.m_start_addr); } else range.SetByteSize (DEFAULT_DISASM_BYTE_SIZE); } else { if (exe_ctx.frame) { SymbolContext sc(exe_ctx.frame->GetSymbolContext(eSymbolContextFunction | eSymbolContextSymbol)); if (sc.function) range = sc.function->GetAddressRange(); else if (sc.symbol && sc.symbol->GetAddressRangePtr()) range = *sc.symbol->GetAddressRangePtr(); else range.GetBaseAddress() = exe_ctx.frame->GetFrameCodeAddress(); } else { result.AppendError ("invalid frame"); result.SetStatus (eReturnStatusFailed); return false; } } if (range.GetByteSize() == 0) range.SetByteSize(DEFAULT_DISASM_BYTE_SIZE); if (Disassembler::Disassemble (m_interpreter.GetDebugger(), arch, exe_ctx, range, m_options.show_mixed ? m_options.num_lines_context : 0, m_options.show_bytes, result.GetOutputStream())) { result.SetStatus (eReturnStatusSuccessFinishResult); } else { result.AppendErrorWithFormat ("Failed to disassemble memory at 0x%8.8llx.\n", m_options.m_start_addr); result.SetStatus (eReturnStatusFailed); } } return result.Succeeded(); } <commit_msg>Comment out uninmplemented command option (-f) for disassemble command.<commit_after>//===-- CommandObjectDisassemble.cpp ----------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "CommandObjectDisassemble.h" // C Includes // C++ Includes // Other libraries and framework includes // Project includes #include "lldb/Core/AddressRange.h" #include "lldb/Interpreter/Args.h" #include "lldb/Interpreter/CommandCompletions.h" #include "lldb/Interpreter/CommandInterpreter.h" #include "lldb/Interpreter/CommandReturnObject.h" #include "lldb/Core/Disassembler.h" #include "lldb/Interpreter/Options.h" #include "lldb/Core/SourceManager.h" #include "lldb/Target/StackFrame.h" #include "lldb/Symbol/Symbol.h" #include "lldb/Target/Process.h" #include "lldb/Target/Target.h" #define DEFAULT_DISASM_BYTE_SIZE 32 using namespace lldb; using namespace lldb_private; CommandObjectDisassemble::CommandOptions::CommandOptions () : Options(), m_func_name(), m_start_addr(), m_end_addr () { ResetOptionValues(); } CommandObjectDisassemble::CommandOptions::~CommandOptions () { } Error CommandObjectDisassemble::CommandOptions::SetOptionValue (int option_idx, const char *option_arg) { Error error; char short_option = (char) m_getopt_table[option_idx].val; switch (short_option) { case 'm': show_mixed = true; break; case 'c': num_lines_context = Args::StringToUInt32(option_arg, 0, 0); break; case 'b': show_bytes = true; break; case 's': m_start_addr = Args::StringToUInt64(optarg, LLDB_INVALID_ADDRESS, 0); if (m_start_addr == LLDB_INVALID_ADDRESS) m_start_addr = Args::StringToUInt64(optarg, LLDB_INVALID_ADDRESS, 16); if (m_start_addr == LLDB_INVALID_ADDRESS) error.SetErrorStringWithFormat ("Invalid start address string '%s'.\n", optarg); break; case 'e': m_end_addr = Args::StringToUInt64(optarg, LLDB_INVALID_ADDRESS, 0); if (m_end_addr == LLDB_INVALID_ADDRESS) m_end_addr = Args::StringToUInt64(optarg, LLDB_INVALID_ADDRESS, 16); if (m_end_addr == LLDB_INVALID_ADDRESS) error.SetErrorStringWithFormat ("Invalid end address string '%s'.\n", optarg); break; case 'n': m_func_name = option_arg; break; case 'r': raw = true; break; default: error.SetErrorStringWithFormat("Unrecognized short option '%c'.\n", short_option); break; } return error; } void CommandObjectDisassemble::CommandOptions::ResetOptionValues () { Options::ResetOptionValues(); show_mixed = false; show_bytes = false; num_lines_context = 0; m_func_name.clear(); m_start_addr = LLDB_INVALID_ADDRESS; m_end_addr = LLDB_INVALID_ADDRESS; raw = false; } const lldb::OptionDefinition* CommandObjectDisassemble::CommandOptions::GetDefinitions () { return g_option_table; } lldb::OptionDefinition CommandObjectDisassemble::CommandOptions::g_option_table[] = { { LLDB_OPT_SET_ALL, false, "bytes", 'b', no_argument, NULL, 0, eArgTypeNone, "Show opcode bytes when disassembling."}, { LLDB_OPT_SET_ALL, false, "context", 'c', required_argument, NULL, 0, eArgTypeNumLines, "Number of context lines of source to show."}, { LLDB_OPT_SET_ALL, false, "mixed", 'm', no_argument, NULL, 0, eArgTypeNone, "Enable mixed source and assembly display."}, { LLDB_OPT_SET_ALL, false, "raw", 'r', no_argument, NULL, 0, eArgTypeNone, "Print raw disassembly with no symbol information."}, { LLDB_OPT_SET_1, true, "start-address", 's', required_argument, NULL, 0, eArgTypeStartAddress, "Address at which to start disassembling."}, { LLDB_OPT_SET_1, false, "end-address", 'e', required_argument, NULL, 0, eArgTypeEndAddress, "Address at which to end disassembling."}, { LLDB_OPT_SET_2, true, "name", 'n', required_argument, NULL, CommandCompletions::eSymbolCompletion, eArgTypeFunctionName, "Disassemble entire contents of the given function name."}, //{ LLDB_OPT_SET_3, false, "current-frame", 'f', no_argument, NULL, 0, eArgTypeNone, "Disassemble entire contents of the current frame's function."}, { 0, false, NULL, 0, 0, NULL, 0, eArgTypeNone, NULL } }; //------------------------------------------------------------------------- // CommandObjectDisassemble //------------------------------------------------------------------------- CommandObjectDisassemble::CommandObjectDisassemble (CommandInterpreter &interpreter) : CommandObject (interpreter, "disassemble", "Disassemble bytes in the current function, or elsewhere in the executable program as specified by the user.", "disassemble [<cmd-options>]") { } CommandObjectDisassemble::~CommandObjectDisassemble() { } bool CommandObjectDisassemble::Execute ( Args& command, CommandReturnObject &result ) { Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); if (target == NULL) { result.AppendError ("invalid target, set executable file using 'file' command"); result.SetStatus (eReturnStatusFailed); return false; } ArchSpec arch(target->GetArchitecture()); if (!arch.IsValid()) { result.AppendError ("target needs valid architecure in order to be able to disassemble"); result.SetStatus (eReturnStatusFailed); return false; } Disassembler *disassembler = Disassembler::FindPlugin(arch); if (disassembler == NULL) { result.AppendErrorWithFormat ("Unable to find Disassembler plug-in for %s architecture.\n", arch.AsCString()); result.SetStatus (eReturnStatusFailed); return false; } result.SetStatus (eReturnStatusSuccessFinishResult); if (command.GetArgumentCount() != 0) { result.AppendErrorWithFormat ("\"disassemble\" arguments are specified as options.\n"); GetOptions()->GenerateOptionUsage (m_interpreter, result.GetErrorStream(), this); result.SetStatus (eReturnStatusFailed); return false; } ExecutionContext exe_ctx(m_interpreter.GetDebugger().GetExecutionContext()); if (m_options.show_mixed && m_options.num_lines_context == 0) m_options.num_lines_context = 1; if (!m_options.m_func_name.empty()) { ConstString name(m_options.m_func_name.c_str()); if (Disassembler::Disassemble (m_interpreter.GetDebugger(), arch, exe_ctx, name, NULL, // Module * m_options.show_mixed ? m_options.num_lines_context : 0, m_options.show_bytes, result.GetOutputStream())) { result.SetStatus (eReturnStatusSuccessFinishResult); } else { result.AppendErrorWithFormat ("Unable to find symbol with name '%s'.\n", name.GetCString()); result.SetStatus (eReturnStatusFailed); } } else { AddressRange range; if (m_options.m_start_addr != LLDB_INVALID_ADDRESS) { range.GetBaseAddress().SetOffset (m_options.m_start_addr); if (m_options.m_end_addr != LLDB_INVALID_ADDRESS) { if (m_options.m_end_addr < m_options.m_start_addr) { result.AppendErrorWithFormat ("End address before start address.\n"); result.SetStatus (eReturnStatusFailed); return false; } range.SetByteSize (m_options.m_end_addr - m_options.m_start_addr); } else range.SetByteSize (DEFAULT_DISASM_BYTE_SIZE); } else { if (exe_ctx.frame) { SymbolContext sc(exe_ctx.frame->GetSymbolContext(eSymbolContextFunction | eSymbolContextSymbol)); if (sc.function) range = sc.function->GetAddressRange(); else if (sc.symbol && sc.symbol->GetAddressRangePtr()) range = *sc.symbol->GetAddressRangePtr(); else range.GetBaseAddress() = exe_ctx.frame->GetFrameCodeAddress(); } else { result.AppendError ("invalid frame"); result.SetStatus (eReturnStatusFailed); return false; } } if (range.GetByteSize() == 0) range.SetByteSize(DEFAULT_DISASM_BYTE_SIZE); if (Disassembler::Disassemble (m_interpreter.GetDebugger(), arch, exe_ctx, range, m_options.show_mixed ? m_options.num_lines_context : 0, m_options.show_bytes, result.GetOutputStream())) { result.SetStatus (eReturnStatusSuccessFinishResult); } else { result.AppendErrorWithFormat ("Failed to disassemble memory at 0x%8.8llx.\n", m_options.m_start_addr); result.SetStatus (eReturnStatusFailed); } } return result.Succeeded(); } <|endoftext|>
<commit_before>#include "generator/cross_mwm_osm_ways_collector.hpp" #include "generator/feature_builder.hpp" #include "generator/osm_element.hpp" #include "routing/routing_helpers.hpp" #include "platform/platform.hpp" #include "base/assert.hpp" #include "base/file_name_utils.hpp" #include "base/logging.hpp" #include <utility> namespace generator { // CrossMwmOsmWaysCollector ------------------------------------------------------------------------ CrossMwmOsmWaysCollector::CrossMwmOsmWaysCollector(std::string intermediateDir, std::string const & targetDir, bool haveBordersForWholeWorld) : m_intermediateDir(std::move(intermediateDir)) { m_affiliation = std::make_shared<feature::CountriesFilesAffiliation>(targetDir, haveBordersForWholeWorld); } CrossMwmOsmWaysCollector::CrossMwmOsmWaysCollector( std::string intermediateDir, std::shared_ptr<feature::CountriesFilesAffiliation> affiliation) : m_intermediateDir(std::move(intermediateDir)), m_affiliation(std::move(affiliation)) { } std::shared_ptr<CollectorInterface> CrossMwmOsmWaysCollector::Clone(std::shared_ptr<cache::IntermediateDataReader> const &) const { return std::make_shared<CrossMwmOsmWaysCollector>(m_intermediateDir, m_affiliation); } void CrossMwmOsmWaysCollector::CollectFeature(feature::FeatureBuilder const & fb, OsmElement const & element) { if (element.m_type != OsmElement::EntityType::Way) return; if (!routing::IsRoad(fb.GetTypes())) return; auto const & affiliations = m_affiliation->GetAffiliations(fb); if (affiliations.empty()) return; auto const & featurePoints = fb.GetOuterGeometry(); std::map<std::string, std::vector<bool>> featurePointsEntriesToMwm; for (auto const & mwmName : affiliations) featurePointsEntriesToMwm[mwmName] = std::vector<bool>(featurePoints.size(), false); std::vector<size_t> pointsAffiliationsNumber(featurePoints.size()); for (size_t pointNumber = 0; pointNumber < featurePoints.size(); ++pointNumber) { auto const & point = featurePoints[pointNumber]; auto const & pointAffiliations = m_affiliation->GetAffiliations(point); for (auto const & mwmName : pointAffiliations) featurePointsEntriesToMwm[mwmName][pointNumber] = true; // TODO (@gmoryes) // Uncomment this check after: https://github.com/mapsme/omim/pull/10996 // It could happend when point places between mwm's borders and doesn't belong to any of them. // CHECK_GREATER(pointAffiliations.size(), 0, ()); pointsAffiliationsNumber[pointNumber] = pointAffiliations.size(); } for (auto const & item : featurePointsEntriesToMwm) { auto const & mwmName = item.first; auto const & entries = item.second; std::vector<CrossMwmInfo::SegmentInfo> crossMwmSegments; bool prevPointIn = entries[0]; for (size_t i = 1; i < entries.size(); ++i) { bool curPointIn = entries[i]; // We must be sure below that either both points belong to mwm either one of them belongs. if (!curPointIn && !prevPointIn) continue; // If pointsAffiliationsNumber[i] is more than 1, that means point lies on the mwms' borders // And belongs to both. So we consider such segment as cross mwm segment. // So the condition that segment certainly lies inside of mwm is: // both points inside and both points belong to only this mwm. if (prevPointIn && curPointIn && pointsAffiliationsNumber[i] == 1 && pointsAffiliationsNumber[i - 1] == 1) { continue; } bool forwardIsEnter; if (prevPointIn != curPointIn) { forwardIsEnter = curPointIn; } else { if (pointsAffiliationsNumber[i - 1] != 1) forwardIsEnter = curPointIn; else if (pointsAffiliationsNumber[i] != 1) forwardIsEnter = !prevPointIn; else UNREACHABLE(); } prevPointIn = curPointIn; crossMwmSegments.emplace_back(i - 1 /* segmentId */, forwardIsEnter); } if (crossMwmSegments.empty()) return; m_mwmToCrossMwmOsmIds[mwmName].emplace_back(element.m_id, std::move(crossMwmSegments)); } } void CrossMwmOsmWaysCollector::Save() { auto const & crossMwmOsmWaysDir = base::JoinPath(m_intermediateDir, CROSS_MWM_OSM_WAYS_DIR); CHECK(Platform::MkDirChecked(crossMwmOsmWaysDir), (crossMwmOsmWaysDir)); for (auto const & item : m_mwmToCrossMwmOsmIds) { auto const & mwmName = item.first; auto const & waysInfo = item.second; auto const & pathToCrossMwmOsmIds = base::JoinPath(crossMwmOsmWaysDir, mwmName); std::ofstream output; output.exceptions(std::fstream::failbit | std::fstream::badbit); output.open(pathToCrossMwmOsmIds); for (auto const & wayInfo : waysInfo) CrossMwmInfo::Dump(wayInfo, output); } } void CrossMwmOsmWaysCollector::Merge(generator::CollectorInterface const & collector) { collector.MergeInto(*this); } void CrossMwmOsmWaysCollector::MergeInto(CrossMwmOsmWaysCollector & collector) const { for (auto const & item : m_mwmToCrossMwmOsmIds) { auto const & mwmName = item.first; auto const & osmIds = item.second; auto & otherOsmIds = collector.m_mwmToCrossMwmOsmIds[mwmName]; otherOsmIds.insert(otherOsmIds.end(), osmIds.cbegin(), osmIds.cend()); } } // CrossMwmOsmWaysCollector::Info ------------------------------------------------------------------ bool CrossMwmOsmWaysCollector::CrossMwmInfo::operator<(CrossMwmInfo const & rhs) const { return m_osmId < rhs.m_osmId; } // static void CrossMwmOsmWaysCollector::CrossMwmInfo::Dump(CrossMwmInfo const & info, std::ofstream & output) { output << base::MakeOsmWay(info.m_osmId) << " " << info.m_crossMwmSegments.size() << " "; for (auto const & segmentInfo : info.m_crossMwmSegments) output << segmentInfo.m_segmentId << " " << segmentInfo.m_forwardIsEnter << " "; output << std::endl; } // static std::set<CrossMwmOsmWaysCollector::CrossMwmInfo> CrossMwmOsmWaysCollector::CrossMwmInfo::LoadFromFileToSet(std::string const & path) { if (!Platform::IsFileExistsByFullPath(path)) { LOG(LWARNING, ("No info about cross mwm ways:", path)); return {}; } std::set<CrossMwmInfo> result; std::ifstream input; input.exceptions(std::fstream::failbit | std::fstream::badbit); input.open(path); input.exceptions(std::fstream::badbit); uint64_t osmId; size_t segmentsNumber; while (input >> osmId >> segmentsNumber) { std::vector<SegmentInfo> segments; CHECK_NOT_EQUAL(segmentsNumber, 0, ()); segments.resize(segmentsNumber); for (size_t j = 0; j < segmentsNumber; ++j) input >> segments[j].m_segmentId >> segments[j].m_forwardIsEnter; result.emplace(osmId, std::move(segments)); } return result; } } // namespace generator <commit_msg>[generator] Fix for segmentation fault in cross mwm collector.<commit_after>#include "generator/cross_mwm_osm_ways_collector.hpp" #include "generator/feature_builder.hpp" #include "generator/osm_element.hpp" #include "routing/routing_helpers.hpp" #include "platform/platform.hpp" #include "base/assert.hpp" #include "base/file_name_utils.hpp" #include "base/logging.hpp" #include <utility> namespace generator { // CrossMwmOsmWaysCollector ------------------------------------------------------------------------ CrossMwmOsmWaysCollector::CrossMwmOsmWaysCollector(std::string intermediateDir, std::string const & targetDir, bool haveBordersForWholeWorld) : m_intermediateDir(std::move(intermediateDir)) { m_affiliation = std::make_shared<feature::CountriesFilesAffiliation>(targetDir, haveBordersForWholeWorld); } CrossMwmOsmWaysCollector::CrossMwmOsmWaysCollector( std::string intermediateDir, std::shared_ptr<feature::CountriesFilesAffiliation> affiliation) : m_intermediateDir(std::move(intermediateDir)), m_affiliation(std::move(affiliation)) { } std::shared_ptr<CollectorInterface> CrossMwmOsmWaysCollector::Clone(std::shared_ptr<cache::IntermediateDataReader> const &) const { return std::make_shared<CrossMwmOsmWaysCollector>(m_intermediateDir, m_affiliation); } void CrossMwmOsmWaysCollector::CollectFeature(feature::FeatureBuilder const & fb, OsmElement const & element) { if (element.m_type != OsmElement::EntityType::Way) return; if (!routing::IsRoad(fb.GetTypes())) return; auto const & affiliations = m_affiliation->GetAffiliations(fb); if (affiliations.empty()) return; auto const & featurePoints = fb.GetOuterGeometry(); std::map<std::string, std::vector<bool>> featurePointsEntriesToMwm; for (auto const & mwmName : affiliations) featurePointsEntriesToMwm[mwmName] = std::vector<bool>(featurePoints.size(), false); std::vector<size_t> pointsAffiliationsNumber(featurePoints.size()); for (size_t pointNumber = 0; pointNumber < featurePoints.size(); ++pointNumber) { auto const & point = featurePoints[pointNumber]; auto const & pointAffiliations = m_affiliation->GetAffiliations(point); for (auto const & mwmName : pointAffiliations) { // Skip mwms which are not present in the map: these are GetAffiliations() false positives. auto it = featurePointsEntriesToMwm.find(mwmName); if (it == featurePointsEntriesToMwm.end()) continue; it->second[pointNumber] = true; } // TODO (@gmoryes) // Uncomment this check after: https://github.com/mapsme/omim/pull/10996 // It could happend when point places between mwm's borders and doesn't belong to any of them. // CHECK_GREATER(pointAffiliations.size(), 0, ()); pointsAffiliationsNumber[pointNumber] = pointAffiliations.size(); } for (auto const & item : featurePointsEntriesToMwm) { auto const & mwmName = item.first; auto const & entries = item.second; std::vector<CrossMwmInfo::SegmentInfo> crossMwmSegments; bool prevPointIn = entries[0]; for (size_t i = 1; i < entries.size(); ++i) { bool curPointIn = entries[i]; // We must be sure below that either both points belong to mwm either one of them belongs. if (!curPointIn && !prevPointIn) continue; // If pointsAffiliationsNumber[i] is more than 1, that means point lies on the mwms' borders // And belongs to both. So we consider such segment as cross mwm segment. // So the condition that segment certainly lies inside of mwm is: // both points inside and both points belong to only this mwm. if (prevPointIn && curPointIn && pointsAffiliationsNumber[i] == 1 && pointsAffiliationsNumber[i - 1] == 1) { continue; } bool forwardIsEnter; if (prevPointIn != curPointIn) { forwardIsEnter = curPointIn; } else { if (pointsAffiliationsNumber[i - 1] != 1) forwardIsEnter = curPointIn; else if (pointsAffiliationsNumber[i] != 1) forwardIsEnter = !prevPointIn; else UNREACHABLE(); } prevPointIn = curPointIn; crossMwmSegments.emplace_back(i - 1 /* segmentId */, forwardIsEnter); } if (crossMwmSegments.empty()) return; m_mwmToCrossMwmOsmIds[mwmName].emplace_back(element.m_id, std::move(crossMwmSegments)); } } void CrossMwmOsmWaysCollector::Save() { auto const & crossMwmOsmWaysDir = base::JoinPath(m_intermediateDir, CROSS_MWM_OSM_WAYS_DIR); CHECK(Platform::MkDirChecked(crossMwmOsmWaysDir), (crossMwmOsmWaysDir)); for (auto const & item : m_mwmToCrossMwmOsmIds) { auto const & mwmName = item.first; auto const & waysInfo = item.second; auto const & pathToCrossMwmOsmIds = base::JoinPath(crossMwmOsmWaysDir, mwmName); std::ofstream output; output.exceptions(std::fstream::failbit | std::fstream::badbit); output.open(pathToCrossMwmOsmIds); for (auto const & wayInfo : waysInfo) CrossMwmInfo::Dump(wayInfo, output); } } void CrossMwmOsmWaysCollector::Merge(generator::CollectorInterface const & collector) { collector.MergeInto(*this); } void CrossMwmOsmWaysCollector::MergeInto(CrossMwmOsmWaysCollector & collector) const { for (auto const & item : m_mwmToCrossMwmOsmIds) { auto const & mwmName = item.first; auto const & osmIds = item.second; auto & otherOsmIds = collector.m_mwmToCrossMwmOsmIds[mwmName]; otherOsmIds.insert(otherOsmIds.end(), osmIds.cbegin(), osmIds.cend()); } } // CrossMwmOsmWaysCollector::Info ------------------------------------------------------------------ bool CrossMwmOsmWaysCollector::CrossMwmInfo::operator<(CrossMwmInfo const & rhs) const { return m_osmId < rhs.m_osmId; } // static void CrossMwmOsmWaysCollector::CrossMwmInfo::Dump(CrossMwmInfo const & info, std::ofstream & output) { output << base::MakeOsmWay(info.m_osmId) << " " << info.m_crossMwmSegments.size() << " "; for (auto const & segmentInfo : info.m_crossMwmSegments) output << segmentInfo.m_segmentId << " " << segmentInfo.m_forwardIsEnter << " "; output << std::endl; } // static std::set<CrossMwmOsmWaysCollector::CrossMwmInfo> CrossMwmOsmWaysCollector::CrossMwmInfo::LoadFromFileToSet(std::string const & path) { if (!Platform::IsFileExistsByFullPath(path)) { LOG(LWARNING, ("No info about cross mwm ways:", path)); return {}; } std::set<CrossMwmInfo> result; std::ifstream input; input.exceptions(std::fstream::failbit | std::fstream::badbit); input.open(path); input.exceptions(std::fstream::badbit); uint64_t osmId; size_t segmentsNumber; while (input >> osmId >> segmentsNumber) { std::vector<SegmentInfo> segments; CHECK_NOT_EQUAL(segmentsNumber, 0, ()); segments.resize(segmentsNumber); for (size_t j = 0; j < segmentsNumber; ++j) input >> segments[j].m_segmentId >> segments[j].m_forwardIsEnter; result.emplace(osmId, std::move(segments)); } return result; } } // namespace generator <|endoftext|>
<commit_before>/* */ #include <v8.h> #include <unistd.h> #include <stdlib.h> #include <sys/stat.h> #include <fcntl.h> #include <ev.h> #include <sys/time.h> #include <sys/resource.h> #include <node.h> using namespace v8; Handle<Value> GetCPUTime(const Arguments& args) { struct rusage ru; getrusage(RUSAGE_SELF, &ru); return Number::New( (double)ru.ru_utime.tv_sec + (double)ru.ru_utime.tv_usec * 1e-6 + (double)ru.ru_stime.tv_sec + (double)ru.ru_stime.tv_usec * 1e-6); } Handle<Value> GetSystemTime(const Arguments& args) { struct rusage ru; getrusage(RUSAGE_SELF, &ru); return Number::New( (double)ru.ru_stime.tv_sec + (double)ru.ru_stime.tv_usec * 1e-6); } static Handle<Value> timevalToNumber(struct timeval &tim) { return Number::New((double)tim.tv_sec + (double)tim.tv_usec * 1e-6); } Handle<Value> GetUsage(const Arguments& args) { HandleScope scope; struct rusage ru; getrusage(RUSAGE_SELF, &ru); Local<Object> info = Object::New(); #define FIELD(name, conv) \ info->Set(String::NewSymbol(#name), conv(ru.ru_##name)) FIELD(utime, timevalToNumber); /* user time used */ FIELD(stime, timevalToNumber); /* system time used */ FIELD(maxrss, Number::New); /* maximum resident set size */ FIELD(ixrss, Number::New); /* integral shared memory size */ FIELD(idrss, Number::New); /* integral unshared data size */ FIELD(isrss, Number::New); /* integral unshared stack size */ FIELD(minflt, Number::New); /* page reclaims */ FIELD(majflt, Number::New); /* page faults */ FIELD(nswap, Number::New); /* swaps */ FIELD(inblock, Number::New); /* block input operations */ FIELD(oublock, Number::New); /* block output operations */ FIELD(msgsnd, Number::New); /* messages sent */ FIELD(msgrcv, Number::New); /* messages received */ FIELD(nsignals, Number::New); /* signals received */ FIELD(nvcsw, Number::New); /* voluntary context switches */ FIELD(nivcsw, Number::New); /* involuntary context switches */ #undef FIELD return scope.Close(info); } extern "C" void init(Handle<Object> target) { HandleScope scope; target->Set(String::New("usage"), FunctionTemplate::New(GetUsage)->GetFunction()); target->Set(String::New("getcputime"), FunctionTemplate::New(GetCPUTime)->GetFunction()); target->Set(String::New("getsystemtime"), FunctionTemplate::New(GetSystemTime)->GetFunction()); } <commit_msg>Remove unused <ev.h> import.<commit_after>/* */ #include <v8.h> #include <unistd.h> #include <stdlib.h> #include <sys/stat.h> #include <fcntl.h> #include <sys/time.h> #include <sys/resource.h> #include <node.h> using namespace v8; Handle<Value> GetCPUTime(const Arguments& args) { struct rusage ru; getrusage(RUSAGE_SELF, &ru); return Number::New( (double)ru.ru_utime.tv_sec + (double)ru.ru_utime.tv_usec * 1e-6 + (double)ru.ru_stime.tv_sec + (double)ru.ru_stime.tv_usec * 1e-6); } Handle<Value> GetSystemTime(const Arguments& args) { struct rusage ru; getrusage(RUSAGE_SELF, &ru); return Number::New( (double)ru.ru_stime.tv_sec + (double)ru.ru_stime.tv_usec * 1e-6); } static Handle<Value> timevalToNumber(struct timeval &tim) { return Number::New((double)tim.tv_sec + (double)tim.tv_usec * 1e-6); } Handle<Value> GetUsage(const Arguments& args) { HandleScope scope; struct rusage ru; getrusage(RUSAGE_SELF, &ru); Local<Object> info = Object::New(); #define FIELD(name, conv) \ info->Set(String::NewSymbol(#name), conv(ru.ru_##name)) FIELD(utime, timevalToNumber); /* user time used */ FIELD(stime, timevalToNumber); /* system time used */ FIELD(maxrss, Number::New); /* maximum resident set size */ FIELD(ixrss, Number::New); /* integral shared memory size */ FIELD(idrss, Number::New); /* integral unshared data size */ FIELD(isrss, Number::New); /* integral unshared stack size */ FIELD(minflt, Number::New); /* page reclaims */ FIELD(majflt, Number::New); /* page faults */ FIELD(nswap, Number::New); /* swaps */ FIELD(inblock, Number::New); /* block input operations */ FIELD(oublock, Number::New); /* block output operations */ FIELD(msgsnd, Number::New); /* messages sent */ FIELD(msgrcv, Number::New); /* messages received */ FIELD(nsignals, Number::New); /* signals received */ FIELD(nvcsw, Number::New); /* voluntary context switches */ FIELD(nivcsw, Number::New); /* involuntary context switches */ #undef FIELD return scope.Close(info); } extern "C" void init(Handle<Object> target) { HandleScope scope; target->Set(String::New("usage"), FunctionTemplate::New(GetUsage)->GetFunction()); target->Set(String::New("getcputime"), FunctionTemplate::New(GetCPUTime)->GetFunction()); target->Set(String::New("getsystemtime"), FunctionTemplate::New(GetSystemTime)->GetFunction()); } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: anminfo.hxx,v $ * * $Revision: 1.1.1.1 $ * * last change: $Author: hr $ $Date: 2000-09-18 16:48:27 $ * * 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 _SD_ANMINFO_HXX #define _SD_ANMINFO_HXX #ifndef _COM_SUN_STAR_PRESENTATION_ANIMATIONEFFECT_HPP_ #include <com/sun/star/presentation/AnimationEffect.hpp> #endif #ifndef _COM_SUN_STAR_PRESENTATION_ANIMATIONSPEED_HPP_ #include <com/sun/star/presentation/AnimationSpeed.hpp> #endif #ifndef _COM_SUN_STAR_PRESENTATION_CLICKACTION_HPP_ #include <com/sun/star/presentation/ClickAction.hpp> #endif #ifndef _SD_ANMDEF_HXX #include "anmdef.hxx" #endif #ifndef _SVDOBJ_HXX //autogen #include <svx/svdobj.hxx> #endif #ifndef _SV_COLOR_HXX //autogen #include <vcl/color.hxx> #endif class Polygon; class Point; class SvStream; class SdrObjSurrogate; class SdrObject; class SdrPathObj; class SdDrawDocument; class SdAnimationInfo : public SdrObjUserData, public SfxListener { private: SdDrawDocument* pDoc; public: Polygon* pPolygon; // fuer nichtlinearen Pfad (unbenutzt) Point aStart; // Startpunkt eines linearen Pfades (unbenutzt) Point aEnd; // Endpunkt eines linearen Pfades (unbenutzt) ::com::sun::star::presentation::AnimationEffect eEffect; // Animationseffekt ::com::sun::star::presentation::AnimationEffect eTextEffect; // Animationseffekt fuer Textinhalt ::com::sun::star::presentation::AnimationSpeed eSpeed; // Geschwindigkeit der Animation BOOL bActive; // eingeschaltet ? BOOL bDimPrevious; // Objekt abblenden BOOL bIsMovie; // wenn Gruppenobjekt, dann Sequenz aus den BOOL bDimHide; // verstecken statt abblenden Color aBlueScreen; // identifiziert "Hintergrundpixel" Color aDimColor; // zum Abblenden des Objekts String aSoundFile; // Pfad zum Soundfile in MSDOS-Notation BOOL bSoundOn; // Sound ein/aus BOOL bPlayFull; // Sound ganz abspielen SdrObjSurrogate* pPathSuro; // Surrogat fuer pPathObj SdrPathObj* pPathObj; // das Pfadobjekt ::com::sun::star::presentation::ClickAction eClickAction; // Aktion bei Mausklick ::com::sun::star::presentation::AnimationEffect eSecondEffect; // fuer Objekt ausblenden ::com::sun::star::presentation::AnimationSpeed eSecondSpeed; // fuer Objekt ausblenden String aSecondSoundFile; // fuer Objekt ausblenden BOOL bSecondSoundOn; // fuer Objekt ausblenden BOOL bSecondPlayFull;// fuer Objekt ausblenden String aBookmark; // Sprung zu Objekt/Seite USHORT nVerb; // fuer OLE-Objekt BOOL bInvisibleInPresentation; BOOL bIsShown; // in der Show gerade sichtbar, NICHT PERSISTENT! BOOL bShow; // Befehl: mit 1. Effekt zeigen (TRUE) // oder mit 2. Effekt entfernen (FALSE) // NICHT PERSISTENT! BOOL bDimmed; // in der Show abgeblendet (TRUE) oder // nicht (TRUE) // NICHT PERSISTENT! ULONG nPresOrder; SdAnimationInfo(SdDrawDocument* pTheDoc); SdAnimationInfo(const SdAnimationInfo& rAnmInfo); virtual ~SdAnimationInfo(); virtual SdrObjUserData* Clone(SdrObject* pObj) const; virtual void WriteData(SvStream& rOut); virtual void ReadData(SvStream& rIn); // NULL loest die Verbindung zum Pfadobjekt void SetPath(SdrPathObj* pPath = NULL); virtual void SFX_NOTIFY(SfxBroadcaster& rBC, const TypeId& rBCType, const SfxHint& rHint, const TypeId& rHintType); virtual void AfterRead(); }; #endif // _SD_ANMINFO_HXX <commit_msg>INTEGRATION: CWS vclcleanup02 (1.1.1.1.336); FILE MERGED 2003/12/11 09:17:21 mt 1.1.1.1.336.1: #i23061# VCL cleanup, removed headers, methods and types...<commit_after>/************************************************************************* * * $RCSfile: anminfo.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: vg $ $Date: 2004-01-06 18:42:25 $ * * 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 _SD_ANMINFO_HXX #define _SD_ANMINFO_HXX #ifndef _COM_SUN_STAR_PRESENTATION_ANIMATIONEFFECT_HPP_ #include <com/sun/star/presentation/AnimationEffect.hpp> #endif #ifndef _COM_SUN_STAR_PRESENTATION_ANIMATIONSPEED_HPP_ #include <com/sun/star/presentation/AnimationSpeed.hpp> #endif #ifndef _COM_SUN_STAR_PRESENTATION_CLICKACTION_HPP_ #include <com/sun/star/presentation/ClickAction.hpp> #endif #ifndef _SD_ANMDEF_HXX #include "anmdef.hxx" #endif #ifndef _SVDOBJ_HXX //autogen #include <svx/svdobj.hxx> #endif #ifndef _TOOLS_COLOR_HXX #include <tools/color.hxx> #endif class Polygon; class Point; class SvStream; class SdrObjSurrogate; class SdrObject; class SdrPathObj; class SdDrawDocument; class SdAnimationInfo : public SdrObjUserData, public SfxListener { private: SdDrawDocument* pDoc; public: Polygon* pPolygon; // fuer nichtlinearen Pfad (unbenutzt) Point aStart; // Startpunkt eines linearen Pfades (unbenutzt) Point aEnd; // Endpunkt eines linearen Pfades (unbenutzt) ::com::sun::star::presentation::AnimationEffect eEffect; // Animationseffekt ::com::sun::star::presentation::AnimationEffect eTextEffect; // Animationseffekt fuer Textinhalt ::com::sun::star::presentation::AnimationSpeed eSpeed; // Geschwindigkeit der Animation BOOL bActive; // eingeschaltet ? BOOL bDimPrevious; // Objekt abblenden BOOL bIsMovie; // wenn Gruppenobjekt, dann Sequenz aus den BOOL bDimHide; // verstecken statt abblenden Color aBlueScreen; // identifiziert "Hintergrundpixel" Color aDimColor; // zum Abblenden des Objekts String aSoundFile; // Pfad zum Soundfile in MSDOS-Notation BOOL bSoundOn; // Sound ein/aus BOOL bPlayFull; // Sound ganz abspielen SdrObjSurrogate* pPathSuro; // Surrogat fuer pPathObj SdrPathObj* pPathObj; // das Pfadobjekt ::com::sun::star::presentation::ClickAction eClickAction; // Aktion bei Mausklick ::com::sun::star::presentation::AnimationEffect eSecondEffect; // fuer Objekt ausblenden ::com::sun::star::presentation::AnimationSpeed eSecondSpeed; // fuer Objekt ausblenden String aSecondSoundFile; // fuer Objekt ausblenden BOOL bSecondSoundOn; // fuer Objekt ausblenden BOOL bSecondPlayFull;// fuer Objekt ausblenden String aBookmark; // Sprung zu Objekt/Seite USHORT nVerb; // fuer OLE-Objekt BOOL bInvisibleInPresentation; BOOL bIsShown; // in der Show gerade sichtbar, NICHT PERSISTENT! BOOL bShow; // Befehl: mit 1. Effekt zeigen (TRUE) // oder mit 2. Effekt entfernen (FALSE) // NICHT PERSISTENT! BOOL bDimmed; // in der Show abgeblendet (TRUE) oder // nicht (TRUE) // NICHT PERSISTENT! ULONG nPresOrder; SdAnimationInfo(SdDrawDocument* pTheDoc); SdAnimationInfo(const SdAnimationInfo& rAnmInfo); virtual ~SdAnimationInfo(); virtual SdrObjUserData* Clone(SdrObject* pObj) const; virtual void WriteData(SvStream& rOut); virtual void ReadData(SvStream& rIn); // NULL loest die Verbindung zum Pfadobjekt void SetPath(SdrPathObj* pPath = NULL); virtual void SFX_NOTIFY(SfxBroadcaster& rBC, const TypeId& rBCType, const SfxHint& rHint, const TypeId& rHintType); virtual void AfterRead(); }; #endif // _SD_ANMINFO_HXX <|endoftext|>
<commit_before>/* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "gm.h" #include "SkSurface.h" #include "SkCanvas.h" #include "SkStream.h" #include "SkData.h" extern GrContext* GetGr(); static SkData* fileToData(const char path[]) { SkFILEStream stream(path); if (!stream.isValid()) { return SkData::NewEmpty(); } size_t size = stream.getLength(); void* mem = sk_malloc_throw(size); stream.read(mem, size); return SkData::NewFromMalloc(mem, size); } static void drawJpeg(SkCanvas* canvas, const SkISize& size) { SkAutoDataUnref data(fileToData("/Users/mike/Downloads/skia.google.jpeg")); SkImage* image = SkImage::NewEncodedData(data); if (image) { SkAutoCanvasRestore acr(canvas, true); canvas->scale(size.width() * 1.0f / image->width(), size.height() * 1.0f / image->height()); image->draw(canvas,0, 0, NULL); image->unref(); } } static void drawContents(SkSurface* surface, SkColor fillC) { SkSize size = SkSize::Make(surface->width(), surface->height()); SkCanvas* canvas = surface->getCanvas(); SkScalar stroke = size.fWidth / 10; SkScalar radius = (size.fWidth - stroke) / 2; SkPaint paint; paint.setAntiAlias(true); paint.setColor(fillC); canvas->drawCircle(size.fWidth/2, size.fHeight/2, radius, paint); paint.setStyle(SkPaint::kStroke_Style); paint.setStrokeWidth(stroke); paint.setColor(SK_ColorBLACK); canvas->drawCircle(size.fWidth/2, size.fHeight/2, radius, paint); } static void test_surface(SkCanvas* canvas, SkSurface* surf) { drawContents(surf, SK_ColorRED); SkImage* imgR = surf->newImageShapshot(); if (true) { SkImage* imgR2 = surf->newImageShapshot(); SkASSERT(imgR == imgR2); imgR2->unref(); } drawContents(surf, SK_ColorGREEN); SkImage* imgG = surf->newImageShapshot(); // since we've drawn after we snapped imgR, imgG will be a different obj SkASSERT(imgR != imgG); drawContents(surf, SK_ColorBLUE); SkPaint paint; // paint.setFilterBitmap(true); // paint.setAlpha(0x80); imgR->draw(canvas, 0, 0, &paint); imgG->draw(canvas, 0, 80, &paint); surf->draw(canvas, 0, 160, &paint); imgG->unref(); imgR->unref(); } class ImageGM : public skiagm::GM { void* fBuffer; size_t fBufferSize; SkSize fSize; enum { W = 64, H = 64, RB = W * 4 + 8, }; public: ImageGM() { fBufferSize = RB * H; fBuffer = sk_malloc_throw(fBufferSize); fSize.set(SkIntToScalar(W), SkIntToScalar(H)); } virtual ~ImageGM() { sk_free(fBuffer); } protected: virtual SkString onShortName() { return SkString("image"); } virtual SkISize onISize() { return SkISize::Make(640, 480); } virtual void onDraw(SkCanvas* canvas) { drawJpeg(canvas, this->getISize()); canvas->translate(10, 10); canvas->scale(2, 2); // since we draw into this directly, we need to start fresh sk_bzero(fBuffer, fBufferSize); SkImage::Info info; info.fWidth = W; info.fHeight = H; info.fColorType = SkImage::kPMColor_ColorType; info.fAlphaType = SkImage::kPremul_AlphaType; SkAutoTUnref<SkSurface> surf0(SkSurface::NewRasterDirect(info, NULL, fBuffer, RB)); SkAutoTUnref<SkSurface> surf1(SkSurface::NewRaster(info, NULL)); SkAutoTUnref<SkSurface> surf2(SkSurface::NewPicture(info.fWidth, info.fHeight)); test_surface(canvas, surf0); canvas->translate(80, 0); test_surface(canvas, surf1); canvas->translate(80, 0); test_surface(canvas, surf2); } virtual uint32_t onGetFlags() const SK_OVERRIDE { return GM::kSkipPicture_Flag; } private: typedef skiagm::GM INHERITED; }; ////////////////////////////////////////////////////////////////////////////// static skiagm::GM* MyFactory(void*) { return new ImageGM; } static skiagm::GMRegistry reg(MyFactory); <commit_msg>disable pipe for now<commit_after>/* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "gm.h" #include "SkSurface.h" #include "SkCanvas.h" #include "SkStream.h" #include "SkData.h" extern GrContext* GetGr(); static SkData* fileToData(const char path[]) { SkFILEStream stream(path); if (!stream.isValid()) { return SkData::NewEmpty(); } size_t size = stream.getLength(); void* mem = sk_malloc_throw(size); stream.read(mem, size); return SkData::NewFromMalloc(mem, size); } static void drawJpeg(SkCanvas* canvas, const SkISize& size) { SkAutoDataUnref data(fileToData("/Users/mike/Downloads/skia.google.jpeg")); SkImage* image = SkImage::NewEncodedData(data); if (image) { SkAutoCanvasRestore acr(canvas, true); canvas->scale(size.width() * 1.0f / image->width(), size.height() * 1.0f / image->height()); image->draw(canvas,0, 0, NULL); image->unref(); } } static void drawContents(SkSurface* surface, SkColor fillC) { SkSize size = SkSize::Make(surface->width(), surface->height()); SkCanvas* canvas = surface->getCanvas(); SkScalar stroke = size.fWidth / 10; SkScalar radius = (size.fWidth - stroke) / 2; SkPaint paint; paint.setAntiAlias(true); paint.setColor(fillC); canvas->drawCircle(size.fWidth/2, size.fHeight/2, radius, paint); paint.setStyle(SkPaint::kStroke_Style); paint.setStrokeWidth(stroke); paint.setColor(SK_ColorBLACK); canvas->drawCircle(size.fWidth/2, size.fHeight/2, radius, paint); } static void test_surface(SkCanvas* canvas, SkSurface* surf) { drawContents(surf, SK_ColorRED); SkImage* imgR = surf->newImageShapshot(); if (true) { SkImage* imgR2 = surf->newImageShapshot(); SkASSERT(imgR == imgR2); imgR2->unref(); } drawContents(surf, SK_ColorGREEN); SkImage* imgG = surf->newImageShapshot(); // since we've drawn after we snapped imgR, imgG will be a different obj SkASSERT(imgR != imgG); drawContents(surf, SK_ColorBLUE); SkPaint paint; // paint.setFilterBitmap(true); // paint.setAlpha(0x80); imgR->draw(canvas, 0, 0, &paint); imgG->draw(canvas, 0, 80, &paint); surf->draw(canvas, 0, 160, &paint); imgG->unref(); imgR->unref(); } class ImageGM : public skiagm::GM { void* fBuffer; size_t fBufferSize; SkSize fSize; enum { W = 64, H = 64, RB = W * 4 + 8, }; public: ImageGM() { fBufferSize = RB * H; fBuffer = sk_malloc_throw(fBufferSize); fSize.set(SkIntToScalar(W), SkIntToScalar(H)); } virtual ~ImageGM() { sk_free(fBuffer); } protected: virtual SkString onShortName() { return SkString("image"); } virtual SkISize onISize() { return SkISize::Make(640, 480); } virtual void onDraw(SkCanvas* canvas) { drawJpeg(canvas, this->getISize()); canvas->translate(10, 10); canvas->scale(2, 2); // since we draw into this directly, we need to start fresh sk_bzero(fBuffer, fBufferSize); SkImage::Info info; info.fWidth = W; info.fHeight = H; info.fColorType = SkImage::kPMColor_ColorType; info.fAlphaType = SkImage::kPremul_AlphaType; SkAutoTUnref<SkSurface> surf0(SkSurface::NewRasterDirect(info, NULL, fBuffer, RB)); SkAutoTUnref<SkSurface> surf1(SkSurface::NewRaster(info, NULL)); SkAutoTUnref<SkSurface> surf2(SkSurface::NewPicture(info.fWidth, info.fHeight)); test_surface(canvas, surf0); canvas->translate(80, 0); test_surface(canvas, surf1); canvas->translate(80, 0); test_surface(canvas, surf2); } virtual uint32_t onGetFlags() const SK_OVERRIDE { return GM::kSkipPicture_Flag | GM::kSkipPipe_Flag; } private: typedef skiagm::GM INHERITED; }; ////////////////////////////////////////////////////////////////////////////// static skiagm::GM* MyFactory(void*) { return new ImageGM; } static skiagm::GMRegistry reg(MyFactory); <|endoftext|>
<commit_before>/* * main.cpp * Program: kalarm * (C) 2001 - 2004 by David Jarvie <software@astrojar.org.uk> * * 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. * * In addition, as a special exception, the copyright holders give permission * to link the code of this program with any edition of the Qt library by * Trolltech AS, Norway (or with modified versions of Qt that use the same * license as Qt), and distribute linked combinations including the two. * You must obey the GNU General Public License in all respects for all of * the code used other than Qt. If you modify this file, you may extend * this exception to your version of the file, but you are not obligated to * do so. If you do not wish to do so, delete this exception statement from * your version. */ #include "kalarm.h" #include <stdlib.h> #include <kcmdlineargs.h> #include <kaboutdata.h> #include <klocale.h> #include <kdebug.h> #include "kalarmapp.h" #define PROGRAM_NAME "kalarm" QCString execArguments; // argument to --exec option static KCmdLineOptions options[] = { { "a", 0, 0 }, { "ack-confirm", I18N_NOOP("Prompt for confirmation when alarm is acknowledged"), 0 }, { "A", 0, 0 }, { "attach <url>", I18N_NOOP("Attach file to email (repeat as needed)"), 0 }, { "bcc", I18N_NOOP("Blind copy email to self"), 0 }, { "b", 0, 0 }, { "beep", I18N_NOOP("Beep when message is displayed"), 0 }, { "colour", 0, 0 }, { "c", 0, 0 }, { "color <color>", I18N_NOOP("Message background color (name or hex 0xRRGGBB)"), 0 }, { "colourfg", 0, 0 }, { "C", 0, 0 }, { "colorfg <color>", I18N_NOOP("Message foreground color (name or hex 0xRRGGBB)"), 0 }, { "calendarURL <url>", I18N_NOOP("URL of calendar file"), 0 }, { "cancelEvent <eventID>", I18N_NOOP("Cancel alarm with the specified event ID"), 0 }, { "e", 0, 0 }, { "exec <commandline>", I18N_NOOP("Execute a shell command line"), 0 }, { "f", 0, 0 }, { "file <url>", I18N_NOOP("File to display"), 0 }, { "handleEvent <eventID>", I18N_NOOP("Trigger or cancel alarm with the specified event ID"), 0 }, { "i", 0, 0 }, { "interval <period>", I18N_NOOP("Interval between alarm recurrences"), 0 }, { "l", 0, 0 }, { "late-cancel", I18N_NOOP("Cancel alarm if it cannot be triggered on time"), 0 }, { "L", 0, 0 }, { "login", I18N_NOOP("Repeat alarm at every login"), 0 }, { "m", 0, 0 }, { "mail <address>", I18N_NOOP("Send an email to the given address (repeat as needed)"), 0 }, { "p", 0, 0 }, { "play <url>", I18N_NOOP("Audio file to play once"), 0 }, #if KDE_VERSION >= 290 { "P", 0, 0 }, { "play-repeat <url>", I18N_NOOP("Audio file to play repeatedly"), 0 }, #endif { "recurrence <spec>", I18N_NOOP("Specify alarm recurrence using iCalendar syntax"), 0 }, { "R", 0, 0 }, { "reminder <period>", I18N_NOOP("Display reminder in advance of alarm"), 0 }, { "reminder-once <period>", I18N_NOOP("Display reminder once in advance of first alarm recurrence"), 0 }, { "r", 0, 0 }, { "repeat <count>", I18N_NOOP("Number of times to repeat alarm (after the initial occasion)"), 0 }, { "reset", I18N_NOOP("Reset the alarm scheduling daemon"), 0 }, { "stop", I18N_NOOP("Stop the alarm scheduling daemon"), 0 }, { "S", 0, 0 }, { "subject ", I18N_NOOP("Email subject line"), 0 }, { "t", 0, 0 }, { "time <time>", I18N_NOOP("Trigger alarm at time [[[yyyy-]mm-]dd-]hh:mm, or date yyyy-mm-dd"), 0 }, { "tray", I18N_NOOP("Display system tray icon"), 0 }, { "triggerEvent <eventID>", I18N_NOOP("Trigger alarm with the specified event ID"), 0 }, { "u", 0, 0 }, { "until <time>", I18N_NOOP("Repeat until time [[[yyyy-]mm-]dd-]hh:mm, or date yyyy-mm-dd"), 0 }, { "+[message]", I18N_NOOP("Message text to display"), 0 }, KCmdLineLastOption }; int main(int argc, char *argv[]) { KAboutData aboutData(PROGRAM_NAME, I18N_NOOP("KAlarm"), KALARM_VERSION, I18N_NOOP("Personal alarm message, command and email scheduler for KDE"), KAboutData::License_GPL, "(c) 2001 - 2003, David Jarvie", 0, "http://www.astrojar.org.uk/linux/kalarm.html"); aboutData.addAuthor("David Jarvie", 0, "software@astrojar.org.uk"); // Fetch all command line options/arguments after --exec and concatenate // them into a single argument. Then change the leading '-'. // This is necessary because the "!" indicator in the 'options' // array above doesn't work (on KDE2, at least) for (int i = 0; i < argc; ++i) { if (!strcmp(argv[i], "-e") || !strcmp(argv[i], "--exec")) { while (++i < argc) { execArguments += argv[i]; if (i < argc - 1) execArguments += ' '; argv[i][0] = 'x'; // in case it's an option } break; } } KCmdLineArgs::init(argc, argv, &aboutData); KCmdLineArgs::addCmdLineOptions(options); KUniqueApplication::addCmdLineOptions(); if (!KAlarmApp::start()) { // An instance of the application is already running exit(0); } // This is the first time through kdDebug(5950) << "main(): initialising\n"; KAlarmApp* app = KAlarmApp::getInstance(); app->restoreSession(); return app->exec(); } <commit_msg>Improve wording for command line option<commit_after>/* * main.cpp * Program: kalarm * (C) 2001 - 2004 by David Jarvie <software@astrojar.org.uk> * * 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. * * In addition, as a special exception, the copyright holders give permission * to link the code of this program with any edition of the Qt library by * Trolltech AS, Norway (or with modified versions of Qt that use the same * license as Qt), and distribute linked combinations including the two. * You must obey the GNU General Public License in all respects for all of * the code used other than Qt. If you modify this file, you may extend * this exception to your version of the file, but you are not obligated to * do so. If you do not wish to do so, delete this exception statement from * your version. */ #include "kalarm.h" #include <stdlib.h> #include <kcmdlineargs.h> #include <kaboutdata.h> #include <klocale.h> #include <kdebug.h> #include "kalarmapp.h" #define PROGRAM_NAME "kalarm" QCString execArguments; // argument to --exec option static KCmdLineOptions options[] = { { "a", 0, 0 }, { "ack-confirm", I18N_NOOP("Prompt for confirmation when alarm is acknowledged"), 0 }, { "A", 0, 0 }, { "attach <url>", I18N_NOOP("Attach file to email (repeat as needed)"), 0 }, { "bcc", I18N_NOOP("Blind copy email to self"), 0 }, { "b", 0, 0 }, { "beep", I18N_NOOP("Beep when message is displayed"), 0 }, { "colour", 0, 0 }, { "c", 0, 0 }, { "color <color>", I18N_NOOP("Message background color (name or hex 0xRRGGBB)"), 0 }, { "colourfg", 0, 0 }, { "C", 0, 0 }, { "colorfg <color>", I18N_NOOP("Message foreground color (name or hex 0xRRGGBB)"), 0 }, { "calendarURL <url>", I18N_NOOP("URL of calendar file"), 0 }, { "cancelEvent <eventID>", I18N_NOOP("Cancel alarm with the specified event ID"), 0 }, { "e", 0, 0 }, { "exec <commandline>", I18N_NOOP("Execute a shell command line"), 0 }, { "f", 0, 0 }, { "file <url>", I18N_NOOP("File to display"), 0 }, { "handleEvent <eventID>", I18N_NOOP("Trigger or cancel alarm with the specified event ID"), 0 }, { "i", 0, 0 }, { "interval <period>", I18N_NOOP("Interval between alarm recurrences"), 0 }, { "l", 0, 0 }, { "late-cancel", I18N_NOOP("Cancel alarm if it cannot be triggered on time"), 0 }, { "L", 0, 0 }, { "login", I18N_NOOP("Repeat alarm at every login"), 0 }, { "m", 0, 0 }, { "mail <address>", I18N_NOOP("Send an email to the given address (repeat as needed)"), 0 }, { "p", 0, 0 }, { "play <url>", I18N_NOOP("Audio file to play once"), 0 }, #if KDE_VERSION >= 290 { "P", 0, 0 }, { "play-repeat <url>", I18N_NOOP("Audio file to play repeatedly"), 0 }, #endif { "recurrence <spec>", I18N_NOOP("Specify alarm recurrence using iCalendar syntax"), 0 }, { "R", 0, 0 }, { "reminder <period>", I18N_NOOP("Display reminder in advance of alarm"), 0 }, { "reminder-once <period>", I18N_NOOP("Display reminder once, before first alarm recurrence"), 0 }, { "r", 0, 0 }, { "repeat <count>", I18N_NOOP("Number of times to repeat alarm (after the initial occasion)"), 0 }, { "reset", I18N_NOOP("Reset the alarm scheduling daemon"), 0 }, { "stop", I18N_NOOP("Stop the alarm scheduling daemon"), 0 }, { "S", 0, 0 }, { "subject ", I18N_NOOP("Email subject line"), 0 }, { "t", 0, 0 }, { "time <time>", I18N_NOOP("Trigger alarm at time [[[yyyy-]mm-]dd-]hh:mm, or date yyyy-mm-dd"), 0 }, { "tray", I18N_NOOP("Display system tray icon"), 0 }, { "triggerEvent <eventID>", I18N_NOOP("Trigger alarm with the specified event ID"), 0 }, { "u", 0, 0 }, { "until <time>", I18N_NOOP("Repeat until time [[[yyyy-]mm-]dd-]hh:mm, or date yyyy-mm-dd"), 0 }, { "+[message]", I18N_NOOP("Message text to display"), 0 }, KCmdLineLastOption }; int main(int argc, char *argv[]) { KAboutData aboutData(PROGRAM_NAME, I18N_NOOP("KAlarm"), KALARM_VERSION, I18N_NOOP("Personal alarm message, command and email scheduler for KDE"), KAboutData::License_GPL, "(c) 2001 - 2003, David Jarvie", 0, "http://www.astrojar.org.uk/linux/kalarm.html"); aboutData.addAuthor("David Jarvie", 0, "software@astrojar.org.uk"); // Fetch all command line options/arguments after --exec and concatenate // them into a single argument. Then change the leading '-'. // This is necessary because the "!" indicator in the 'options' // array above doesn't work (on KDE2, at least) for (int i = 0; i < argc; ++i) { if (!strcmp(argv[i], "-e") || !strcmp(argv[i], "--exec")) { while (++i < argc) { execArguments += argv[i]; if (i < argc - 1) execArguments += ' '; argv[i][0] = 'x'; // in case it's an option } break; } } KCmdLineArgs::init(argc, argv, &aboutData); KCmdLineArgs::addCmdLineOptions(options); KUniqueApplication::addCmdLineOptions(); if (!KAlarmApp::start()) { // An instance of the application is already running exit(0); } // This is the first time through kdDebug(5950) << "main(): initialising\n"; KAlarmApp* app = KAlarmApp::getInstance(); app->restoreSession(); return app->exec(); } <|endoftext|>
<commit_before>/*===========================================================================*\ author: Matthias W. Smith email: mwsmith2@uw.edu file: error_estimator_test_root.cxx notes: Tests the techniques used to estimate the fit errors on the frequency extraction. usage: ./error_estimator_test [<output_file>] The parameters in brackets are optional. The default output is error_estimator_data.csv. \*===========================================================================*/ //--- std includes ----------------------------------------------------------// #include <iostream> #include <fstream> #include <random> #include <string> //--- other includes --------------------------------------------------------// #include <boost/filesystem.hpp> #include "TFile.h" #include "TTree.h" //--- project includes ------------------------------------------------------// #include "fid.h" #define FID_LEN 10000 #define FREQ_METHOD 6 using std::cout; using std::endl; using std::string; using std::to_string; using namespace fid; struct fid_data { Double_t i_wf; Double_t f_wf; Double_t i_psd; Double_t f_psd; Double_t freq_def; Double_t wf[FID_LEN]; Double_t psd[FID_LEN/2]; Double_t phi[FID_LEN]; Double_t freq_ext[FREQ_METHOD]; Double_t freq_err[FREQ_METHOD]; Double_t fit[FREQ_METHOD][FID_LEN]; }; int main(int argc, char **argv) { // Necessary variables. int rounds = 10; std::vector<double> wf; std::vector<double> tm = time_vector(); // default time vector in fid:: // Ouput filename. string outfile; // now get optional output file if (argc > 1) { outfile = string(argv[1]); } else { outfile = string("data/error_estimator_data.root"); } fid_data myfid_data; string br_vars; br_vars += "i_wf/D:f_wf/D:i_psd/D:f_psd/D:freq_def/D:"; br_vars += "wf[" + to_string(FID_LEN) + "]/D:"; br_vars += "psd[" + to_string(FID_LEN/2) + "]/D:"; br_vars += "phi[" + to_string(FID_LEN) + "]/D:"; br_vars += "freq_ext[" + to_string(FREQ_METHOD) + "]/D:"; br_vars += "freq_err[" + to_string(FREQ_METHOD) + "]/D:"; br_vars += "fit[" + to_string(FREQ_METHOD) + "][" + to_string(FID_LEN) + "]/D"; TFile pf(outfile.c_str(), "RECREATE"); TTree pt("t", "fid_fits"); pt.Branch("fid_data", &myfid_data, br_vars.c_str()); // Create random number engine/distribution. std::default_random_engine gen; std::uniform_real_distribution<double> rand_flat_dist(35.0, 40.0); FidFactory ff; for (int i = 0; i < rounds; ++i) { if (i % (rounds / 5) == 0) { cout << "Processing round " << i << " of " << rounds << "." << endl; } // Make ideal Fid waveform double freq = rand_flat_dist(gen); sim::larmor_freq = freq; sim::mixdown_phi = 0.0; sim::signal_to_noise = 100 * 100; ff.IdealFid(wf, tm); Fid myfid(wf, tm); myfid_data.i_wf = myfid.i_wf(); myfid_data.f_wf = myfid.f_wf(); myfid_data.i_psd = myfid.i_fft(); myfid_data.f_psd = myfid.f_fft(); myfid_data.freq_def = freq; std::copy(myfid.wf().begin(), myfid.wf().end(), myfid_data.wf); std::copy(myfid.psd().begin(), myfid.psd().end(), myfid_data.psd); std::copy(myfid.phi().begin(), myfid.phi().end(), myfid_data.phi); int idx = 0; myfid_data.freq_ext[idx] = myfid.CalcZeroCountFreq(); myfid_data.freq_err[idx] = myfid.freq_err(); idx++; myfid_data.freq_ext[idx] = myfid.CalcCentroidFreq(); myfid_data.freq_err[idx] = myfid.freq_err(); idx++; myfid_data.freq_ext[idx] = myfid.CalcAnalyticalFreq(); myfid_data.freq_err[idx] = myfid.freq_err(); for (int i = myfid.i_fft(); i < myfid.f_fft(); ++i) { myfid_data.fit[idx][i] = myfid.f_fit().Eval(myfid.fftfreq()[i]); } idx++; myfid_data.freq_ext[idx] = myfid.CalcLorentzianFreq(); myfid_data.freq_err[idx] = myfid.freq_err(); for (int i = myfid.i_fft(); i < myfid.f_fft(); ++i) { myfid_data.fit[idx][i] = myfid.f_fit().Eval(myfid.fftfreq()[i]); } idx++; myfid_data.freq_ext[idx] = myfid.CalcPhaseFreq(); myfid_data.freq_err[idx] = myfid.freq_err(); for (int i = myfid.i_wf(); i < myfid.f_wf(); ++i) { myfid_data.fit[idx][i] = myfid.f_fit().Eval(myfid.tm()[i]); } idx++; myfid_data.freq_ext[idx] = myfid.CalcSinusoidFreq(); myfid_data.freq_err[idx] = myfid.freq_err(); for (int i = myfid.i_wf(); i < myfid.f_wf(); ++i) { myfid_data.fit[idx][i] = myfid.f_fit().Eval(myfid.tm()[i]); } pt.Fill(); } pf.Write(); pf.Close(); return 0; } <commit_msg>Updated error_estimator example to use new ROOT functions.<commit_after>/*===========================================================================*\ author: Matthias W. Smith email: mwsmith2@uw.edu file: error_estimator_test_root.cxx notes: Tests the techniques used to estimate the fit errors on the frequency extraction. usage: ./error_estimator_test [<output_file>] The parameters in brackets are optional. The default output is error_estimator_data.csv. \*===========================================================================*/ //--- std includes ----------------------------------------------------------// #include <iostream> #include <fstream> #include <random> #include <string> //--- other includes --------------------------------------------------------// #include <boost/filesystem.hpp> #include "TFile.h" #include "TTree.h" //--- project includes ------------------------------------------------------// #include "fid.h" #define FID_LEN 10000 #define FREQ_METHOD 6 using std::cout; using std::endl; using std::string; using std::to_string; using namespace fid; int main(int argc, char **argv) { // Necessary variables. int rounds = 10; std::vector<double> wf; std::vector<double> tm = time_vector(); // default time vector in fid:: // Ouput filename. string outfile; // now get optional output file if (argc > 1) { outfile = string(argv[1]); } else { outfile = string("data/error_estimator_data.root"); } fid_freq_t fid_data; Double_t freq; TFile pf(outfile.c_str(), "RECREATE"); TTree pt("t", "FID Fits"); pt.Branch("data", &fid_data, fid_freq_str); pt.Branch("seed", &freq, "freq/D"); // Create random number engine/distribution. std::default_random_engine gen; std::uniform_real_distribution<double> rand_flat_dist(35.0, 40.0); FidFactory ff; ff.SetSignalToNoise(100*100); ff.SetMixdownPhi(0.0); for (int i = 0; i < rounds; ++i) { if (i % (rounds / 5) == 0) { cout << "Processing round " << i << " of " << rounds << "." << endl; } // Make ideal Fid waveform freq = rand_flat_dist(gen); ff.SetFidFreq(freq); ff.IdealFid(wf, tm); Fid myfid(wf, tm); myfid.CopyStruct(fid_data); pt.Fill(); } pf.Write(); pf.Close(); return 0; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: smdetect.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2005-09-07 15:12:12 $ * * 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 _SM_TYPEDETECT_HXX #define _SM_TYPEDETECT_HXX #ifndef _RTL_USTRING_HXX_ #include <rtl/ustring.hxx> #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif #ifndef _COM_SUN_STAR_DOCUMENT_XEXTENDEDFILTERDETECTION_HPP_ #include <com/sun/star/document/XExtendedFilterDetection.hpp> #endif #ifndef _COM_SUN_STAR_UNO_EXCEPTION_HPP_ #include <com/sun/star/uno/Exception.hpp> #endif #ifndef _COM_SUN_STAR_UNO_REFERENCE_H_ #include <com/sun/star/uno/Reference.h> #endif #ifndef _CPPUHELPER_IMPLBASE2_HXX_ #include <cppuhelper/implbase2.hxx> #endif #include <com/sun/star/lang/XServiceInfo.hpp> #include <com/sun/star/lang/XSingleServiceFactory.hpp> #include <cppuhelper/factory.hxx> #include <tools/link.hxx> #include <tools/string.hxx> class SfxObjectFactory; class SfxFilterMatcher; class LoadEnvironment_Impl; class SfxMedium; namespace com { namespace sun { namespace star { namespace uno { class Any; } namespace lang { class XMultiServiceFactory; } namespace frame { class XFrame; } namespace beans { struct PropertyValue; } } } } #include <sfx2/sfxuno.hxx> #define REFERENCE ::com::sun::star::uno::Reference #define SEQUENCE ::com::sun::star::uno::Sequence #define RUNTIME_EXCEPTION ::com::sun::star::uno::RuntimeException class SmFilterDetect : public ::cppu::WeakImplHelper2< ::com::sun::star::document::XExtendedFilterDetection, ::com::sun::star::lang::XServiceInfo > { public: SmFilterDetect( const REFERENCE < ::com::sun::star::lang::XMultiServiceFactory >& xFactory ); virtual ~SmFilterDetect(); SFX_DECL_XSERVICEINFO //---------------------------------------------------------------------------------- // XExtendedFilterDetect //---------------------------------------------------------------------------------- virtual ::rtl::OUString SAL_CALL detect( SEQUENCE< ::com::sun::star::beans::PropertyValue >& lDescriptor ) throw( RUNTIME_EXCEPTION ); }; #endif <commit_msg>INTEGRATION: CWS changefileheader (1.3.278); FILE MERGED 2008/04/01 15:41:59 thb 1.3.278.3: #i85898# Stripping all external header guards 2008/04/01 12:41:40 thb 1.3.278.2: #i85898# Stripping all external header guards 2008/03/31 16:29:46 rt 1.3.278.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: smdetect.hxx,v $ * $Revision: 1.4 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef _SM_TYPEDETECT_HXX #define _SM_TYPEDETECT_HXX #include <rtl/ustring.hxx> #include <tools/debug.hxx> #include <com/sun/star/document/XExtendedFilterDetection.hpp> #include <com/sun/star/uno/Exception.hpp> #include <com/sun/star/uno/Reference.h> #include <cppuhelper/implbase2.hxx> #include <com/sun/star/lang/XServiceInfo.hpp> #include <com/sun/star/lang/XSingleServiceFactory.hpp> #include <cppuhelper/factory.hxx> #include <tools/link.hxx> #include <tools/string.hxx> class SfxObjectFactory; class SfxFilterMatcher; class LoadEnvironment_Impl; class SfxMedium; namespace com { namespace sun { namespace star { namespace uno { class Any; } namespace lang { class XMultiServiceFactory; } namespace frame { class XFrame; } namespace beans { struct PropertyValue; } } } } #include <sfx2/sfxuno.hxx> #define REFERENCE ::com::sun::star::uno::Reference #define SEQUENCE ::com::sun::star::uno::Sequence #define RUNTIME_EXCEPTION ::com::sun::star::uno::RuntimeException class SmFilterDetect : public ::cppu::WeakImplHelper2< ::com::sun::star::document::XExtendedFilterDetection, ::com::sun::star::lang::XServiceInfo > { public: SmFilterDetect( const REFERENCE < ::com::sun::star::lang::XMultiServiceFactory >& xFactory ); virtual ~SmFilterDetect(); SFX_DECL_XSERVICEINFO //---------------------------------------------------------------------------------- // XExtendedFilterDetect //---------------------------------------------------------------------------------- virtual ::rtl::OUString SAL_CALL detect( SEQUENCE< ::com::sun::star::beans::PropertyValue >& lDescriptor ) throw( RUNTIME_EXCEPTION ); }; #endif <|endoftext|>
<commit_before>#include "Spritemap.h" #include "Common.h" Spritemap::Spritemap() : m_texture(nullptr), m_currentAnim(nullptr), m_animSet(nullptr), callback(nullptr), m_currentFrame(0), m_currentTime(sf::Time::Zero) { } Spritemap::Spritemap(const sf::Texture& texture) : Spritemap() { setTexture(texture); } Spritemap::Spritemap(const sf::Texture& texture, const AnimationSet& animSet) : Spritemap(texture) { setAnimationSet(animSet); setIndex(0); } void Spritemap::playAnimation(std::string name, bool reset) { if (!m_animSet) { LOG(WARNING) << "Tried to play animation \"" + name + "\" on a Spritemap with no animations!"; } const Animation &newAnim = m_animSet->getAnimation(name); // Already playing if (&newAnim == m_currentAnim && reset) { setIndex(0, true); return; } // Start playing m_currentAnim = &newAnim; m_currentTime = sf::Time::Zero; m_playing = true; } void Spritemap::stop() { m_playing = false; m_currentAnim = nullptr; } void Spritemap::update(sf::Time deltaTime) { if (!m_playing || !m_currentAnim) return; size_t frameCount = m_currentAnim->frames.size(); sf::Time frameTime = m_currentAnim->frameTime; // Calculate new frame m_currentTime += deltaTime; if (m_currentTime > frameTime) { size_t frameIncrease = static_cast<size_t>(m_currentTime / frameTime); m_currentFrame += frameIncrease; // Reset time with remainder m_currentTime = m_currentTime % frameTime; if (m_currentFrame >= frameCount) { // Call back if there's a callback function if (callback) callback(); // Loop if (m_currentAnim->looping) { m_currentFrame = m_currentFrame % frameCount; } else { m_currentFrame = frameCount - 1; m_playing = false; } } setIndex(m_currentAnim->frames[m_currentFrame]); } } void Spritemap::setTexture(const sf::Texture& texture) { m_texture = &texture; if (!m_animSet) { setIndex(0); } updateGrid(); } void Spritemap::setAnimationSet(const AnimationSet& animSet) { m_animSet = &animSet; m_frameSize = sf::Vector2f(static_cast<float>(animSet.frameSize.x), static_cast<float>(animSet.frameSize.y)); updateGrid(); } void Spritemap::setIndex(size_t newFrame, bool stop) { m_currentIndex = newFrame; sf::FloatRect rect = getIndexRect(m_currentIndex); m_vertices[0].position = sf::Vector2f(0.f, 0.f); m_vertices[1].position = sf::Vector2f(0.f, rect.width); m_vertices[2].position = sf::Vector2f(rect.height, 0.f); m_vertices[3].position = sf::Vector2f(rect.height, rect.width); m_vertices[0].texCoords = sf::Vector2f(rect.left, rect.top); m_vertices[1].texCoords = sf::Vector2f(rect.left, rect.top + rect.height); m_vertices[2].texCoords = sf::Vector2f(rect.left + rect.width, rect.top); m_vertices[3].texCoords = sf::Vector2f(rect.left + rect.width, rect.top + rect.height); if (stop) { m_currentTime = sf::Time::Zero; m_playing = false; } } void Spritemap::setColor(const sf::Color& color) { m_vertices[0].color = color; m_vertices[1].color = color; m_vertices[2].color = color; m_vertices[3].color = color; } const sf::Texture* Spritemap::getTexture() const { return m_texture; } const AnimationSet* Spritemap::getAnimationSet() const { return m_animSet; } const sf::Color& Spritemap::getColor() const { return m_vertices[0].color; } sf::FloatRect Spritemap::getLocalBounds() const { return getIndexRect(m_currentIndex); } sf::FloatRect Spritemap::getGlobalBounds() const { return getTransform().transformRect(getLocalBounds()); } sf::FloatRect Spritemap::getIndexRect(size_t frame) const { if (m_frameGrid.x == 0 || m_frameGrid.y == 0) { LOG(DEBUG) << "Zero frameGrid"; return sf::FloatRect(sf::Vector2f(), sf::Vector2f(m_texture->getSize())); } sf::Vector2f frameOffset = sf::Vector2f( static_cast<float>(frame % m_frameGrid.x), static_cast<float>(frame / m_frameGrid.x) ); frameOffset.x *= m_frameSize.x; frameOffset.y *= m_frameSize.y; return sf::FloatRect(frameOffset, m_frameSize); } void Spritemap::updateGrid() { // No data to work with if (!m_texture || m_frameSize.x == 0 || m_frameSize.y == 0) return; sf::Vector2u textureSize = m_texture->getSize(); m_frameGrid = sf::Vector2u( textureSize.x / static_cast<size_t>(m_frameSize.x), textureSize.y / static_cast<size_t>(m_frameSize.y) ); } void Spritemap::draw(sf::RenderTarget& target, sf::RenderStates states) const { if (m_texture) { states.transform *= getTransform(); states.texture = m_texture; target.draw(m_vertices, 4, sf::TrianglesStrip, states); } }<commit_msg>Fixed reversed width and height.<commit_after>#include "Spritemap.h" #include "Common.h" Spritemap::Spritemap() : m_texture(nullptr), m_currentAnim(nullptr), m_animSet(nullptr), callback(nullptr), m_currentFrame(0), m_currentTime(sf::Time::Zero) { } Spritemap::Spritemap(const sf::Texture& texture) : Spritemap() { setTexture(texture); } Spritemap::Spritemap(const sf::Texture& texture, const AnimationSet& animSet) : Spritemap(texture) { setAnimationSet(animSet); setIndex(0); } void Spritemap::playAnimation(std::string name, bool reset) { if (!m_animSet) { LOG(WARNING) << "Tried to play animation \"" + name + "\" on a Spritemap with no animations!"; } const Animation &newAnim = m_animSet->getAnimation(name); // Already playing if (&newAnim == m_currentAnim && reset) { setIndex(0, true); return; } // Start playing m_currentAnim = &newAnim; m_currentTime = sf::Time::Zero; m_playing = true; } void Spritemap::stop() { m_playing = false; m_currentAnim = nullptr; } void Spritemap::update(sf::Time deltaTime) { if (!m_playing || !m_currentAnim) return; size_t frameCount = m_currentAnim->frames.size(); sf::Time frameTime = m_currentAnim->frameTime; // Calculate new frame m_currentTime += deltaTime; if (m_currentTime > frameTime) { size_t frameIncrease = static_cast<size_t>(m_currentTime / frameTime); m_currentFrame += frameIncrease; // Reset time with remainder m_currentTime = m_currentTime % frameTime; if (m_currentFrame >= frameCount) { // Call back if there's a callback function if (callback) callback(); // Loop if (m_currentAnim->looping) { m_currentFrame = m_currentFrame % frameCount; } else { m_currentFrame = frameCount - 1; m_playing = false; } } setIndex(m_currentAnim->frames[m_currentFrame]); } } void Spritemap::setTexture(const sf::Texture& texture) { m_texture = &texture; if (!m_animSet) { setIndex(0); } updateGrid(); } void Spritemap::setAnimationSet(const AnimationSet& animSet) { m_animSet = &animSet; m_frameSize = sf::Vector2f(static_cast<float>(animSet.frameSize.x), static_cast<float>(animSet.frameSize.y)); updateGrid(); } void Spritemap::setIndex(size_t newFrame, bool stop) { m_currentIndex = newFrame; sf::FloatRect rect = getIndexRect(m_currentIndex); m_vertices[0].position = sf::Vector2f(0.f, 0.f); m_vertices[1].position = sf::Vector2f(0.f, rect.height); m_vertices[2].position = sf::Vector2f(rect.width, 0.f); m_vertices[3].position = sf::Vector2f(rect.width, rect.height); m_vertices[0].texCoords = sf::Vector2f(rect.left, rect.top); m_vertices[1].texCoords = sf::Vector2f(rect.left, rect.top + rect.height); m_vertices[2].texCoords = sf::Vector2f(rect.left + rect.width, rect.top); m_vertices[3].texCoords = sf::Vector2f(rect.left + rect.width, rect.top + rect.height); if (stop) { m_currentTime = sf::Time::Zero; m_playing = false; } } void Spritemap::setColor(const sf::Color& color) { m_vertices[0].color = color; m_vertices[1].color = color; m_vertices[2].color = color; m_vertices[3].color = color; } const sf::Texture* Spritemap::getTexture() const { return m_texture; } const AnimationSet* Spritemap::getAnimationSet() const { return m_animSet; } const sf::Color& Spritemap::getColor() const { return m_vertices[0].color; } sf::FloatRect Spritemap::getLocalBounds() const { return getIndexRect(m_currentIndex); } sf::FloatRect Spritemap::getGlobalBounds() const { return getTransform().transformRect(getLocalBounds()); } sf::FloatRect Spritemap::getIndexRect(size_t frame) const { if (m_frameGrid.x == 0 || m_frameGrid.y == 0) { LOG(DEBUG) << "Zero frameGrid"; return sf::FloatRect(sf::Vector2f(), sf::Vector2f(m_texture->getSize())); } sf::Vector2f frameOffset = sf::Vector2f( static_cast<float>(frame % m_frameGrid.x), static_cast<float>(frame / m_frameGrid.x) ); frameOffset.x *= m_frameSize.x; frameOffset.y *= m_frameSize.y; return sf::FloatRect(frameOffset, m_frameSize); } void Spritemap::updateGrid() { // No data to work with if (!m_texture || m_frameSize.x == 0 || m_frameSize.y == 0) return; sf::Vector2u textureSize = m_texture->getSize(); m_frameGrid = sf::Vector2u( textureSize.x / static_cast<size_t>(m_frameSize.x), textureSize.y / static_cast<size_t>(m_frameSize.y) ); } void Spritemap::draw(sf::RenderTarget& target, sf::RenderStates states) const { if (m_texture) { states.transform *= getTransform(); states.texture = m_texture; target.draw(m_vertices, 4, sf::TrianglesStrip, states); } }<|endoftext|>
<commit_before>/************************************************************************************* * Copyright (C) 2012 by Alejandro Fiestas Olivares <afiestas@kde.org> * * * * This program is free software; you can redistribute it and/or * * modify it under the terms of the GNU General Public License * * as published by the Free Software Foundation; either version 2 * * of the License, or (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the Free Software * * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA * *************************************************************************************/ #include "daemon.h" #include "serializer.h" #include "generator.h" #include <QtCore/QDebug> #include <kdemacros.h> #include <kaction.h> #include <KLocalizedString> #include <KActionCollection> #include <KPluginFactory> #include <kscreen/config.h> #include <kscreen/configmonitor.h K_PLUGIN_FACTORY(KScreenDaemonFactory, registerPlugin<KScreenDaemon>();) K_EXPORT_PLUGIN(KScreenDaemonFactory("kscreen", "kscreen")) KScreenDaemon::KScreenDaemon(QObject* parent, const QList< QVariant >& ) : KDEDModule(parent) , m_iteration(0) , m_pendingSave(false) { setenv("KSCREEN_BACKEND", "XRandR", 1); KActionCollection *coll = new KActionCollection(this); KAction* action = coll->addAction("display"); action->setText(i18n("Switch Display" )); action->setGlobalShortcut(KShortcut(Qt::Key_Display)); connect(action, SIGNAL(triggered(bool)), SLOT(displayButton())); connect(Generator::self(), SIGNAL(ready()), SLOT(init())); } KScreenDaemon::~KScreenDaemon() { Generator::destroy(); } void KScreenDaemon::init() { applyConfig(); monitorForChanges(); } void KScreenDaemon::applyConfig() { qDebug() << "Applying config"; KScreen::Config* config = 0; if (Serializer::configExists()) { config = Serializer::config(Serializer::currentId()); } else { config = Generator::self()->idealConfig(); } KScreen::Config::setConfig(config); } void KScreenDaemon::configChanged() { qDebug() << "Change detected"; if (m_pendingSave) { return; } qDebug() << "Scheduling screen save"; m_pendingSave = true; QMetaObject::invokeMethod(this, "saveCurrentConfig", Qt::QueuedConnection); } void KScreenDaemon::saveCurrentConfig() { qDebug() << "Saving current config"; m_pendingSave = false; Serializer::saveConfig(KScreen::Config::current()); } void KScreenDaemon::displayButton() { if (m_iteration > 5) { m_iteration = 1; } Generator::self()->displaySwitch(m_iteration); } void KScreenDaemon::monitorForChanges() { KScreen::Config* config = KScreen::Config::current(); KScreen::ConfigMonitor::instance()->addConfig(config); KScreen::OutputList outputs = config->outputs(); Q_FOREACH(KScreen::Output* output, outputs) { connect(output, SIGNAL(isConnectedChanged()), SLOT(applyConfig())); connect(output, SIGNAL(currentModeChanged()), SLOT(configChanged())); connect(output, SIGNAL(isEnabledChanged()), SLOT(configChanged())); connect(output, SIGNAL(isPrimaryChanged()), SLOT(configChanged())); connect(output, SIGNAL(outputChanged()), SLOT(configChanged())); connect(output, SIGNAL(clonesChanged()), SLOT(configChanged())); connect(output, SIGNAL(posChanged()), SLOT(configChanged())); connect(output, SIGNAL(rotationChanged()), SLOT(configChanged())); } }<commit_msg>Increase and check m_iteration properly (lack of sleep starting to affect)<commit_after>/************************************************************************************* * Copyright (C) 2012 by Alejandro Fiestas Olivares <afiestas@kde.org> * * * * This program is free software; you can redistribute it and/or * * modify it under the terms of the GNU General Public License * * as published by the Free Software Foundation; either version 2 * * of the License, or (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the Free Software * * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA * *************************************************************************************/ #include "daemon.h" #include "serializer.h" #include "generator.h" #include <QtCore/QDebug> #include <kdemacros.h> #include <kaction.h> #include <KLocalizedString> #include <KActionCollection> #include <KPluginFactory> #include <kscreen/config.h> #include <kscreen/configmonitor.h K_PLUGIN_FACTORY(KScreenDaemonFactory, registerPlugin<KScreenDaemon>();) K_EXPORT_PLUGIN(KScreenDaemonFactory("kscreen", "kscreen")) KScreenDaemon::KScreenDaemon(QObject* parent, const QList< QVariant >& ) : KDEDModule(parent) , m_iteration(0) , m_pendingSave(false) { setenv("KSCREEN_BACKEND", "XRandR", 1); KActionCollection *coll = new KActionCollection(this); KAction* action = coll->addAction("display"); action->setText(i18n("Switch Display" )); action->setGlobalShortcut(KShortcut(Qt::Key_Display)); connect(action, SIGNAL(triggered(bool)), SLOT(displayButton())); connect(Generator::self(), SIGNAL(ready()), SLOT(init())); } KScreenDaemon::~KScreenDaemon() { Generator::destroy(); } void KScreenDaemon::init() { applyConfig(); monitorForChanges(); } void KScreenDaemon::applyConfig() { qDebug() << "Applying config"; KScreen::Config* config = 0; if (Serializer::configExists()) { config = Serializer::config(Serializer::currentId()); } else { config = Generator::self()->idealConfig(); } KScreen::Config::setConfig(config); } void KScreenDaemon::configChanged() { qDebug() << "Change detected"; if (m_pendingSave) { return; } qDebug() << "Scheduling screen save"; m_pendingSave = true; QMetaObject::invokeMethod(this, "saveCurrentConfig", Qt::QueuedConnection); } void KScreenDaemon::saveCurrentConfig() { qDebug() << "Saving current config"; m_pendingSave = false; Serializer::saveConfig(KScreen::Config::current()); } void KScreenDaemon::displayButton() { if (m_iteration == 5) { m_iteration = 0; } m_iteration++; Generator::self()->displaySwitch(m_iteration); } void KScreenDaemon::monitorForChanges() { KScreen::Config* config = KScreen::Config::current(); KScreen::ConfigMonitor::instance()->addConfig(config); KScreen::OutputList outputs = config->outputs(); Q_FOREACH(KScreen::Output* output, outputs) { connect(output, SIGNAL(isConnectedChanged()), SLOT(applyConfig())); connect(output, SIGNAL(currentModeChanged()), SLOT(configChanged())); connect(output, SIGNAL(isEnabledChanged()), SLOT(configChanged())); connect(output, SIGNAL(isPrimaryChanged()), SLOT(configChanged())); connect(output, SIGNAL(outputChanged()), SLOT(configChanged())); connect(output, SIGNAL(clonesChanged()), SLOT(configChanged())); connect(output, SIGNAL(posChanged()), SLOT(configChanged())); connect(output, SIGNAL(rotationChanged()), SLOT(configChanged())); } }<|endoftext|>
<commit_before>#include "Spritemap.h" #include "Logging.h" namespace ECSE { Spritemap::Spritemap() : callback(nullptr), m_texture(nullptr), m_animSet(nullptr), m_currentAnim(nullptr), m_currentTime(sf::Time::Zero), m_currentFrame(0) { } Spritemap::Spritemap(const sf::Texture& texture) : Spritemap() { setTexture(texture); } Spritemap::Spritemap(const sf::Texture& texture, const AnimationSet& animSet) : Spritemap(texture) { setAnimationSet(animSet); setIndex(0); } void Spritemap::playAnimation(std::string name, bool reset) { if (!m_animSet) { LOG(WARNING) << "Tried to play animation \"" + name + "\" on a Spritemap with no animations!"; } const Animation &newAnim = m_animSet->getAnimation(name); // Already playing if (&newAnim == m_currentAnim && reset) { setIndex(0, true); return; } // Start playing m_currentAnim = &newAnim; m_currentTime = sf::Time::Zero; m_playing = true; } void Spritemap::stop() { m_playing = false; m_currentAnim = nullptr; } void Spritemap::update(sf::Time deltaTime) { if (!m_playing || !m_currentAnim) return; size_t frameCount = m_currentAnim->frames.size(); sf::Time frameTime = m_currentAnim->frameTime; // Calculate new frame m_currentTime += deltaTime; // If frame time is 0, we just want the first frame if (frameTime == sf::seconds(0)) { m_currentFrame = 0; setIndex(m_currentAnim->frames[m_currentFrame]); return; } if (m_currentTime > frameTime) { size_t frameIncrease = static_cast<size_t>(m_currentTime / frameTime); m_currentFrame += frameIncrease; // Reset time with remainder m_currentTime = m_currentTime % frameTime; if (m_currentFrame >= frameCount) { // Call back if there's a callback function if (callback) callback(); // Loop if (m_currentAnim->looping) { m_currentFrame = m_currentFrame % frameCount; } else { m_currentFrame = frameCount - 1; m_playing = false; } } setIndex(m_currentAnim->frames[m_currentFrame]); } } void Spritemap::setTexture(const sf::Texture& texture) { m_texture = &texture; if (!m_animSet) { setIndex(0); } updateGrid(); } void Spritemap::setAnimationSet(const AnimationSet& animSet) { m_animSet = &animSet; m_frameSize = sf::Vector2f(static_cast<float>(animSet.frameSize.x), static_cast<float>(animSet.frameSize.y)); updateGrid(); } void Spritemap::setIndex(size_t newFrame, bool stop) { m_currentIndex = newFrame; sf::FloatRect rect = getIndexRect(m_currentIndex); m_vertices[0].position = sf::Vector2f(0.f, 0.f); m_vertices[1].position = sf::Vector2f(0.f, rect.height); m_vertices[2].position = sf::Vector2f(rect.width, 0.f); m_vertices[3].position = sf::Vector2f(rect.width, rect.height); m_vertices[0].texCoords = sf::Vector2f(rect.left, rect.top); m_vertices[1].texCoords = sf::Vector2f(rect.left, rect.top + rect.height); m_vertices[2].texCoords = sf::Vector2f(rect.left + rect.width, rect.top); m_vertices[3].texCoords = sf::Vector2f(rect.left + rect.width, rect.top + rect.height); if (stop) { m_currentTime = sf::Time::Zero; m_playing = false; } } void Spritemap::setColor(const sf::Color& color) { m_vertices[0].color = color; m_vertices[1].color = color; m_vertices[2].color = color; m_vertices[3].color = color; } const sf::Texture* Spritemap::getTexture() const { return m_texture; } const AnimationSet* Spritemap::getAnimationSet() const { return m_animSet; } const sf::Color& Spritemap::getColor() const { return m_vertices[0].color; } sf::FloatRect Spritemap::getLocalBounds() const { return getIndexRect(m_currentIndex); } sf::FloatRect Spritemap::getGlobalBounds() const { return getTransform().transformRect(getLocalBounds()); } sf::FloatRect Spritemap::getIndexRect(size_t frame) const { if (m_frameGrid.x == 0 || m_frameGrid.y == 0) { return sf::FloatRect(sf::Vector2f(), sf::Vector2f(m_texture->getSize())); } sf::Vector2f frameOffset = sf::Vector2f( static_cast<float>(frame % m_frameGrid.x), static_cast<float>(frame / m_frameGrid.x) ); frameOffset.x *= m_frameSize.x; frameOffset.y *= m_frameSize.y; return sf::FloatRect(frameOffset, m_frameSize); } void Spritemap::updateGrid() { // No data to work with if (!m_texture || m_frameSize.x == 0 || m_frameSize.y == 0) return; sf::Vector2u textureSize = m_texture->getSize(); if (static_cast<size_t>(m_frameSize.x) > textureSize.x || static_cast<size_t>(m_frameSize.y) > textureSize.y) { LOG(WARNING) << "Texture not big enough for provided frame width"; } m_frameGrid = sf::Vector2u( textureSize.x / static_cast<size_t>(m_frameSize.x), textureSize.y / static_cast<size_t>(m_frameSize.y) ); } void Spritemap::draw(sf::RenderTarget& target, sf::RenderStates states) const { if (m_texture) { states.transform *= getTransform(); states.texture = m_texture; target.draw(m_vertices, 4, sf::TrianglesStrip, states); } } } <commit_msg>Fixed Spritemap showing wrong frame for 1 frame<commit_after>#include "Spritemap.h" #include "Logging.h" namespace ECSE { Spritemap::Spritemap() : callback(nullptr), m_texture(nullptr), m_animSet(nullptr), m_currentAnim(nullptr), m_currentTime(sf::Time::Zero), m_currentFrame(0) { } Spritemap::Spritemap(const sf::Texture& texture) : Spritemap() { setTexture(texture); } Spritemap::Spritemap(const sf::Texture& texture, const AnimationSet& animSet) : Spritemap(texture) { setAnimationSet(animSet); setIndex(0); } void Spritemap::playAnimation(std::string name, bool reset) { if (!m_animSet) { LOG(WARNING) << "Tried to play animation \"" + name + "\" on a Spritemap with no animations!"; } const Animation &newAnim = m_animSet->getAnimation(name); // Already playing if (&newAnim == m_currentAnim && reset) { setIndex(0, true); return; } // Start playing m_currentAnim = &newAnim; m_currentTime = sf::Time::Zero; setIndex(0, false); m_playing = true; } void Spritemap::stop() { m_playing = false; m_currentAnim = nullptr; } void Spritemap::update(sf::Time deltaTime) { if (!m_playing || !m_currentAnim) return; size_t frameCount = m_currentAnim->frames.size(); sf::Time frameTime = m_currentAnim->frameTime; // Calculate new frame m_currentTime += deltaTime; // If frame time is 0, we just want the first frame if (frameTime == sf::seconds(0)) { m_currentFrame = 0; setIndex(m_currentAnim->frames[m_currentFrame]); return; } if (m_currentTime > frameTime) { size_t frameIncrease = static_cast<size_t>(m_currentTime / frameTime); m_currentFrame += frameIncrease; // Reset time with remainder m_currentTime = m_currentTime % frameTime; if (m_currentFrame >= frameCount) { // Call back if there's a callback function if (callback) callback(); // Loop if (m_currentAnim->looping) { m_currentFrame = m_currentFrame % frameCount; } else { m_currentFrame = frameCount - 1; m_playing = false; } } setIndex(m_currentAnim->frames[m_currentFrame]); } } void Spritemap::setTexture(const sf::Texture& texture) { m_texture = &texture; if (!m_animSet) { setIndex(0); } updateGrid(); } void Spritemap::setAnimationSet(const AnimationSet& animSet) { m_animSet = &animSet; m_frameSize = sf::Vector2f(static_cast<float>(animSet.frameSize.x), static_cast<float>(animSet.frameSize.y)); updateGrid(); } void Spritemap::setIndex(size_t newFrame, bool stop) { m_currentIndex = newFrame; sf::FloatRect rect = getIndexRect(m_currentIndex); m_vertices[0].position = sf::Vector2f(0.f, 0.f); m_vertices[1].position = sf::Vector2f(0.f, rect.height); m_vertices[2].position = sf::Vector2f(rect.width, 0.f); m_vertices[3].position = sf::Vector2f(rect.width, rect.height); m_vertices[0].texCoords = sf::Vector2f(rect.left, rect.top); m_vertices[1].texCoords = sf::Vector2f(rect.left, rect.top + rect.height); m_vertices[2].texCoords = sf::Vector2f(rect.left + rect.width, rect.top); m_vertices[3].texCoords = sf::Vector2f(rect.left + rect.width, rect.top + rect.height); if (stop) { m_currentTime = sf::Time::Zero; m_playing = false; } } void Spritemap::setColor(const sf::Color& color) { m_vertices[0].color = color; m_vertices[1].color = color; m_vertices[2].color = color; m_vertices[3].color = color; } const sf::Texture* Spritemap::getTexture() const { return m_texture; } const AnimationSet* Spritemap::getAnimationSet() const { return m_animSet; } const sf::Color& Spritemap::getColor() const { return m_vertices[0].color; } sf::FloatRect Spritemap::getLocalBounds() const { return getIndexRect(m_currentIndex); } sf::FloatRect Spritemap::getGlobalBounds() const { return getTransform().transformRect(getLocalBounds()); } sf::FloatRect Spritemap::getIndexRect(size_t frame) const { if (m_frameGrid.x == 0 || m_frameGrid.y == 0) { return sf::FloatRect(sf::Vector2f(), sf::Vector2f(m_texture->getSize())); } sf::Vector2f frameOffset = sf::Vector2f( static_cast<float>(frame % m_frameGrid.x), static_cast<float>(frame / m_frameGrid.x) ); frameOffset.x *= m_frameSize.x; frameOffset.y *= m_frameSize.y; return sf::FloatRect(frameOffset, m_frameSize); } void Spritemap::updateGrid() { // No data to work with if (!m_texture || m_frameSize.x == 0 || m_frameSize.y == 0) return; sf::Vector2u textureSize = m_texture->getSize(); if (static_cast<size_t>(m_frameSize.x) > textureSize.x || static_cast<size_t>(m_frameSize.y) > textureSize.y) { LOG(WARNING) << "Texture not big enough for provided frame width"; } m_frameGrid = sf::Vector2u( textureSize.x / static_cast<size_t>(m_frameSize.x), textureSize.y / static_cast<size_t>(m_frameSize.y) ); } void Spritemap::draw(sf::RenderTarget& target, sf::RenderStates states) const { if (m_texture) { states.transform *= getTransform(); states.texture = m_texture; target.draw(m_vertices, 4, sf::TrianglesStrip, states); } } } <|endoftext|>
<commit_before>/************************** * CMPE-450/CMPE-451 - KEGBOT * MUX_TEST - Used for PoC * of testing multiplexers * with 16 total inputs. * * Michael Byers * Kyle Henry * Sam Sullivan * Yue Yu */ #include "kegbot_base.h" int pulses[NUM_METERS] = {0}; int Previous_Pulses[NUM_METERS] = {0}; int Current_Pulse[NUM_METERS] = {0}; /* Count will loop through * all possible control signals */ uint8_t count; int main (){ wiringPiSetupGpio(); /* Setup flow meters and internal pull-up */ pinMode(Flow_Meter1, INPUT); pullUpDnControl(Flow_Meter1, PUD_UP); pinMode(Flow_Meter2, INPUT); pullUpDnControl(Flow_Meter2, PUD_UP); pinMode(RESET, INPUT); pullUpDnControl(RESET, PUD_UP); pinMode(END, INPUT); pullUpDnControl(END, PUD_UP); /* Set Control Pins as output */ pinMode(M0, OUTPUT); pinMode(M1, OUTPUT); pinMode(M2, OUTPUT); /* Count will loop through * all possible control signals */ count = 0; std::thread worker(worker_thread); while(true){ /* Overflow, reset count */ if (count > 7){ count = 0; } /* Set correct control signal bits * based on count */ digitalWrite(M0, count & 0x01); digitalWrite(M1, count & 0x02); digitalWrite(M2, count & 0x04); /* Check store last pulse results in previous pulse * Used to find edges of the signals */ Previous_Pulses[count] = Current_Pulse[count]; Current_Pulse[count] = digitalRead(Flow_Meter1); /* Read from Flow_Meter 2 */ Previous_Pulses[count+8] = Current_Pulse[count+8]; Current_Pulse[count+8] = digitalRead(Flow_Meter2); /* Detected a falling edge on first MUX, current count */ if ((Current_Pulse[count] == 0)&&(Previous_Pulses[count] == 1)){ pulses[count]++; } /* Detected a falling edge on second MUX, current count+8 */ if ((Current_Pulse[count+8] == 0)&&(Previous_Pulses[count+8] == 1)){ pulses[count+8]++; } nanosleep(&PIN_SLEEP_TIME, NULL); count++; } } void worker_thread(void) { uint8_t count=0; while(true) { /* Overflow, reset count */ if (count > 7){ count = 0; } db.add(count, pulses[count]); db.add(count+8, pulses[count+8]); db.update(); pulses[count] = 0; pulses[count+8] = 0; db.archive(); //nanosleep(db.sleep_time(), NULL); nanosleep(&DB_SLEEP_TIME, NULL); count++; } } <commit_msg>Fixed mux polling sleep spot<commit_after>/************************** * CMPE-450/CMPE-451 - KEGBOT * MUX_TEST - Used for PoC * of testing multiplexers * with 16 total inputs. * * Michael Byers * Kyle Henry * Sam Sullivan * Yue Yu */ #include "kegbot_base.h" int pulses[NUM_METERS] = {0}; int Previous_Pulses[NUM_METERS] = {0}; int Current_Pulse[NUM_METERS] = {0}; /* Count will loop through * all possible control signals */ uint8_t count; int main (){ wiringPiSetupGpio(); /* Setup flow meters and internal pull-up */ pinMode(Flow_Meter1, INPUT); pullUpDnControl(Flow_Meter1, PUD_UP); pinMode(Flow_Meter2, INPUT); pullUpDnControl(Flow_Meter2, PUD_UP); pinMode(RESET, INPUT); pullUpDnControl(RESET, PUD_UP); pinMode(END, INPUT); pullUpDnControl(END, PUD_UP); /* Set Control Pins as output */ pinMode(M0, OUTPUT); pinMode(M1, OUTPUT); pinMode(M2, OUTPUT); /* Count will loop through * all possible control signals */ count = 0; std::thread worker(worker_thread); while(true){ /* Overflow, reset count */ if (count > 7){ count = 0; } /* Set correct control signal bits * based on count */ digitalWrite(M0, count & 0x01); digitalWrite(M1, count & 0x02); digitalWrite(M2, count & 0x04); nanosleep(&PIN_SLEEP_TIME, NULL); /* Check store last pulse results in previous pulse * Used to find edges of the signals */ Previous_Pulses[count] = Current_Pulse[count]; Current_Pulse[count] = digitalRead(Flow_Meter1); /* Read from Flow_Meter 2 */ Previous_Pulses[count+8] = Current_Pulse[count+8]; Current_Pulse[count+8] = digitalRead(Flow_Meter2); /* Detected a falling edge on first MUX, current count */ if ((Current_Pulse[count] == 0)&&(Previous_Pulses[count] == 1)){ pulses[count]++; } /* Detected a falling edge on second MUX, current count+8 */ if ((Current_Pulse[count+8] == 0)&&(Previous_Pulses[count+8] == 1)){ pulses[count+8]++; } count++; } } void worker_thread(void) { uint8_t count=0; while(true) { /* Overflow, reset count */ if (count > 7){ count = 0; } db.add(count, pulses[count]); db.add(count+8, pulses[count+8]); db.update(); pulses[count] = 0; pulses[count+8] = 0; db.archive(); //nanosleep(db.sleep_time(), NULL); nanosleep(&DB_SLEEP_TIME, NULL); count++; } } <|endoftext|>
<commit_before>// Use of this source code is governed by a BSD-style license // that can be found in the License file. // // Author: Shuo Chen (chenshuo at chenshuo dot com) #include <muduo/base/ThreadPool.h> #include <muduo/base/Exception.h> #include <boost/bind.hpp> #include <assert.h> #include <stdio.h> using namespace muduo; ThreadPool::ThreadPool(const string& name) : mutex_(), cond_(mutex_), name_(name), running_(false) { } ThreadPool::~ThreadPool() { } void ThreadPool::start(int numThreads) { assert(threads_.empty()); running_ = true; threads_.reserve(numThreads); for (int i = 0; i < numThreads; ++i) { char id[32]; snprintf(id, sizeof id, "%d", i); threads_.push_back(new muduo::Thread( boost::bind(&ThreadPool::runInThread, this), name_+id)); threads_[i].start(); } } void ThreadPool::stop() { running_ = false; cond_.notifyAll(); for_each(threads_.begin(), threads_.end(), boost::bind(&muduo::Thread::join, _1)); } void ThreadPool::run(const Task& task) { if (threads_.empty()) { task(); } else { MutexLockGuard lock(mutex_); queue_.push_back(task); cond_.notify(); } } ThreadPool::Task ThreadPool::take() { MutexLockGuard lock(mutex_); while (queue_.empty() && running_) { cond_.wait(); } Task task; if(!queue_.empty()) { task = queue_.front(); queue_.pop_front(); } return task; } void ThreadPool::runInThread() { try { while (running_) { Task task(take()); if (task) { task(); } } } catch (const Exception& ex) { fprintf(stderr, "exception caught in ThreadPool %s\n", name_.c_str()); fprintf(stderr, "reason: %s\n", ex.what()); fprintf(stderr, "stack trace: %s\n", ex.stackTrace()); abort(); } catch (const std::exception& ex) { fprintf(stderr, "exception caught in ThreadPool %s\n", name_.c_str()); fprintf(stderr, "reason: %s\n", ex.what()); abort(); } catch (...) { fprintf(stderr, "unknown exception caught in ThreadPool %s\n", name_.c_str()); abort(); } } <commit_msg>stop() in ThreadPool::dtor.<commit_after>// Use of this source code is governed by a BSD-style license // that can be found in the License file. // // Author: Shuo Chen (chenshuo at chenshuo dot com) #include <muduo/base/ThreadPool.h> #include <muduo/base/Exception.h> #include <boost/bind.hpp> #include <assert.h> #include <stdio.h> using namespace muduo; ThreadPool::ThreadPool(const string& name) : mutex_(), cond_(mutex_), name_(name), running_(false) { } ThreadPool::~ThreadPool() { stop(); } void ThreadPool::start(int numThreads) { assert(threads_.empty()); running_ = true; threads_.reserve(numThreads); for (int i = 0; i < numThreads; ++i) { char id[32]; snprintf(id, sizeof id, "%d", i); threads_.push_back(new muduo::Thread( boost::bind(&ThreadPool::runInThread, this), name_+id)); threads_[i].start(); } } void ThreadPool::stop() { running_ = false; cond_.notifyAll(); for_each(threads_.begin(), threads_.end(), boost::bind(&muduo::Thread::join, _1)); } void ThreadPool::run(const Task& task) { if (threads_.empty()) { task(); } else { MutexLockGuard lock(mutex_); queue_.push_back(task); cond_.notify(); } } ThreadPool::Task ThreadPool::take() { MutexLockGuard lock(mutex_); while (queue_.empty() && running_) { cond_.wait(); } Task task; if(!queue_.empty()) { task = queue_.front(); queue_.pop_front(); } return task; } void ThreadPool::runInThread() { try { while (running_) { Task task(take()); if (task) { task(); } } } catch (const Exception& ex) { fprintf(stderr, "exception caught in ThreadPool %s\n", name_.c_str()); fprintf(stderr, "reason: %s\n", ex.what()); fprintf(stderr, "stack trace: %s\n", ex.stackTrace()); abort(); } catch (const std::exception& ex) { fprintf(stderr, "exception caught in ThreadPool %s\n", name_.c_str()); fprintf(stderr, "reason: %s\n", ex.what()); abort(); } catch (...) { fprintf(stderr, "unknown exception caught in ThreadPool %s\n", name_.c_str()); abort(); } } <|endoftext|>
<commit_before>#include "qtmonkey.hpp" #include <atomic> #include <cassert> #include <iostream> #ifdef _WIN32 // windows both 32 bit and 64 bit #include <windows.h> #else #include <cerrno> #include <unistd.h> #endif #include <QtCore/QCoreApplication> #include <QtCore/QTextCodec> #include <QtCore/QThread> #include "common.hpp" #include "qtmonkey_app_api.hpp" using qt_monkey_app::QtMonkey; using qt_monkey_agent::Private::Script; using qt_monkey_agent::Private::PacketTypeForAgent; using qt_monkey_app::Private::StdinReader; using qt_monkey_common::operator <<; namespace { static constexpr int waitBeforeExitMs = 300; static inline std::ostream &operator <<(std::ostream &os, const QString &str) { os << str.toUtf8(); return os; } /* win32 not allow overlapped I/O (see CreateFile [Consoles section] plus QWinEventNotifier private on Qt 4.x and become public only on Qt 5.x so just create thread for both win32 and posix */ class ReadStdinThread final : public QThread { public: ReadStdinThread(QObject *parent, StdinReader &reader); void run() override; void stop(); private: StdinReader &reader_; std::atomic<bool> timeToExit_{false}; #ifdef _WIN32 HANDLE stdinHandle_; #endif }; #ifdef _WIN32 ReadStdinThread::ReadStdinThread(QObject *parent, StdinReader &reader) : QThread(parent), reader_(reader) { stdinHandle_ = ::GetStdHandle(STD_INPUT_HANDLE); if (stdinHandle_ == INVALID_HANDLE_VALUE) throw std::runtime_error("GetStdHandle(STD_INPUT_HANDLE) return error: " + std::to_string(GetLastError())); } void ReadStdinThread::run() { while (!timeToExit_) { char ch; DWORD readBytes = 0; if (!::ReadFile(stdinHandle_, &ch, sizeof(ch), &readBytes, nullptr)) { reader_.emitError( T_("reading from stdin error: %1").arg(GetLastError())); return; } if (readBytes == 0) break; { auto ptr = reader_.data.get(); ptr->append(ch); } reader_.emitDataReady(); } } void ReadStdinThread::stop() { timeToExit_ = true; if (!::CloseHandle(stdinHandle_)) throw std::runtime_error("CloseHandle(stdin) error: " + std::to_string(GetLastError())); } #else ReadStdinThread::ReadStdinThread(QObject *parent, StdinReader &reader) : QThread(parent), reader_(reader) { } void ReadStdinThread::run() { while (!timeToExit_) { char ch; const ssize_t nBytes = ::read(STDIN_FILENO, &ch, sizeof(ch)); if (nBytes < 0) { reader_.emitError(T_("reading from stdin error: %1").arg(errno)); return; } else if (nBytes == 0) { break; } { auto ptr = reader_.data.get(); ptr->append(ch); } reader_.emitDataReady(); } } void ReadStdinThread::stop() { timeToExit_ = true; do { if (::close(STDIN_FILENO) == 0) return; } while (errno == EINTR); throw std::runtime_error("close(stdin) failure: " + std::to_string(errno)); } #endif } //namespace { QtMonkey::QtMonkey(bool exitOnScriptError) : exitOnScriptError_(exitOnScriptError) { connect(&userApp_, SIGNAL(error(QProcess::ProcessError)), this, SLOT(userAppError(QProcess::ProcessError))); connect(&userApp_, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(userAppFinished(int, QProcess::ExitStatus))); connect(&userApp_, SIGNAL(readyReadStandardOutput()), this, SLOT(userAppNewOutput())); connect(&userApp_, SIGNAL(readyReadStandardError()), this, SLOT(userAppNewErrOutput())); connect(&channelWithAgent_, SIGNAL(error(QString)), this, SLOT(communicationWithAgentError(const QString &))); connect(&channelWithAgent_, SIGNAL(newUserAppEvent(QString)), this, SLOT(onNewUserAppEvent(QString))); connect(&channelWithAgent_, SIGNAL(scriptError(QString)), this, SLOT(onScriptError(QString))); connect(&channelWithAgent_, SIGNAL(agentReadyToRunScript()), this, SLOT(onAgentReadyToRunScript())); connect(&channelWithAgent_, SIGNAL(scriptEnd()), this, SLOT(onScriptEnd())); connect(&channelWithAgent_, SIGNAL(scriptLog(QString)), this, SLOT(onScriptLog(QString))); readStdinThread_ = new ReadStdinThread(this, stdinReader_); stdinReader_.moveToThread(readStdinThread_); readStdinThread_->start(); connect(&stdinReader_, SIGNAL(dataReady()), this, SLOT(stdinDataReady())); } QtMonkey::~QtMonkey() { assert(readStdinThread_ != nullptr); auto thread = static_cast<ReadStdinThread *>(readStdinThread_); thread->stop(); thread->wait(100 /*ms*/); thread->terminate(); if (userApp_.state() != QProcess::NotRunning) { userApp_.terminate(); QCoreApplication::processEvents(QEventLoop::AllEvents, 3000 /*ms*/); userApp_.kill(); QCoreApplication::processEvents(QEventLoop::AllEvents, 1000 /*ms*/); } // so any signals from channel will be disconected channelWithAgent_.close(); } void QtMonkey::communicationWithAgentError(const QString &errStr) { qWarning("%s: errStr %s", Q_FUNC_INFO, qPrintable(errStr)); } void QtMonkey::onNewUserAppEvent(QString scriptLines) { std::cout << qt_monkey_app::createPacketFromUserAppEvent(scriptLines) << "\n"; std::cout.flush(); } void QtMonkey::userAppError(QProcess::ProcessError err) { qDebug("%s: begin err %d", Q_FUNC_INFO, static_cast<int>(err)); throw std::runtime_error( qPrintable(qt_monkey_common::processErrorToString(err))); } void QtMonkey::userAppFinished(int exitCode, QProcess::ExitStatus exitStatus) { qDebug("%s: begin exitCode %d, exitStatus %d", Q_FUNC_INFO, exitCode, static_cast<int>(exitStatus)); qt_monkey_common::processEventsFor(waitBeforeExitMs); if (exitCode != EXIT_SUCCESS) throw std::runtime_error(T_("user app exit status not %1: %2") .arg(EXIT_SUCCESS) .arg(exitCode) .toUtf8() .data()); QCoreApplication::exit(EXIT_SUCCESS); } void QtMonkey::userAppNewOutput() { // just ignore for now userApp_.readAllStandardOutput(); } void QtMonkey::userAppNewErrOutput() { const QString errOut = QString::fromLocal8Bit(userApp_.readAllStandardError()); std::cout << createPacketFromUserAppErrors(errOut) << "\n"; std::cout.flush(); } void QtMonkey::stdinDataReady() { auto dataPtr = stdinReader_.data.get(); size_t parserStopPos; parseOutputFromGui( *dataPtr, parserStopPos, [this](QString script, QString scriptFileName) { toRunList_.push(Script{std::move(script)}); onAgentReadyToRunScript(); }, [this](QString errMsg) { std::cerr << T_("Can not parse gui<->monkey protocol: %1\n").arg(errMsg); }); if (parserStopPos != 0) dataPtr->remove(0, parserStopPos); } void QtMonkey::onScriptError(QString errMsg) { qDebug("%s: begin %s", Q_FUNC_INFO, qPrintable(errMsg)); setScriptRunningState(false); std::cout << createPacketFromUserAppErrors(errMsg) << "\n"; std::cout.flush(); if (exitOnScriptError_) { qt_monkey_common::processEventsFor(waitBeforeExitMs); throw std::runtime_error( T_("script return error: %1").arg(errMsg).toUtf8().data()); } } bool QtMonkey::runScriptFromFile(QStringList scriptPathList, const char *encoding) { if (encoding == nullptr) encoding = "UTF-8"; QString script; for (const QString &fn : scriptPathList) { QFile f(fn); if (!f.open(QIODevice::ReadOnly)) { std::cerr << T_("Error: can not open %1\n").arg(fn); return false; } QTextStream t(&f); t.setCodec(QTextCodec::codecForName(encoding)); if (!script.isEmpty()) script += "\n<<<RESTART FROM HERE>>>\n"; script += t.readAll(); } toRunList_.push(Script{std::move(script)}); return true; } void QtMonkey::onAgentReadyToRunScript() { qDebug("%s: begin", Q_FUNC_INFO); if (!channelWithAgent_.isConnectedState() || toRunList_.empty() || scriptRunning_) return; Script script = std::move(toRunList_.front()); toRunList_.pop(); QString code; script.releaseCode(code); channelWithAgent_.sendCommand(PacketTypeForAgent::RunScript, std::move(code)); setScriptRunningState(true); } void QtMonkey::onScriptEnd() { setScriptRunningState(false); std::cout << createPacketFromScriptEnd() << "\n"; std::cout.flush(); } void QtMonkey::onScriptLog(QString msg) { std::cout << createPacketFromUserAppScriptLog(msg) << "\n"; std::cout.flush(); } void QtMonkey::setScriptRunningState(bool val) { scriptRunning_ = val; if (!scriptRunning_) onAgentReadyToRunScript(); } <commit_msg>use endl, instead of \n and flush<commit_after>#include "qtmonkey.hpp" #include <atomic> #include <cassert> #include <iostream> #ifdef _WIN32 // windows both 32 bit and 64 bit #include <windows.h> #else #include <cerrno> #include <unistd.h> #endif #include <QtCore/QCoreApplication> #include <QtCore/QTextCodec> #include <QtCore/QThread> #include "common.hpp" #include "qtmonkey_app_api.hpp" using qt_monkey_app::QtMonkey; using qt_monkey_agent::Private::Script; using qt_monkey_agent::Private::PacketTypeForAgent; using qt_monkey_app::Private::StdinReader; using qt_monkey_common::operator <<; namespace { static constexpr int waitBeforeExitMs = 300; static inline std::ostream &operator <<(std::ostream &os, const QString &str) { os << str.toUtf8(); return os; } /* win32 not allow overlapped I/O (see CreateFile [Consoles section] plus QWinEventNotifier private on Qt 4.x and become public only on Qt 5.x so just create thread for both win32 and posix */ class ReadStdinThread final : public QThread { public: ReadStdinThread(QObject *parent, StdinReader &reader); void run() override; void stop(); private: StdinReader &reader_; std::atomic<bool> timeToExit_{false}; #ifdef _WIN32 HANDLE stdinHandle_; #endif }; #ifdef _WIN32 ReadStdinThread::ReadStdinThread(QObject *parent, StdinReader &reader) : QThread(parent), reader_(reader) { stdinHandle_ = ::GetStdHandle(STD_INPUT_HANDLE); if (stdinHandle_ == INVALID_HANDLE_VALUE) throw std::runtime_error("GetStdHandle(STD_INPUT_HANDLE) return error: " + std::to_string(GetLastError())); } void ReadStdinThread::run() { while (!timeToExit_) { char ch; DWORD readBytes = 0; if (!::ReadFile(stdinHandle_, &ch, sizeof(ch), &readBytes, nullptr)) { reader_.emitError( T_("reading from stdin error: %1").arg(GetLastError())); return; } if (readBytes == 0) break; { auto ptr = reader_.data.get(); ptr->append(ch); } reader_.emitDataReady(); } } void ReadStdinThread::stop() { timeToExit_ = true; if (!::CloseHandle(stdinHandle_)) throw std::runtime_error("CloseHandle(stdin) error: " + std::to_string(GetLastError())); } #else ReadStdinThread::ReadStdinThread(QObject *parent, StdinReader &reader) : QThread(parent), reader_(reader) { } void ReadStdinThread::run() { while (!timeToExit_) { char ch; const ssize_t nBytes = ::read(STDIN_FILENO, &ch, sizeof(ch)); if (nBytes < 0) { reader_.emitError(T_("reading from stdin error: %1").arg(errno)); return; } else if (nBytes == 0) { break; } { auto ptr = reader_.data.get(); ptr->append(ch); } reader_.emitDataReady(); } } void ReadStdinThread::stop() { timeToExit_ = true; do { if (::close(STDIN_FILENO) == 0) return; } while (errno == EINTR); throw std::runtime_error("close(stdin) failure: " + std::to_string(errno)); } #endif } //namespace { QtMonkey::QtMonkey(bool exitOnScriptError) : exitOnScriptError_(exitOnScriptError) { connect(&userApp_, SIGNAL(error(QProcess::ProcessError)), this, SLOT(userAppError(QProcess::ProcessError))); connect(&userApp_, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(userAppFinished(int, QProcess::ExitStatus))); connect(&userApp_, SIGNAL(readyReadStandardOutput()), this, SLOT(userAppNewOutput())); connect(&userApp_, SIGNAL(readyReadStandardError()), this, SLOT(userAppNewErrOutput())); connect(&channelWithAgent_, SIGNAL(error(QString)), this, SLOT(communicationWithAgentError(const QString &))); connect(&channelWithAgent_, SIGNAL(newUserAppEvent(QString)), this, SLOT(onNewUserAppEvent(QString))); connect(&channelWithAgent_, SIGNAL(scriptError(QString)), this, SLOT(onScriptError(QString))); connect(&channelWithAgent_, SIGNAL(agentReadyToRunScript()), this, SLOT(onAgentReadyToRunScript())); connect(&channelWithAgent_, SIGNAL(scriptEnd()), this, SLOT(onScriptEnd())); connect(&channelWithAgent_, SIGNAL(scriptLog(QString)), this, SLOT(onScriptLog(QString))); readStdinThread_ = new ReadStdinThread(this, stdinReader_); stdinReader_.moveToThread(readStdinThread_); readStdinThread_->start(); connect(&stdinReader_, SIGNAL(dataReady()), this, SLOT(stdinDataReady())); } QtMonkey::~QtMonkey() { assert(readStdinThread_ != nullptr); auto thread = static_cast<ReadStdinThread *>(readStdinThread_); thread->stop(); thread->wait(100 /*ms*/); thread->terminate(); if (userApp_.state() != QProcess::NotRunning) { userApp_.terminate(); QCoreApplication::processEvents(QEventLoop::AllEvents, 3000 /*ms*/); userApp_.kill(); QCoreApplication::processEvents(QEventLoop::AllEvents, 1000 /*ms*/); } // so any signals from channel will be disconected channelWithAgent_.close(); } void QtMonkey::communicationWithAgentError(const QString &errStr) { qWarning("%s: errStr %s", Q_FUNC_INFO, qPrintable(errStr)); } void QtMonkey::onNewUserAppEvent(QString scriptLines) { std::cout << qt_monkey_app::createPacketFromUserAppEvent(scriptLines) << std::endl; } void QtMonkey::userAppError(QProcess::ProcessError err) { qDebug("%s: begin err %d", Q_FUNC_INFO, static_cast<int>(err)); throw std::runtime_error( qPrintable(qt_monkey_common::processErrorToString(err))); } void QtMonkey::userAppFinished(int exitCode, QProcess::ExitStatus exitStatus) { qDebug("%s: begin exitCode %d, exitStatus %d", Q_FUNC_INFO, exitCode, static_cast<int>(exitStatus)); qt_monkey_common::processEventsFor(waitBeforeExitMs); if (exitCode != EXIT_SUCCESS) throw std::runtime_error(T_("user app exit status not %1: %2") .arg(EXIT_SUCCESS) .arg(exitCode) .toUtf8() .data()); QCoreApplication::exit(EXIT_SUCCESS); } void QtMonkey::userAppNewOutput() { // just ignore for now userApp_.readAllStandardOutput(); } void QtMonkey::userAppNewErrOutput() { const QString errOut = QString::fromLocal8Bit(userApp_.readAllStandardError()); std::cout << createPacketFromUserAppErrors(errOut) << std::endl; } void QtMonkey::stdinDataReady() { auto dataPtr = stdinReader_.data.get(); size_t parserStopPos; parseOutputFromGui( *dataPtr, parserStopPos, [this](QString script, QString scriptFileName) { toRunList_.push(Script{std::move(script)}); onAgentReadyToRunScript(); }, [this](QString errMsg) { std::cerr << T_("Can not parse gui<->monkey protocol: %1\n").arg(errMsg); }); if (parserStopPos != 0) dataPtr->remove(0, parserStopPos); } void QtMonkey::onScriptError(QString errMsg) { qDebug("%s: begin %s", Q_FUNC_INFO, qPrintable(errMsg)); setScriptRunningState(false); std::cout << createPacketFromUserAppErrors(errMsg) << std::endl; if (exitOnScriptError_) { qt_monkey_common::processEventsFor(waitBeforeExitMs); throw std::runtime_error( T_("script return error: %1").arg(errMsg).toUtf8().data()); } } bool QtMonkey::runScriptFromFile(QStringList scriptPathList, const char *encoding) { if (encoding == nullptr) encoding = "UTF-8"; QString script; for (const QString &fn : scriptPathList) { QFile f(fn); if (!f.open(QIODevice::ReadOnly)) { std::cerr << T_("Error: can not open %1\n").arg(fn); return false; } QTextStream t(&f); t.setCodec(QTextCodec::codecForName(encoding)); if (!script.isEmpty()) script += "\n<<<RESTART FROM HERE>>>\n"; script += t.readAll(); } toRunList_.push(Script{std::move(script)}); return true; } void QtMonkey::onAgentReadyToRunScript() { qDebug("%s: begin", Q_FUNC_INFO); if (!channelWithAgent_.isConnectedState() || toRunList_.empty() || scriptRunning_) return; Script script = std::move(toRunList_.front()); toRunList_.pop(); QString code; script.releaseCode(code); channelWithAgent_.sendCommand(PacketTypeForAgent::RunScript, std::move(code)); setScriptRunningState(true); } void QtMonkey::onScriptEnd() { setScriptRunningState(false); std::cout << createPacketFromScriptEnd() << std::endl; } void QtMonkey::onScriptLog(QString msg) { std::cout << createPacketFromUserAppScriptLog(msg) << std::endl; } void QtMonkey::setScriptRunningState(bool val) { scriptRunning_ = val; if (!scriptRunning_) onAgentReadyToRunScript(); } <|endoftext|>
<commit_before>#include <iostream> #include <vector> #include <climits> #include <math.h> #include <stdio.h> #include <stdlib.h> #include <getopt.h> #include <string> #include <map> using namespace std; static int n_flag; static int min_flag; static int max_flag; static int mean_flag; static int sum_flag; static int sd_flag; static int population_flag; static int sample_flag; static int comp_flag; static int var_flag; //running stats needed void compute_line_stats(vector<long double> * stats){ long double stat = (*stats).at(0); //sum (*stats).at(1) += stat; //N (*stats).at(4)+=1; //min if ((*stats).at(2) > stat){ (*stats).at(2) = stat; } //max if ((*stats).at(3) < stat){ (*stats).at(3) = stat; } } //global descriptive statistics void compute_global_stats(vector<long double> * stats, vector<long double> * points, map<string, long double> * global_stats, map<string,int> * opts){ //mean long double mean = (*stats).at(1) / (*stats).at(4); long double n = (*stats).at(4); //sum of squared deviations long double sum = 0; //for compensated variant long double sum3 = 0; for (long index=0; index<(long)(*points).size(); ++index){ long double diff = (*points).at(index) - mean; sum += (diff * diff); sum3 += diff; } //for compensated variant biased long double comp_var_s = (sum-((sum3*sum3)/n))/n; //for compensated variant unbiased when n is not equal to |population| long double comp_var_p = (sum-((sum3*sum3)/n))/n-1; //sample sd comp long double samp_sd_comp = sqrt(comp_var_s); //pop sd comp long double pop_sd_comp = sqrt(comp_var_p); //sample variance long double var_s = sum/n; //population variance long double var_p = sum/(n-1); //sample sd long double samp_sd = sqrt(var_s); //pop sd long double pop_sd = sqrt(var_p); //init global_stats (*global_stats)["n"] = n; (*global_stats)["mean"] = mean; (*global_stats)["sampl_sd"] = samp_sd; (*global_stats)["pop_sd"] = pop_sd; (*global_stats)["pop_sd_comp"] = pop_sd_comp; (*global_stats)["samp_sd_comp"] = samp_sd_comp; (*global_stats)["sum"] = (*stats).at(1); (*global_stats)["min"] = (*stats).at(2); (*global_stats)["max"] = (*stats).at(3); if( (*opts).find("population") != (*opts).end() && (*opts).find("compensated") != (*opts).end()){ (*global_stats)["sd"] = pop_sd_comp; (*global_stats)["var"] = comp_var_p; } if( (*opts).find("population") != (*opts).end() && (*opts).find("compensated") == (*opts).end() ) { (*global_stats)["sd"] = pop_sd; (*global_stats)["var"] = var_p; } if( (*opts).find("population") == (*opts).end() && (*opts).find("compensated") != (*opts).end()){ (*global_stats)["sd"] = samp_sd_comp; (*global_stats)["var"] = comp_var_s; } if( (*opts).find("population") == (*opts).end() && (*opts).find("compensated") == (*opts).end() ) { (*global_stats)["sd"] = samp_sd; (*global_stats)["var"] = var_s; } } void print_stats(map<string, long double> * stats, map<string,int> * opts){ vector<string> opts_ordered; opts_ordered.push_back("N"); opts_ordered.push_back("max"); opts_ordered.push_back("min"); opts_ordered.push_back("sum"); opts_ordered.push_back("mean"); opts_ordered.push_back("sd"); opts_ordered.push_back("var"); string output = " "; for(vector<string>::iterator ii=opts_ordered.begin(); ii!=opts_ordered.end();++ii){ if ( (*opts).find(*ii) == (*opts).end()) continue; cout << *ii << "\t"; } cout<<endl; for(vector<string>::iterator ii=opts_ordered.begin(); ii!=opts_ordered.end();++ii){ if ( (*opts).find(*ii) == (*opts).end()) continue; cout << (*stats)[*ii] << "\t"; } cout<<endl; } void set_flags(int argc, char **argv, map<string,int> * opts){ int c; while (1){ static struct option long_options[] = { /* These options set a flag. */ {"sum", no_argument, &sum_flag, 1}, {"min", no_argument, &min_flag, 1}, {"max", no_argument, &max_flag, 1}, {"mean", no_argument, &mean_flag, 1}, {"sd", no_argument, &sd_flag, 1}, {"var", no_argument, &var_flag, 1}, {"n", no_argument, &n_flag, 1}, {"population", no_argument, &population_flag, 1}, {"sample", no_argument, &sample_flag, 1}, {"compensated", no_argument, &comp_flag, 1}, }; /* getopt_long stores the option index here. */ int option_index = 0; c = getopt_long (argc, argv, "abc:d:f:", long_options, &option_index); /* Detect the end of the options. */ if (c == -1) break; switch (c) { case 0: /* If this option set a flag, do nothing else now. */ if (long_options[option_index].flag != 0) break; printf ("option %s", long_options[option_index].name); if (optarg) printf (" with arg %s", optarg); printf ("\n"); break; case '?': /* getopt_long already printed an error message. */ break; default: abort (); } } if (sum_flag) (*opts)["sum"] = 1; if (n_flag) (*opts)["N"] = 1; if (min_flag) (*opts)["min"] = 1; if (max_flag) (*opts)["max"] = 1; if (sd_flag) (*opts)["sd"] = 1; if (comp_flag) (*opts)["compensated"] = 1; if (sample_flag) (*opts)["sample"] = 1; if (population_flag) (*opts)["population"] = 1; if (mean_flag) (*opts)["mean"] = 1; if (var_flag) (*opts)["var"] = 1; /* Print any remaining command line arguments (not options). */ if (optind < argc){ printf ("non-option ARGV-elements: "); while (optind < argc) printf ("%s ", argv[optind++]); putchar ('\n'); } /** If opts is empty, print out all info, and assume sample statistics **/ if((*opts).size()==0){ (*opts)["sum"] = 1; (*opts)["N"] = 1; (*opts)["min"] = 1; (*opts)["max"] = 1; (*opts)["mean"] = 1; (*opts)["sd"] = 1; } } int main (int argc, char **argv){ map<string,int> * opts = new map<string, int>(); set_flags(argc, argv,opts); long double sum = 0; long double n = 0; long double min = INT_MAX; long double max = INT_MIN; long double mean = 0; long double sd = 0; vector<long double> * stats = new vector<long double>(); (*stats).push_back(sum); (*stats).push_back(sum); (*stats).push_back(min); (*stats).push_back(max); (*stats).push_back(n); (*stats).push_back(mean); (*stats).push_back(sd); vector<long double> * points = new vector<long double>(); map<string, long double> * global_stats = new map<string, long double>(); while(cin){ string input_line; getline(cin,input_line); if(input_line=="") continue; long double stat = (long double) ::atof(input_line.c_str()); (*stats).at(0) = stat; compute_line_stats(stats); (*points).push_back(stat); } compute_global_stats(stats, points, global_stats, opts); print_stats(global_stats,opts); delete points; delete stats; delete global_stats; delete opts; return 0; } <commit_msg>removed st.cpp<commit_after><|endoftext|>
<commit_before>#pragma sw require header pub.egorpugin.primitives.tools.embedder-master #pragma sw require header org.sw.demo.lexxmark.winflexbison.bison void configure(Build &s) { /*auto ss = s.createSettings(); ss.Native.LibrariesType = LibraryType::Static; ss.Native.ConfigurationType = ConfigurationType::ReleaseWithDebugInformation; s.addSettings(ss);*/ } void build(Solution &s) { auto &p = s.addProject("cppan", "master"); p += Git("https://github.com/cppan/cppan", "", "v1"); auto &common = p.addTarget<StaticLibraryTarget>("common"); common.CPPVersion = CPPLanguageStandard::CPP17; common += "src/common/.*"_rr, "src/printers/.*"_rr, "src/comments/.*"_rr, "src/bazel/.*"_rr, "src/inserts/.*"_rr, "src/support/.*"_rr, "src/gen/.*"_rr; common -= "src/bazel/test/test.cpp", "src/gen/.*"_rr; common.Public += "src"_id, "src/common"_id, "src/support"_id; common.Public += "VERSION_MAJOR=0"_d; common.Public += "VERSION_MINOR=2"_d; common.Public += "VERSION_PATCH=5"_d; common.Public += "BUILD_NUMBER=0"_d; common.Public += "CPPAN_VERSION_STRING=0.2.5"_d; if (common.getBuildSettings().TargetOS.Type == OSType::Windows) common.Public += "UNICODE"_d; common.Public += "org.sw.demo.boost.optional-1"_dep, "org.sw.demo.boost.property_tree-1"_dep, "org.sw.demo.boost.variant-1"_dep, "org.sw.demo.boost.stacktrace-1"_dep, //"org.sw.demo.apolukhin.stacktrace-master"_dep, "org.sw.demo.sqlite3-3"_dep, "org.sw.demo.fmt-*"_dep, "org.sw.demo.imageworks.pystring-1"_dep, "org.sw.demo.giovannidicanio.winreg-master"_dep, "pub.egorpugin.primitives.string-master"_dep, "pub.egorpugin.primitives.filesystem-master"_dep, "pub.egorpugin.primitives.emitter-master"_dep, "pub.egorpugin.primitives.date_time-master"_dep, "pub.egorpugin.primitives.executor-master"_dep, "pub.egorpugin.primitives.hash-master"_dep, "pub.egorpugin.primitives.http-master"_dep, "pub.egorpugin.primitives.lock-master"_dep, "pub.egorpugin.primitives.log-master"_dep, "pub.egorpugin.primitives.pack-master"_dep, "pub.egorpugin.primitives.patch-master"_dep, "pub.egorpugin.primitives.command-master"_dep, "pub.egorpugin.primitives.win32helpers-master"_dep, "pub.egorpugin.primitives.yaml-master"_dep; time_t v; time(&v); common.writeFileSafe("stamp.h.in", "\"" + std::to_string(v) + "\""); embed("pub.egorpugin.primitives.tools.embedder-master"_dep, common, "src/inserts/inserts.cpp.in"); auto [fc,bc] = gen_flex_bison("org.sw.demo.lexxmark.winflexbison"_dep, common, "src/bazel/bazel.ll", "src/bazel/bazel.yy", {"--prefix=ll_bazel", "--header-file=" + normalize_path(common.BinaryDir / "bazel/lexer.h")}); fc->addOutput(common.BinaryDir / "bazel/lexer.h"); auto [fc2,bc2] = gen_flex_bison("org.sw.demo.lexxmark.winflexbison"_dep, common, "src/comments/comments.ll", "src/comments/comments.yy", {"--prefix=ll_comments", "--header-file=" + normalize_path(common.BinaryDir / "comments/lexer.h")}); fc2->addOutput(common.BinaryDir / "comments/lexer.h"); auto &client = p.addTarget<ExecutableTarget>("client"); client.CPPVersion = CPPLanguageStandard::CPP17; // for rc.exe client += "VERSION_MAJOR=0"_d; client += "VERSION_MINOR=2"_d; client += "VERSION_PATCH=5"_d; client += "BUILD_NUMBER=0"_d; client += "CPPAN_VERSION_STRING=0.2.5"_d; client += "src/client/.*"_rr, common, "pub.egorpugin.primitives.sw.main-master"_dep, "org.sw.demo.boost.program_options-1"_dep, "org.sw.demo.yhirose.cpp_linenoise-master"_dep; } <commit_msg>[sw] Remove deps versions.<commit_after>#pragma sw require header pub.egorpugin.primitives.tools.embedder-master #pragma sw require header org.sw.demo.lexxmark.winflexbison.bison void build(Solution &s) { auto &p = s.addProject("cppan", "master"); p += Git("https://github.com/cppan/cppan", "", "v1"); auto &common = p.addTarget<StaticLibraryTarget>("common"); common.CPPVersion = CPPLanguageStandard::CPP17; common += "src/common/.*"_rr, "src/printers/.*"_rr, "src/comments/.*"_rr, "src/bazel/.*"_rr, "src/inserts/.*"_rr, "src/support/.*"_rr, "src/gen/.*"_rr; common -= "src/bazel/test/test.cpp", "src/gen/.*"_rr; common.Public += "src"_id, "src/common"_id, "src/support"_id; common.Public += "VERSION_MAJOR=0"_d; common.Public += "VERSION_MINOR=2"_d; common.Public += "VERSION_PATCH=5"_d; common.Public += "BUILD_NUMBER=0"_d; common.Public += "CPPAN_VERSION_STRING=0.2.5"_d; if (common.getBuildSettings().TargetOS.Type == OSType::Windows) common.Public += "UNICODE"_d; common.Public += "org.sw.demo.boost.optional"_dep, "org.sw.demo.boost.property_tree"_dep, "org.sw.demo.boost.variant"_dep, "org.sw.demo.boost.stacktrace"_dep, //"org.sw.demo.apolukhin.stacktrace-master"_dep, "org.sw.demo.sqlite3"_dep, "org.sw.demo.fmt"_dep, "org.sw.demo.imageworks.pystring"_dep, "org.sw.demo.giovannidicanio.winreg-master"_dep, "pub.egorpugin.primitives.string-master"_dep, "pub.egorpugin.primitives.filesystem-master"_dep, "pub.egorpugin.primitives.emitter-master"_dep, "pub.egorpugin.primitives.date_time-master"_dep, "pub.egorpugin.primitives.executor-master"_dep, "pub.egorpugin.primitives.hash-master"_dep, "pub.egorpugin.primitives.http-master"_dep, "pub.egorpugin.primitives.lock-master"_dep, "pub.egorpugin.primitives.log-master"_dep, "pub.egorpugin.primitives.pack-master"_dep, "pub.egorpugin.primitives.patch-master"_dep, "pub.egorpugin.primitives.command-master"_dep, "pub.egorpugin.primitives.win32helpers-master"_dep, "pub.egorpugin.primitives.yaml-master"_dep; time_t v; time(&v); common.writeFileSafe("stamp.h.in", "\"" + std::to_string(v) + "\""); embed("pub.egorpugin.primitives.tools.embedder-master"_dep, common, "src/inserts/inserts.cpp.in"); auto [fc,bc] = gen_flex_bison("org.sw.demo.lexxmark.winflexbison"_dep, common, "src/bazel/bazel.ll", "src/bazel/bazel.yy", {"--prefix=ll_bazel", "--header-file=" + normalize_path(common.BinaryDir / "bazel/lexer.h")}); fc->addOutput(common.BinaryDir / "bazel/lexer.h"); auto [fc2,bc2] = gen_flex_bison("org.sw.demo.lexxmark.winflexbison"_dep, common, "src/comments/comments.ll", "src/comments/comments.yy", {"--prefix=ll_comments", "--header-file=" + normalize_path(common.BinaryDir / "comments/lexer.h")}); fc2->addOutput(common.BinaryDir / "comments/lexer.h"); auto &client = p.addTarget<ExecutableTarget>("client"); client.CPPVersion = CPPLanguageStandard::CPP17; // for rc.exe client += "VERSION_MAJOR=0"_d; client += "VERSION_MINOR=2"_d; client += "VERSION_PATCH=5"_d; client += "BUILD_NUMBER=0"_d; client += "CPPAN_VERSION_STRING=0.2.5"_d; client += "src/client/.*"_rr, common, "pub.egorpugin.primitives.sw.main-master"_dep, "org.sw.demo.boost.program_options"_dep, "org.sw.demo.yhirose.cpp_linenoise-master"_dep; } <|endoftext|>
<commit_before>// Copyright 2017 Netherlands Institute for Radio Astronomy (ASTRON) // Copyright 2017 Netherlands eScience Center // // 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 <configuration.hpp> #include <CommandLine.hpp> #include <Kernels.hpp> #include <Memory.hpp> #include <Pipeline.hpp> int main(int argc, char * argv[]) { // Command line options Options options {}; DeviceOptions deviceOptions {}; DataOptions dataOptions {}; GeneratorOptions generatorOptions {}; // Memory HostMemory hostMemory {}; DeviceMemory deviceMemory {}; // OpenCL kernels OpenCLRunTime openclRunTime {}; KernelConfigurations kernelConfigurations {}; Kernels kernels {}; KernelRunTimeConfigurations kernelRunTimeConfigurations {}; // Timers Timers timers {}; // Observation AstroData::Observation observation; // Process command line arguments isa::utils::ArgumentList args(argc, argv); try { processCommandLineOptions(args, options, deviceOptions, dataOptions, kernelConfigurations, generatorOptions, observation); } catch ( std::exception & err ) { return 1; } // Load or generate input data try { try { hostMemory.zappedChannels.resize(observation.getNrChannels(deviceOptions.padding.at(deviceOptions.deviceName) / sizeof(unsigned int))); } catch ( std::out_of_range & err ) { std::cerr << "No padding specified for " << deviceOptions.deviceName << "." << std::endl; return 1; } try { AstroData::readZappedChannels(observation, dataOptions.channelsFile, hostMemory.zappedChannels); AstroData::readIntegrationSteps(observation, dataOptions.integrationFile, hostMemory.integrationSteps); } catch ( AstroData::FileError & err ) { std::cerr << err.what() << std::endl; return 1; } hostMemory.input.resize(observation.getNrBeams()); if ( dataOptions.dataLOFAR || dataOptions.dataSIGPROC || dataOptions.dataPSRDADA ) { loadInput(observation, deviceOptions, dataOptions, hostMemory, timers); } else { for ( unsigned int beam = 0; beam < observation.getNrBeams(); beam++ ) { // TODO: if there are multiple synthesized beams, the generated data should take this into account hostMemory.input.at(beam) = new std::vector<std::vector<inputDataType> *>(observation.getNrBatches()); AstroData::generateSinglePulse(generatorOptions.width, generatorOptions.DM, observation, deviceOptions.padding.at(deviceOptions.deviceName), *(hostMemory.input.at(beam)), inputBits, generatorOptions.random); } } } catch ( std::exception & err ) { std::cerr << err.what() << std::endl; return 1; } // Print message with observation and search information if ( options.print) { std::cout << "Device: " << deviceOptions.deviceName << " (" + std::to_string(deviceOptions.platformID) + ", "; std::cout << std::to_string(deviceOptions.deviceID) + ")" << std::endl; std::cout << "Padding: " << deviceOptions.padding[deviceOptions.deviceName] << " bytes" << std::endl; std::cout << std::endl; std::cout << "Beams: " << observation.getNrBeams() << std::endl; std::cout << "Synthesized Beams: " << observation.getNrSynthesizedBeams() << std::endl; std::cout << "Batches: " << observation.getNrBatches() << std::endl; std::cout << "Samples: " << observation.getNrSamplesPerBatch() << std::endl; std::cout << "Sampling time: " << observation.getSamplingTime() << std::endl; std::cout << "Frequency range: " << observation.getMinFreq() << " MHz, " << observation.getMaxFreq() << " MHz"; std::cout << std::endl; std::cout << "Subbands: " << observation.getNrSubbands() << " (" << observation.getSubbandBandwidth() << " MHz)"; std::cout << std::endl; std::cout << "Channels: " << observation.getNrChannels() << " (" << observation.getChannelBandwidth() << " MHz)"; std::cout << std::endl; std::cout << "Zapped Channels: " << observation.getNrZappedChannels() << std::endl; std::cout << "Integration steps: " << hostMemory.integrationSteps.size() << std::endl; if ( options.subbandDedispersion ) { std::cout << "Subbanding DMs: " << observation.getNrDMs(true) << " (" << observation.getFirstDM(true) << ", "; std::cout << observation.getFirstDM(true) + ((observation.getNrDMs(true) - 1) * observation.getDMStep(true)); std::cout << ")" << std::endl; } std::cout << "DMs: " << observation.getNrDMs() << " (" << observation.getFirstDM() << ", "; std::cout << observation.getFirstDM() + ((observation.getNrDMs() - 1) * observation.getDMStep()) << ")"; std::cout << std::endl; std::cout << std::endl; } // Initialize OpenCL openclRunTime.context = new cl::Context(); openclRunTime.platforms = new std::vector<cl::Platform>(); openclRunTime.devices = new std::vector<cl::Device>(); openclRunTime.queues = new std::vector<std::vector<cl::CommandQueue>>(); try { isa::OpenCL::initializeOpenCL(deviceOptions.platformID, 1, openclRunTime.platforms, openclRunTime.context, openclRunTime.devices, openclRunTime.queues); } catch ( isa::OpenCL::OpenCLError & err ) { std::cerr << err.what() << std::endl; return 1; } // Memory allocation allocateHostMemory(observation, options, deviceOptions, dataOptions, kernelConfigurations, hostMemory); if ( observation.getNrDelayBatches() > observation.getNrBatches() ) { std::cerr << "Not enough input batches for the specified search." << std::endl; return 1; } try { allocateDeviceMemory(openclRunTime, options, deviceOptions, hostMemory, deviceMemory); } catch ( cl::Error & err ) { std::cerr << "Memory error: " << err.what() << " " << err.err() << std::endl; return 1; } // Generate OpenCL kernels try { generateOpenCLKernels(openclRunTime, observation, options, deviceOptions, kernelConfigurations, hostMemory, deviceMemory, kernels); } catch ( std::exception & err ) { std::cerr << "OpenCL code generation error: " << err.what() << std::endl; return 1; } // Generate run time configurations for the OpenCL kernels generateOpenCLRunTimeConfigurations(observation, options, deviceOptions, kernelConfigurations, hostMemory, kernelRunTimeConfigurations); // Search loop pipeline(openclRunTime, observation, options, deviceOptions, dataOptions, timers, kernels, kernelConfigurations, kernelRunTimeConfigurations, hostMemory, deviceMemory); // Store performance statistics before shutting down std::ofstream outputStats; outputStats.open(dataOptions.outputFile + ".stats"); outputStats << std::fixed << std::setprecision(6); outputStats << "# nrDMs" << std::endl; if ( options.subbandDedispersion ) { outputStats << observation.getNrDMs(true) * observation.getNrDMs() << std::endl; } else { outputStats << observation.getNrDMs() << std::endl; } outputStats << "# timers.inputLoad" << std::endl; outputStats << timers.inputLoad.getTotalTime() << std::endl; outputStats << "# timers.search" << std::endl; outputStats << timers.search.getTotalTime() << std::endl; outputStats << "# inputHandlingTotal inputHandlingAvg err" << std::endl; outputStats << timers.inputHandling.getTotalTime() << " " << timers.inputHandling.getAverageTime() << " "; outputStats << timers.inputHandling.getStandardDeviation() << std::endl; outputStats << "# inputCopyTotal inputCopyAvg err" << std::endl; outputStats << timers.inputCopy.getTotalTime() << " " << timers.inputCopy.getAverageTime() << " "; outputStats << timers.inputCopy.getStandardDeviation() << std::endl; if ( ! options.subbandDedispersion ) { outputStats << "# dedispersionSingleStepTotal dedispersionSingleStepAvg err" << std::endl; outputStats << timers.dedispersionSingleStep.getTotalTime() << " "; outputStats << timers.dedispersionSingleStep.getAverageTime() << " "; outputStats << timers.dedispersionSingleStep.getStandardDeviation() << std::endl; } else { outputStats << "# dedispersionStepOneTotal dedispersionStepOneAvg err" << std::endl; outputStats << timers.dedispersionStepOne.getTotalTime() << " "; outputStats << timers.dedispersionStepOne.getAverageTime() << " "; outputStats << timers.dedispersionStepOne.getStandardDeviation() << std::endl; outputStats << "# dedispersionStepTwoTotal dedispersionStepTwoAvg err" << std::endl; outputStats << timers.dedispersionStepTwo.getTotalTime() << " "; outputStats << timers.dedispersionStepTwo.getAverageTime() << " "; outputStats << timers.dedispersionStepTwo.getStandardDeviation() << std::endl; } outputStats << "# integrationTotal integrationAvg err" << std::endl; outputStats << timers.integration.getTotalTime() << " " << timers.integration.getAverageTime() << " "; outputStats << timers.integration.getStandardDeviation() << std::endl; outputStats << "# snrTotal snrAvg err" << std::endl; outputStats << timers.snr.getTotalTime() << " " << timers.snr.getAverageTime() << " "; outputStats << timers.snr.getStandardDeviation() << std::endl; outputStats << "# outputCopyTotal outputCopyAvg err" << std::endl; outputStats << timers.outputCopy.getTotalTime() << " " << timers.outputCopy.getAverageTime() << " "; outputStats << timers.outputCopy.getStandardDeviation() << std::endl; outputStats << "# triggerTimeTotal triggerTimeAvg err" << std::endl; outputStats << timers.trigger.getTotalTime() << " " << timers.trigger.getAverageTime() << " "; outputStats << timers.trigger.getStandardDeviation() << std::endl; outputStats.close(); return 0; } <commit_msg>Updated to use allocateDeviceMemory().<commit_after>// Copyright 2017 Netherlands Institute for Radio Astronomy (ASTRON) // Copyright 2017 Netherlands eScience Center // // 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 <configuration.hpp> #include <CommandLine.hpp> #include <Kernels.hpp> #include <Memory.hpp> #include <Pipeline.hpp> int main(int argc, char *argv[]) { // Command line options Options options{}; DeviceOptions deviceOptions{}; DataOptions dataOptions{}; GeneratorOptions generatorOptions{}; // Memory HostMemory hostMemory{}; DeviceMemory deviceMemory{}; // OpenCL kernels OpenCLRunTime openclRunTime{}; KernelConfigurations kernelConfigurations{}; Kernels kernels{}; KernelRunTimeConfigurations kernelRunTimeConfigurations{}; // Timers Timers timers{}; // Observation AstroData::Observation observation; // Process command line arguments isa::utils::ArgumentList args(argc, argv); try { processCommandLineOptions(args, options, deviceOptions, dataOptions, kernelConfigurations, generatorOptions, observation); } catch (std::exception &err) { return 1; } // Load or generate input data try { try { hostMemory.zappedChannels.resize(observation.getNrChannels(deviceOptions.padding.at(deviceOptions.deviceName) / sizeof(unsigned int))); } catch (std::out_of_range &err) { std::cerr << "No padding specified for " << deviceOptions.deviceName << "." << std::endl; return 1; } try { AstroData::readZappedChannels(observation, dataOptions.channelsFile, hostMemory.zappedChannels); AstroData::readIntegrationSteps(observation, dataOptions.integrationFile, hostMemory.integrationSteps); } catch (AstroData::FileError &err) { std::cerr << err.what() << std::endl; return 1; } hostMemory.input.resize(observation.getNrBeams()); if (dataOptions.dataLOFAR || dataOptions.dataSIGPROC || dataOptions.dataPSRDADA) { loadInput(observation, deviceOptions, dataOptions, hostMemory, timers); } else { for (unsigned int beam = 0; beam < observation.getNrBeams(); beam++) { // TODO: if there are multiple synthesized beams, the generated data should take this into account hostMemory.input.at(beam) = new std::vector<std::vector<inputDataType> *>(observation.getNrBatches()); AstroData::generateSinglePulse(generatorOptions.width, generatorOptions.DM, observation, deviceOptions.padding.at(deviceOptions.deviceName), *(hostMemory.input.at(beam)), inputBits, generatorOptions.random); } } } catch (std::exception &err) { std::cerr << err.what() << std::endl; return 1; } // Print message with observation and search information if (options.print) { std::cout << "Device: " << deviceOptions.deviceName << " (" + std::to_string(deviceOptions.platformID) + ", "; std::cout << std::to_string(deviceOptions.deviceID) + ")" << std::endl; std::cout << "Padding: " << deviceOptions.padding[deviceOptions.deviceName] << " bytes" << std::endl; std::cout << std::endl; std::cout << "Beams: " << observation.getNrBeams() << std::endl; std::cout << "Synthesized Beams: " << observation.getNrSynthesizedBeams() << std::endl; std::cout << "Batches: " << observation.getNrBatches() << std::endl; std::cout << "Samples: " << observation.getNrSamplesPerBatch() << std::endl; std::cout << "Sampling time: " << observation.getSamplingTime() << std::endl; std::cout << "Frequency range: " << observation.getMinFreq() << " MHz, " << observation.getMaxFreq() << " MHz"; std::cout << std::endl; std::cout << "Subbands: " << observation.getNrSubbands() << " (" << observation.getSubbandBandwidth() << " MHz)"; std::cout << std::endl; std::cout << "Channels: " << observation.getNrChannels() << " (" << observation.getChannelBandwidth() << " MHz)"; std::cout << std::endl; std::cout << "Zapped Channels: " << observation.getNrZappedChannels() << std::endl; std::cout << "Integration steps: " << hostMemory.integrationSteps.size() << std::endl; if (options.subbandDedispersion) { std::cout << "Subbanding DMs: " << observation.getNrDMs(true) << " (" << observation.getFirstDM(true) << ", "; std::cout << observation.getFirstDM(true) + ((observation.getNrDMs(true) - 1) * observation.getDMStep(true)); std::cout << ")" << std::endl; } std::cout << "DMs: " << observation.getNrDMs() << " (" << observation.getFirstDM() << ", "; std::cout << observation.getFirstDM() + ((observation.getNrDMs() - 1) * observation.getDMStep()) << ")"; std::cout << std::endl; std::cout << std::endl; } // Initialize OpenCL openclRunTime.context = new cl::Context(); openclRunTime.platforms = new std::vector<cl::Platform>(); openclRunTime.devices = new std::vector<cl::Device>(); openclRunTime.queues = new std::vector<std::vector<cl::CommandQueue>>(); try { isa::OpenCL::initializeOpenCL(deviceOptions.platformID, 1, openclRunTime.platforms, openclRunTime.context, openclRunTime.devices, openclRunTime.queues); } catch (isa::OpenCL::OpenCLError &err) { std::cerr << err.what() << std::endl; return 1; } // Memory allocation allocateHostMemory(observation, options, deviceOptions, dataOptions, kernelConfigurations, hostMemory); if (observation.getNrDelayBatches() > observation.getNrBatches()) { std::cerr << "Not enough input batches for the specified search." << std::endl; return 1; } try { allocateDeviceMemory(observation, openclRunTime, options, deviceOptions, hostMemory, deviceMemory); } catch (cl::Error &err) { std::cerr << "Memory error: " << err.what() << " " << err.err() << std::endl; return 1; } // Generate OpenCL kernels try { generateOpenCLKernels(openclRunTime, observation, options, deviceOptions, kernelConfigurations, hostMemory, deviceMemory, kernels); } catch (std::exception &err) { std::cerr << "OpenCL code generation error: " << err.what() << std::endl; return 1; } // Generate run time configurations for the OpenCL kernels generateOpenCLRunTimeConfigurations(observation, options, deviceOptions, kernelConfigurations, hostMemory, kernelRunTimeConfigurations); // Search loop pipeline(openclRunTime, observation, options, deviceOptions, dataOptions, timers, kernels, kernelConfigurations, kernelRunTimeConfigurations, hostMemory, deviceMemory); // Store performance statistics before shutting down std::ofstream outputStats; outputStats.open(dataOptions.outputFile + ".stats"); outputStats << std::fixed << std::setprecision(6); outputStats << "# nrDMs" << std::endl; if (options.subbandDedispersion) { outputStats << observation.getNrDMs(true) * observation.getNrDMs() << std::endl; } else { outputStats << observation.getNrDMs() << std::endl; } outputStats << "# timers.inputLoad" << std::endl; outputStats << timers.inputLoad.getTotalTime() << std::endl; outputStats << "# timers.search" << std::endl; outputStats << timers.search.getTotalTime() << std::endl; outputStats << "# inputHandlingTotal inputHandlingAvg err" << std::endl; outputStats << timers.inputHandling.getTotalTime() << " " << timers.inputHandling.getAverageTime() << " "; outputStats << timers.inputHandling.getStandardDeviation() << std::endl; outputStats << "# inputCopyTotal inputCopyAvg err" << std::endl; outputStats << timers.inputCopy.getTotalTime() << " " << timers.inputCopy.getAverageTime() << " "; outputStats << timers.inputCopy.getStandardDeviation() << std::endl; if (!options.subbandDedispersion) { outputStats << "# dedispersionSingleStepTotal dedispersionSingleStepAvg err" << std::endl; outputStats << timers.dedispersionSingleStep.getTotalTime() << " "; outputStats << timers.dedispersionSingleStep.getAverageTime() << " "; outputStats << timers.dedispersionSingleStep.getStandardDeviation() << std::endl; } else { outputStats << "# dedispersionStepOneTotal dedispersionStepOneAvg err" << std::endl; outputStats << timers.dedispersionStepOne.getTotalTime() << " "; outputStats << timers.dedispersionStepOne.getAverageTime() << " "; outputStats << timers.dedispersionStepOne.getStandardDeviation() << std::endl; outputStats << "# dedispersionStepTwoTotal dedispersionStepTwoAvg err" << std::endl; outputStats << timers.dedispersionStepTwo.getTotalTime() << " "; outputStats << timers.dedispersionStepTwo.getAverageTime() << " "; outputStats << timers.dedispersionStepTwo.getStandardDeviation() << std::endl; } outputStats << "# integrationTotal integrationAvg err" << std::endl; outputStats << timers.integration.getTotalTime() << " " << timers.integration.getAverageTime() << " "; outputStats << timers.integration.getStandardDeviation() << std::endl; outputStats << "# snrTotal snrAvg err" << std::endl; outputStats << timers.snr.getTotalTime() << " " << timers.snr.getAverageTime() << " "; outputStats << timers.snr.getStandardDeviation() << std::endl; outputStats << "# outputCopyTotal outputCopyAvg err" << std::endl; outputStats << timers.outputCopy.getTotalTime() << " " << timers.outputCopy.getAverageTime() << " "; outputStats << timers.outputCopy.getStandardDeviation() << std::endl; outputStats << "# triggerTimeTotal triggerTimeAvg err" << std::endl; outputStats << timers.trigger.getTotalTime() << " " << timers.trigger.getAverageTime() << " "; outputStats << timers.trigger.getStandardDeviation() << std::endl; outputStats.close(); return 0; } <|endoftext|>
<commit_before>#include "SymbolicMath.h" #include "SymbolicMathFunction.h" #include "SymbolicMathHelpers.h" #include "SymbolicMathJITTypes.h" #include <iostream> struct Test { std::string expression; std::function<double(double)> native; }; // clang-format off const std::vector<Test> tests = { // obvious simplifcations {"c/1.0", [](double c) { return c / 1.0; }}, {"c+0", [](double c) { return c + 0.0; }}, {"c*0", [](double c) { return c * 0.0; }}, {"0/c", [](double c) { return 0.0 / c; }}, // expressions {"1 + c + 2*c + 3*c^3", [](double c) { return 1 + c + 2*c + 3*c*c*c; }}, {"c + sin(1.1)", [](double c) { return c + std::sin(1.1); }}, // mathematical functions {"sin(c)", [](double c) { return std::sin(c); }}, {"cos(c)", [](double c) { return std::cos(c); }}, {"tan(c)", [](double c) { return std::tan(c); }}, {"csc(c)", [](double c) { return 1.0 / std::sin(c); }}, {"sec(c)", [](double c) { return 1.0 / std::cos(c); }}, {"cot(c)", [](double c) { return 1.0 / std::tan(c); }}, {"sinh(c)", [](double c) { return std::sinh(c); }}, {"cosh(c)", [](double c) { return std::cosh(c); }}, {"tanh(c)", [](double c) { return std::tanh(c); }}, {"asin(c*c)", [](double c) { return std::asin(c*c); }}, {"acos(c*c)", [](double c) { return std::acos(c*c); }}, {"atan(c)", [](double c) { return std::atan(c); }}, {"asinh(c)", [](double c) { return std::asinh(c); }}, {"acosh(c+1.1)", [](double c) { return std::acosh(c+1.1); }}, {"atanh(c*0.9)", [](double c) { return std::atanh(c*0.9); }}, {"erf(c)", [](double c) { return std::erf(c); }}, {"exp(c)", [](double c) { return std::exp(c); }}, {"exp2(c)", [](double c) { return std::exp2(c); }}, {"log(c+1.1)", [](double c) { return std::log(c+1.1); }}, {"log2(c+1.1)", [](double c) { return std::log2(c+1.1); }}, {"log10(c+1.1)", [](double c) { return std::log10(c+1.1); }}, {"atan2(c,0.5)", [](double c) { return std::atan2(c, 0.5); }}, {"atan2(0.5,c)", [](double c) { return std::atan2(0.5, c); }}, {"atan2(2*c, 3*c)", [](double c) { return std::atan2(2*c, 3*c); }}, {"int(c)", [](double c) { return std::round(c); }}, {"floor(c)", [](double c) { return std::floor(c); }}, {"ceil(c)", [](double c) { return std::ceil(c); }}, {"trunc(c)", [](double c) { return static_cast<int>(c); }}, // powers and their simplifications {"pow(c,3)", [](double c) { return std::pow(c, 3); }}, {"pow(c,-3)", [](double c) { return std::pow(c, -3); }}, {"pow(c,3.5)", [](double c) { return std::pow(c, 3.5); }}, {"pow(pow(c,3.5),2)", [](double c) { return std::pow(std::pow(c, 3.5), 2.0); }}, {"pow(pow(c,3.5),2.5)", [](double c) { return std::pow(std::pow(c, 3.5), 2.5); }}, {"pow(c,1)", [](double c) { return std::pow(c, 1); }}, // comparison operators {"c<0.2", [](double c) { return c<0.2; }}, {"c>0.2", [](double c) { return c>0.2; }}, {"c<=0.2", [](double c) { return c<=0.2; }}, // {"c<=-0.7", [](double c) { return c<=-0.7; }}, // fails {"c>=0.2", [](double c) { return c>=0.2; }}, {"c==0.2", [](double c) { return c==0.2; }}, {"c!=0.2", [](double c) { return c!=0.2; }}, // constant comparisons {"1<2", [](double c) { return 1<2; }}, {"1>2", [](double c) { return 1>2; }}, {"1<2", [](double c) { return 1<=2; }}, {"1>2", [](double c) { return 1>=2; }}, {"1==2", [](double c) { return 1==2; }}, {"1!=2", [](double c) { return 1!=2; }}, // logical operators {"c<0.5 & c>-0.5", [](double c) { return c<0.5 && c>-0.5; }}, {"c>0.5 | c<-0.5", [](double c) { return c>0.5 || c<-0.5; }}, {"c>0.5 | c<-0.5 | (c<0.3 & c > -0.1)", [](double c) { return c>0.5 || c<-0.5 || (c<0.3 && c > -0.1); }}, // logical operators with non 0/1 constants {"c<0.2 & 2.0", [](double c) { return c<0.2 && static_cast<bool>(2.0); }}, {"c<0.2 | 2.0", [](double c) { return c<0.2 || static_cast<bool>(2.0); }}, {"c<0.2 & 0.0", [](double c) { return c<0.2 && static_cast<bool>(0.0); }}, {"c<0.2 | 0.0", [](double c) { return c<0.2 || static_cast<bool>(0.0); }}, // conditional (if) {"if(c<0.15, 10, 20)", [](double c) { return c < 0.15 ? 10 : 20; }}, // nested if {"if(c<-0.5, 10, if(c>0.2, 20, 30))", [](double c) { return c <= -0.5 ? 10 : (c > 0.2 ? 20 : 30); }}, }; // clang-format on struct DiffTest { std::string expression; SymbolicMath::Real cmin, cmax, dc, epsilon; SymbolicMath::Real tol; }; // clang-format off const std::vector<DiffTest> difftests = { {"c", -10, 10, 0.7, 0.1, 1e-9}, {"abs(c)", -10, 10, 0.7, 0.1, 1e-9}, {"sin(c)", -4, 4, 0.1, 1e-8, 1e-8}, {"cos(c)", -4, 4, 0.1, 1e-8, 1e-8}, {"tan(c)", -4, 4, 0.11, 1e-9, 2e-7}, {"csc(c)", -0.99, 0.99, 0.1, 1e-9, 1e-7}, {"sec(c)", -0.99, 0.99, 0.1, 1e-9, 1e-7}, {"cot(c)", -0.99, 0.99, 0.1, 1e-9, 1e-7}, {"sinh(c)", -5, 5, 0.1, 1e-9, 2e-7}, {"cosh(c)", -5, 5, 0.1, 1e-9, 1e-7}, {"tanh(c)", -5, 5, 0.2, 1e-9, 1e-6}, {"asin(c)", -0.99, 0.99, 0.1, 1e-9, 1e-7}, {"acos(c)", -0.99, 0.99, 0.1, 1e-9, 1e-7}, {"atan(c)", -5, 5, 0.1, 1e-9, 1e-6}, {"asinh(c)", -5, 5, 0.1, 1e-9, 1e-6}, {"acosh(c)", 1.01, 5, 0.1, 1e-9, 2e-7}, {"atanh(c)", -0.99, 0.99, 0.1, 1e-9, 1e-7}, {"cbrt(c)", 0.01, 5, 0.1, 1e-9, 5e-7}, {"erf(c)", -5, 5, 0.1, 1e-9, 3e-7}, {"log(c)", 0.01, 5, 0.1, 1e-9, 2e-7}, {"log2(c)", 0.01, 5, 0.1, 1e-9, 2e-7}, {"log10(c)", 0.01, 5, 0.1, 1e-9, 2e-7}, {"exp(c)", -5, 5, 0.1, 1e-9, 2e-7}, {"exp2(c)", -5, 5, 0.1, 1e-9, 2e-7}, {"c^5", -4, 4, 0.1, 1e-8, 2e-8}, {"sin(cos(c))", -4, 4, 0.1, 1e-8, 2e-8}, {"sin(c)+cos(c)", -4, 4, 0.1, 1e-8, 2e-8}, {"sin(c)*cos(c)", -4, 4, 0.1, 1e-8, 2e-8}, }; // clang-format on int main(int argc, char * argv[]) { double norm; int total = 0, fail = 0; // test direct evaluation, simplification, and compilation for (auto & test : tests) { SymbolicMath::Parser parser; SymbolicMath::Real c; auto c_var = std::make_shared<SymbolicMath::RealReferenceData>(c, "c"); parser.registerValueProvider(c_var); auto func = parser.parse(test.expression); // evaluate for various values of c norm = 0.0; for (c = -1.0; c <= 1.0; c += 0.3) norm += std::abs(func.value() - test.native(c)); if (norm > 1e-9) { std::cerr << "Error evaluating unsimplified expression '" << test.expression << "'\n"; fail++; } func.simplify(); // evaluate for various values of c norm = 0.0; for (c = -1.0; c <= 1.0; c += 0.3) norm += std::abs(func.value() - test.native(c)); if (norm > 1e-9) { std::cerr << "Error evaluating expression '" << test.expression << "' simplified to '" << func.format() << "'\n"; fail++; } func.compile(); if (!func.isCompiled()) { std::cerr << "Error compiling expression '" << test.expression << "' simplified to '" << func.format() << "'\n"; fail++; } // evaluate for various values of c norm = 0.0; for (c = -1.0; c <= 1.0; c += 0.3) norm += std::abs(func.value() - test.native(c)); if (norm > 1e-9) { std::cerr << "Error " << norm << "evaluating compiled expression '" << test.expression << "' simplified to '" << func.format() << "'\n"; fail++; } total += 3; } // test derivatives for (auto & test : difftests) { SymbolicMath::Parser parser; SymbolicMath::Real c; auto c_var = std::make_shared<SymbolicMath::RealReferenceData>(c, "c"); parser.registerValueProvider(c_var); auto func = parser.parse(test.expression); func.simplify(); func.compile(); auto diff = func.D(c_var); diff.simplify(); diff.compile(); if (!diff.isCompiled()) { std::cerr << "Error compiling derivative of '" << test.expression << "' simplified to '" << diff.format() << "'\n"; fail++; } // finite differencing norm = 0.0; SymbolicMath::Real abssum = 0.0; for (c = test.cmin; c <= test.cmax; c += test.dc) { auto a = func.value(); c += test.epsilon; auto b = func.value(); c -= test.epsilon; auto d = diff.value(); abssum += std::abs(d); norm += std::abs(d - (b - a) / test.epsilon); } // for debug purposes (to set tolerances for new tests) // std::cerr << norm / abssum << '\t' << test.expression << '\n'; if (norm / abssum > test.tol) { std::cerr << "Derivative does not match finite differencing for '" << test.expression << "' and the derivative '" << diff.format() << "'.\nnorm/abssum = " << (norm / abssum) << "\n"; fail++; } total += 2; } // Final output if (fail) { std::cout << "\033[1;31m"; // red std::cout << (total - fail) << " tests PASSED, " << fail << " tests FAILED!\n"; } else { std::cout << "\033[1;32m"; // green std::cout << "ALL " << total << " tests PASSED.\n"; } std::cout << "\033[0m"; // reset color return fail ? 1 : 0; } <commit_msg>missing include<commit_after>#include "SymbolicMath.h" #include "SymbolicMathFunction.h" #include "SymbolicMathHelpers.h" #include "SymbolicMathJITTypes.h" #include <iostream> #include <functional> struct Test { std::string expression; std::function<double(double)> native; }; // clang-format off const std::vector<Test> tests = { // obvious simplifcations {"c/1.0", [](double c) { return c / 1.0; }}, {"c+0", [](double c) { return c + 0.0; }}, {"c*0", [](double c) { return c * 0.0; }}, {"0/c", [](double c) { return 0.0 / c; }}, // expressions {"1 + c + 2*c + 3*c^3", [](double c) { return 1 + c + 2*c + 3*c*c*c; }}, {"c + sin(1.1)", [](double c) { return c + std::sin(1.1); }}, // mathematical functions {"sin(c)", [](double c) { return std::sin(c); }}, {"cos(c)", [](double c) { return std::cos(c); }}, {"tan(c)", [](double c) { return std::tan(c); }}, {"csc(c)", [](double c) { return 1.0 / std::sin(c); }}, {"sec(c)", [](double c) { return 1.0 / std::cos(c); }}, {"cot(c)", [](double c) { return 1.0 / std::tan(c); }}, {"sinh(c)", [](double c) { return std::sinh(c); }}, {"cosh(c)", [](double c) { return std::cosh(c); }}, {"tanh(c)", [](double c) { return std::tanh(c); }}, {"asin(c*c)", [](double c) { return std::asin(c*c); }}, {"acos(c*c)", [](double c) { return std::acos(c*c); }}, {"atan(c)", [](double c) { return std::atan(c); }}, {"asinh(c)", [](double c) { return std::asinh(c); }}, {"acosh(c+1.1)", [](double c) { return std::acosh(c+1.1); }}, {"atanh(c*0.9)", [](double c) { return std::atanh(c*0.9); }}, {"erf(c)", [](double c) { return std::erf(c); }}, {"exp(c)", [](double c) { return std::exp(c); }}, {"exp2(c)", [](double c) { return std::exp2(c); }}, {"log(c+1.1)", [](double c) { return std::log(c+1.1); }}, {"log2(c+1.1)", [](double c) { return std::log2(c+1.1); }}, {"log10(c+1.1)", [](double c) { return std::log10(c+1.1); }}, {"atan2(c,0.5)", [](double c) { return std::atan2(c, 0.5); }}, {"atan2(0.5,c)", [](double c) { return std::atan2(0.5, c); }}, {"atan2(2*c, 3*c)", [](double c) { return std::atan2(2*c, 3*c); }}, {"int(c)", [](double c) { return std::round(c); }}, {"floor(c)", [](double c) { return std::floor(c); }}, {"ceil(c)", [](double c) { return std::ceil(c); }}, {"trunc(c)", [](double c) { return static_cast<int>(c); }}, // powers and their simplifications {"pow(c,3)", [](double c) { return std::pow(c, 3); }}, {"pow(c,-3)", [](double c) { return std::pow(c, -3); }}, {"pow(c,3.5)", [](double c) { return std::pow(c, 3.5); }}, {"pow(pow(c,3.5),2)", [](double c) { return std::pow(std::pow(c, 3.5), 2.0); }}, {"pow(pow(c,3.5),2.5)", [](double c) { return std::pow(std::pow(c, 3.5), 2.5); }}, {"pow(c,1)", [](double c) { return std::pow(c, 1); }}, // comparison operators {"c<0.2", [](double c) { return c<0.2; }}, {"c>0.2", [](double c) { return c>0.2; }}, {"c<=0.2", [](double c) { return c<=0.2; }}, // {"c<=-0.7", [](double c) { return c<=-0.7; }}, // fails {"c>=0.2", [](double c) { return c>=0.2; }}, {"c==0.2", [](double c) { return c==0.2; }}, {"c!=0.2", [](double c) { return c!=0.2; }}, // constant comparisons {"1<2", [](double c) { return 1<2; }}, {"1>2", [](double c) { return 1>2; }}, {"1<2", [](double c) { return 1<=2; }}, {"1>2", [](double c) { return 1>=2; }}, {"1==2", [](double c) { return 1==2; }}, {"1!=2", [](double c) { return 1!=2; }}, // logical operators {"c<0.5 & c>-0.5", [](double c) { return c<0.5 && c>-0.5; }}, {"c>0.5 | c<-0.5", [](double c) { return c>0.5 || c<-0.5; }}, {"c>0.5 | c<-0.5 | (c<0.3 & c > -0.1)", [](double c) { return c>0.5 || c<-0.5 || (c<0.3 && c > -0.1); }}, // logical operators with non 0/1 constants {"c<0.2 & 2.0", [](double c) { return c<0.2 && static_cast<bool>(2.0); }}, {"c<0.2 | 2.0", [](double c) { return c<0.2 || static_cast<bool>(2.0); }}, {"c<0.2 & 0.0", [](double c) { return c<0.2 && static_cast<bool>(0.0); }}, {"c<0.2 | 0.0", [](double c) { return c<0.2 || static_cast<bool>(0.0); }}, // conditional (if) {"if(c<0.15, 10, 20)", [](double c) { return c < 0.15 ? 10 : 20; }}, // nested if {"if(c<-0.5, 10, if(c>0.2, 20, 30))", [](double c) { return c <= -0.5 ? 10 : (c > 0.2 ? 20 : 30); }}, }; // clang-format on struct DiffTest { std::string expression; SymbolicMath::Real cmin, cmax, dc, epsilon; SymbolicMath::Real tol; }; // clang-format off const std::vector<DiffTest> difftests = { {"c", -10, 10, 0.7, 0.1, 1e-9}, {"abs(c)", -10, 10, 0.7, 0.1, 1e-9}, {"sin(c)", -4, 4, 0.1, 1e-8, 1e-8}, {"cos(c)", -4, 4, 0.1, 1e-8, 1e-8}, {"tan(c)", -4, 4, 0.11, 1e-9, 2e-7}, {"csc(c)", -0.99, 0.99, 0.1, 1e-9, 1e-7}, {"sec(c)", -0.99, 0.99, 0.1, 1e-9, 1e-7}, {"cot(c)", -0.99, 0.99, 0.1, 1e-9, 1e-7}, {"sinh(c)", -5, 5, 0.1, 1e-9, 2e-7}, {"cosh(c)", -5, 5, 0.1, 1e-9, 1e-7}, {"tanh(c)", -5, 5, 0.2, 1e-9, 1e-6}, {"asin(c)", -0.99, 0.99, 0.1, 1e-9, 1e-7}, {"acos(c)", -0.99, 0.99, 0.1, 1e-9, 1e-7}, {"atan(c)", -5, 5, 0.1, 1e-9, 1e-6}, {"asinh(c)", -5, 5, 0.1, 1e-9, 1e-6}, {"acosh(c)", 1.01, 5, 0.1, 1e-9, 2e-7}, {"atanh(c)", -0.99, 0.99, 0.1, 1e-9, 1e-7}, {"cbrt(c)", 0.01, 5, 0.1, 1e-9, 5e-7}, {"erf(c)", -5, 5, 0.1, 1e-9, 3e-7}, {"log(c)", 0.01, 5, 0.1, 1e-9, 2e-7}, {"log2(c)", 0.01, 5, 0.1, 1e-9, 2e-7}, {"log10(c)", 0.01, 5, 0.1, 1e-9, 2e-7}, {"exp(c)", -5, 5, 0.1, 1e-9, 2e-7}, {"exp2(c)", -5, 5, 0.1, 1e-9, 2e-7}, {"c^5", -4, 4, 0.1, 1e-8, 2e-8}, {"sin(cos(c))", -4, 4, 0.1, 1e-8, 2e-8}, {"sin(c)+cos(c)", -4, 4, 0.1, 1e-8, 2e-8}, {"sin(c)*cos(c)", -4, 4, 0.1, 1e-8, 2e-8}, }; // clang-format on int main(int argc, char * argv[]) { double norm; int total = 0, fail = 0; // test direct evaluation, simplification, and compilation for (auto & test : tests) { SymbolicMath::Parser parser; SymbolicMath::Real c; auto c_var = std::make_shared<SymbolicMath::RealReferenceData>(c, "c"); parser.registerValueProvider(c_var); auto func = parser.parse(test.expression); // evaluate for various values of c norm = 0.0; for (c = -1.0; c <= 1.0; c += 0.3) norm += std::abs(func.value() - test.native(c)); if (norm > 1e-9) { std::cerr << "Error evaluating unsimplified expression '" << test.expression << "'\n"; fail++; } func.simplify(); // evaluate for various values of c norm = 0.0; for (c = -1.0; c <= 1.0; c += 0.3) norm += std::abs(func.value() - test.native(c)); if (norm > 1e-9) { std::cerr << "Error evaluating expression '" << test.expression << "' simplified to '" << func.format() << "'\n"; fail++; } func.compile(); if (!func.isCompiled()) { std::cerr << "Error compiling expression '" << test.expression << "' simplified to '" << func.format() << "'\n"; fail++; } // evaluate for various values of c norm = 0.0; for (c = -1.0; c <= 1.0; c += 0.3) norm += std::abs(func.value() - test.native(c)); if (norm > 1e-9) { std::cerr << "Error " << norm << "evaluating compiled expression '" << test.expression << "' simplified to '" << func.format() << "'\n"; fail++; } total += 3; } // test derivatives for (auto & test : difftests) { SymbolicMath::Parser parser; SymbolicMath::Real c; auto c_var = std::make_shared<SymbolicMath::RealReferenceData>(c, "c"); parser.registerValueProvider(c_var); auto func = parser.parse(test.expression); func.simplify(); func.compile(); auto diff = func.D(c_var); diff.simplify(); diff.compile(); if (!diff.isCompiled()) { std::cerr << "Error compiling derivative of '" << test.expression << "' simplified to '" << diff.format() << "'\n"; fail++; } // finite differencing norm = 0.0; SymbolicMath::Real abssum = 0.0; for (c = test.cmin; c <= test.cmax; c += test.dc) { auto a = func.value(); c += test.epsilon; auto b = func.value(); c -= test.epsilon; auto d = diff.value(); abssum += std::abs(d); norm += std::abs(d - (b - a) / test.epsilon); } // for debug purposes (to set tolerances for new tests) // std::cerr << norm / abssum << '\t' << test.expression << '\n'; if (norm / abssum > test.tol) { std::cerr << "Derivative does not match finite differencing for '" << test.expression << "' and the derivative '" << diff.format() << "'.\nnorm/abssum = " << (norm / abssum) << "\n"; fail++; } total += 2; } // Final output if (fail) { std::cout << "\033[1;31m"; // red std::cout << (total - fail) << " tests PASSED, " << fail << " tests FAILED!\n"; } else { std::cout << "\033[1;32m"; // green std::cout << "ALL " << total << " tests PASSED.\n"; } std::cout << "\033[0m"; // reset color return fail ? 1 : 0; } <|endoftext|>
<commit_before>#include "FactDB.h" #include <cstdio> using namespace std; using namespace btree; #define CHUNK_SIZE 1048576 // // Append To KB // void appendToKB(const uint64_t* factStream, const uint64_t& count, btree_set<uint64_t>* kb) { for (uint64_t i = 0; i < count; ++i) { kb->insert(factStream[i]); } } const btree_set<uint64_t> readKB(string path) { btree_set<uint64_t> kb; // Open the KB file FILE* file; file = fopen(path.c_str(), "r"); if (file == NULL) { fprintf(stderr, "Can't open KB file %s!\n", path.c_str()); exit(1); } // Read chunks uint64_t* buffer = (uint64_t*) malloc(CHUNK_SIZE * sizeof(uint64_t)); uint64_t numRead; uint64_t nextPrint = 1000000; fprintf(stderr, "Reading the knowledge base..."); while ( (numRead = fread(buffer, sizeof(uint64_t), CHUNK_SIZE, file)) == CHUNK_SIZE ) { appendToKB(buffer, numRead, &kb); if (kb.size() > nextPrint) { nextPrint += 1000000; fprintf(stderr, "."); } } appendToKB(buffer, numRead, &kb); fprintf(stderr, "done.\n"); // Return free(buffer); fclose(file); return kb; } <commit_msg>Print the knowledge base size<commit_after>#include "FactDB.h" #include <cstdio> using namespace std; using namespace btree; #define CHUNK_SIZE 1048576 // // Append To KB // void appendToKB(const uint64_t* factStream, const uint64_t& count, btree_set<uint64_t>* kb) { for (uint64_t i = 0; i < count; ++i) { kb->insert(factStream[i]); } } const btree_set<uint64_t> readKB(string path) { btree_set<uint64_t> kb; // Open the KB file FILE* file; file = fopen(path.c_str(), "r"); if (file == NULL) { fprintf(stderr, "Can't open KB file %s!\n", path.c_str()); exit(1); } // Read chunks uint64_t* buffer = (uint64_t*) malloc(CHUNK_SIZE * sizeof(uint64_t)); uint64_t numRead; uint64_t nextPrint = 1000000; fprintf(stderr, "Reading the knowledge base..."); while ( (numRead = fread(buffer, sizeof(uint64_t), CHUNK_SIZE, file)) == CHUNK_SIZE ) { appendToKB(buffer, numRead, &kb); fprintf("%lu\n", kb.size()); if (kb.size() > nextPrint) { nextPrint += 1000000; fprintf(stderr, "."); } } appendToKB(buffer, numRead, &kb); fprintf(stderr, "done.\n"); // Return free(buffer); fclose(file); return kb; } <|endoftext|>
<commit_before>#include "all.h" void Graph::addNoodle(Endpoint from, Endpoint to) { debug("addNoodle: %s[%s](@%p) -> %s[%s](@%p)\n", from.block->name(), from.port, from.block, to.block->name(), to.port, to.block); vertex_t vert_from, vert_to; bool found_from = false, found_to = false; /* see if the from or to vertex (or both) is already in the graph */ auto v_it = vertices(m_graph); for (auto it = v_it.first; it != v_it.second; ++it) { vertex_t v = *it; if (m_graph[v] == from.block) { debug("- block %s(@%p) is already in the graph.\n", from.block->name(), from.block); vert_from = v; found_from = true; } if (m_graph[v] == to.block) { debug("- block %s(@%p) is already in the graph.\n", to.block->name(), to.block); vert_to = v; found_to = true; } if (found_from && found_to) break; } /* add new vertex(es) to the graph if necessary */ if (!found_from) { debug("- block %s(@%p) is not in the graph; adding now.\n", from.block->name(), from.block); vert_from = add_vertex(m_graph); m_graph[vert_from] = from.block; } if (!found_to) { debug("- block %s(@%p) is not in the graph; adding now.\n", to.block->name(), to.block); vert_to = add_vertex(m_graph); m_graph[vert_to] = to.block; } debug("- attempting to connect noodle.\n"); /* the connect functions will ensure that this is not a duplicate noodle and * that inputs are not connected to multiple noodles */ Noodle *noodle = new Noodle(from.port, to.port); from.block->outputs.connect(from.port, noodle); to.block->inputs.connect(to.port, noodle); debug("- adding noodle to the graph.\n"); edge_t edge; bool result; tie(edge, result) = add_edge(vert_from, vert_to, m_graph); assert(result); m_graph[edge] = noodle; dumpGraph(); m_needCheck = true; } int Graph::checkGraph(void) { debug("checkGraph: checking graph validity\n"); int errors = 0; auto e_it = edges(m_graph); if (e_it.first == e_it.second) { throw EmptyGraphException(); ++errors; } // TODO: check for nodes with no edges (error) [is this possible?] if (errors == 0) { m_needCheck = false; } debug("- %d errors\n", errors); return errors; } void Graph::dumpGraph(void) { /* don't waste time accessing stuff that we won't print */ if (!verbose) return; debug("\n======================= graph summary =======================\n"); debug("%lu blocks\n", num_vertices(m_graph)); auto v_it = vertices(m_graph); for (auto it = v_it.first; it != v_it.second; ++it) { vertex_t v = *it; Block *b = m_graph[v]; debug("+ block: %s(@%p)\n", b->name(), b); } debug("\n%lu noodles\n", num_edges(m_graph)); auto e_it = edges(m_graph); for (auto it = e_it.first; it != e_it.second; ++it) { edge_t e = *it; Noodle *n = m_graph[e]; vertex_t v1 = source(e, m_graph); vertex_t v2 = target(e, m_graph); Block *b1 = m_graph[v1]; Block *b2 = m_graph[v2]; debug("+ noodle: %s[%s](@%p) -> %s[%s](@%p)\n", b1->name(), n->m_fromPort, b1, b2->name(), n->m_toPort, b2); } debug("=============================================================\n\n"); } void Graph::run(void) { if (m_needCheck) { if (checkGraph() != 0) { throw GraphInvalidException(); } } /* Call work on all blocks */ auto v_it = vertices(m_graph); for (auto it = v_it.first; it != v_it.second; ++it) { vertex_t v = *it; Block *b = m_graph[v]; debug("run: calling work on block %s(@%p)\n", b->name(), b); b->work(); } #if 0 /* Pass samples between blocks. As currently written, no attempt is made * to handle blocks with multiple inputs or multiple outputs. */ v_it = vertices(m_graph); for (auto it = v_it.first; it != v_it.second; ++it) { vertex_t v = *it; debug("run: on block %p\n", m_graph[v]); /* iterator over all outbound edges */ auto e_it = out_edges(v, m_graph); /* This means there are no outbound edges */ if (e_it.first == e_it.second) { continue; } while (!m_graph[v]->outputEmpty()) { int sample = m_graph[v]->popOutput(); /* Iterate over all outbound edges. */ for (auto ei = e_it.first; ei != e_it.second; ++ei) { vertex_t v_sink = target(*ei, m_graph); auto conn = m_graph[*ei]; debug("-- pushing sample %d to block %p input %d" " (but actually input 0 for now)\n", sample, m_graph[v_sink], conn.second); m_graph[v_sink]->pushInput(sample/*, conn.second*/); } } } #endif } <commit_msg>remove sample copying code from Graph::run<commit_after>#include "all.h" void Graph::addNoodle(Endpoint from, Endpoint to) { debug("addNoodle: %s[%s](@%p) -> %s[%s](@%p)\n", from.block->name(), from.port, from.block, to.block->name(), to.port, to.block); vertex_t vert_from, vert_to; bool found_from = false, found_to = false; /* see if the from or to vertex (or both) is already in the graph */ auto v_it = vertices(m_graph); for (auto it = v_it.first; it != v_it.second; ++it) { vertex_t v = *it; if (m_graph[v] == from.block) { debug("- block %s(@%p) is already in the graph.\n", from.block->name(), from.block); vert_from = v; found_from = true; } if (m_graph[v] == to.block) { debug("- block %s(@%p) is already in the graph.\n", to.block->name(), to.block); vert_to = v; found_to = true; } if (found_from && found_to) break; } /* add new vertex(es) to the graph if necessary */ if (!found_from) { debug("- block %s(@%p) is not in the graph; adding now.\n", from.block->name(), from.block); vert_from = add_vertex(m_graph); m_graph[vert_from] = from.block; } if (!found_to) { debug("- block %s(@%p) is not in the graph; adding now.\n", to.block->name(), to.block); vert_to = add_vertex(m_graph); m_graph[vert_to] = to.block; } debug("- attempting to connect noodle.\n"); /* the connect functions will ensure that this is not a duplicate noodle and * that inputs are not connected to multiple noodles */ Noodle *noodle = new Noodle(from.port, to.port); from.block->outputs.connect(from.port, noodle); to.block->inputs.connect(to.port, noodle); debug("- adding noodle to the graph.\n"); edge_t edge; bool result; tie(edge, result) = add_edge(vert_from, vert_to, m_graph); assert(result); m_graph[edge] = noodle; dumpGraph(); m_needCheck = true; } int Graph::checkGraph(void) { debug("checkGraph: checking graph validity\n"); int errors = 0; auto e_it = edges(m_graph); if (e_it.first == e_it.second) { throw EmptyGraphException(); ++errors; } // TODO: check for nodes with no edges (error) [is this possible?] if (errors == 0) { m_needCheck = false; } debug("- %d errors\n", errors); return errors; } void Graph::dumpGraph(void) { /* don't waste time accessing stuff that we won't print */ if (!verbose) return; debug("\n======================= graph summary =======================\n"); debug("%lu blocks\n", num_vertices(m_graph)); auto v_it = vertices(m_graph); for (auto it = v_it.first; it != v_it.second; ++it) { vertex_t v = *it; Block *b = m_graph[v]; debug("+ block: %s(@%p)\n", b->name(), b); } debug("\n%lu noodles\n", num_edges(m_graph)); auto e_it = edges(m_graph); for (auto it = e_it.first; it != e_it.second; ++it) { edge_t e = *it; Noodle *n = m_graph[e]; vertex_t v1 = source(e, m_graph); vertex_t v2 = target(e, m_graph); Block *b1 = m_graph[v1]; Block *b2 = m_graph[v2]; debug("+ noodle: %s[%s](@%p) -> %s[%s](@%p)\n", b1->name(), n->m_fromPort, b1, b2->name(), n->m_toPort, b2); } debug("=============================================================\n\n"); } void Graph::run(void) { if (m_needCheck) { if (checkGraph() != 0) { throw GraphInvalidException(); } } /* Call work on all blocks */ auto v_it = vertices(m_graph); for (auto it = v_it.first; it != v_it.second; ++it) { vertex_t v = *it; Block *b = m_graph[v]; debug("run: calling work on block %s(@%p)\n", b->name(), b); b->work(); } } <|endoftext|>
<commit_before>#include <cstdio> #include <cstdlib> #include <set> #include <cstring> #include <ctime> #include "Search.h" #include "Utils.h" using namespace std; // // Static Variables // uint64_t nextId = 1; // TODO(gabor) this is not threadsafe inline uint64_t generateUniqueId() { nextId++; } // // Class Path // Path::Path(const Path* parentOrNull, const word* fact, uint8_t factLength, edge_type edgeType) : parent(parentOrNull), fact(fact), factLength(factLength), edgeType(edgeType) { } Path::Path(const word* fact, uint8_t factLength) : parent(NULL), fact(fact), factLength(factLength), edgeType(255) { } Path::~Path() { }; bool Path::operator==(const Path& other) const { // Check metadata if ( !( edgeType == other.edgeType && factLength == other.factLength ) ) { return false; } // Check fact content for (int i = 0; i < factLength; ++i) { if (other.fact[i] != fact[i]) { return false; } } // Return true return true; } // // Class SearchType // // // Class BreadthFirstSearch // BreadthFirstSearch::BreadthFirstSearch() : fringeLength(0), fringeCapacity(1), fringeI(0), poolCapacity(1), poolLength(0), poppedRoot(false), sumOffset(0){ this->fringe = (Path*) malloc(fringeCapacity * sizeof(Path)); this->memoryPool = (word*) malloc(poolCapacity * sizeof(word*)); } BreadthFirstSearch::~BreadthFirstSearch() { free(this->fringe); free(this->memoryPool); delete this->root; } void BreadthFirstSearch::push( const Path* parent, uint8_t mutationIndex, uint8_t replaceLength, word replace1, word replace2, edge_type edge) { // Allocate new fact // (ensure space) while (poolLength + parent->factLength >= poolCapacity) { // (re-allocate array) word* newPool = (word*) malloc(2 * poolCapacity * sizeof(word*)); uint64_t startOffset = ((uint64_t) newPool) - ((uint64_t) memoryPool); memcpy(newPool, memoryPool, poolCapacity * sizeof(word*)); free(memoryPool); memoryPool = newPool; poolCapacity = 2 * poolCapacity; // (fix pointers -- and God help me for pointer arithmetic) for (int i = 0; i <fringeLength; ++i) { fringe[i].fact = (word*) (startOffset + ((uint64_t) fringe[i].fact)); } printf("Pool capacity is now %lu\n", poolCapacity); } // (allocate fact) uint8_t mutatedLength = parent->factLength - 1 + replaceLength; word* mutated = &memoryPool[poolLength]; poolLength += mutatedLength; // (mutate fact) memcpy(mutated, parent->fact, mutationIndex * sizeof(word)); if (replaceLength > 0) { mutated[mutationIndex] = replace1; } if (replaceLength > 1) { mutated[mutationIndex + 1] = replace2; } memcpy(&(mutated[mutationIndex + replaceLength]), &(parent->fact[mutationIndex + 1]), (parent->factLength - mutationIndex - 1) * sizeof(word)); // Allocate new path // (ensure space) while (fringeLength >= fringeCapacity) { // (re-allocate array) Path* newFringe = (Path*) malloc(2 * fringeCapacity * sizeof(Path)); uint64_t startOffset = ((uint64_t) newFringe) - ((uint64_t) fringe); memcpy(newFringe, fringe, fringeCapacity * sizeof(Path)); free(fringe); fringe = newFringe; fringeCapacity = 2 * fringeCapacity; // (fix pointers -- and God help me for pointer arithmetic) for (int i = 0; i < fringeLength; ++i) { if (fringe[i].parent != root) { fringe[i].parent = (Path*) (startOffset + ((uint64_t) fringe[i].parent)); } } if (parent != root) { parent = (Path*) (startOffset + ((uint64_t) parent)); } printf("Fringe capacity is now %lu\n", fringeCapacity); } // (allocate path) fringeLength += 1; new(&fringe[fringeLength-1]) Path(parent, mutated, mutatedLength, edge); } const Path* BreadthFirstSearch::peek() { if (!poppedRoot && this->fringeI == 0) { poppedRoot = true; return root; } return &this->fringe[this->fringeI]; } const Path* BreadthFirstSearch::pop() { if (!poppedRoot && this->fringeI == 0) { poppedRoot = true; return root; } this->fringeI += 1; return &this->fringe[this->fringeI - 1]; } bool BreadthFirstSearch::isEmpty() { return root == NULL || (poppedRoot && fringeI >= fringeLength); } // // Class CacheStrategy // // // Class CacheStrategyNone // bool CacheStrategyNone::isSeen(const Path&) { return false; } void CacheStrategyNone::add(const Path&) { } // // Function search() // vector<const Path*> Search(Graph* graph, FactDB* knownFacts, const word* queryFact, const uint8_t queryFactLength, SearchType* fringe, CacheStrategy* cache, const uint64_t timeout) { // // Setup // // Create a vector for the return value to occupy vector<const Path*> responses; // Create the start state fringe->root = new Path(queryFact, queryFactLength); // I need the memory to not go away // Initialize timer (number of elements popped from the fringe) uint64_t time = 0; const uint32_t tickTime = 10000; std::clock_t startTime = std::clock(); // // Search // while (!fringe->isEmpty() && time < timeout) { // Get the next element from the fringe if (fringe->isEmpty()) { printf("IMPOSSIBLE: the search fringe is empty. This means (a) there are leaf nodes in the graph, and (b) this would have caused a memory leak.\n"); std::exit(1); } const Path* parent = fringe->pop(); // Update time time += 1; // printf("search tick %lu; popped %s\n", time, toString(*graph, *fringe, parent).c_str()); if (time % tickTime == 0) { const uint32_t tickOOM = tickTime < 1000 ? 1 : (tickTime < 1000000 ? 1000 : (tickTime < 1000000000 ? 1000000 : 1) ); printf("[%lu%s / %lu%s search tick]; %lu paths found (%f ms elapsed)\n", time / tickOOM, tickTime < 1000 ? "" : (tickTime < 999999 ? "k" : (tickTime < 999999999 ? "m" : "") ), timeout / tickOOM, tickTime < 1000 ? "" : (tickTime < 999999 ? "k" : (tickTime < 999999999 ? "m" : "") ), responses.size(), 1000.0 * ( std::clock() - startTime ) / ((double) CLOCKS_PER_SEC)); } // -- Check If Valid -- if (knownFacts->contains(parent->fact, parent->factLength)) { printf("> %s\n", toString(*graph, *fringe, parent).c_str()); responses.push_back(parent); } // -- Mutations -- for (int indexToMutate = 0; indexToMutate < parent->factLength; ++indexToMutate) { // for each index to mutate... const vector<edge>& mutations = graph->outgoingEdges(parent->fact[indexToMutate]); // printf(" mutating index %d; %lu children\n", indexToMutate, mutations.size()); for(vector<edge>::const_iterator it = mutations.begin(); it != mutations.end(); ++it) { // for each possible mutation on that index... if (it->type > 1) { continue; } // TODO(gabor) don't only do WordNet jumps // Add the state to the fringe fringe->push(parent, indexToMutate, 1, it->sink, 0, it->type); } } } printf("Search complete; %lu paths found\n", responses.size()); return responses; } <commit_msg>Fix a corner case causing a seg fault<commit_after>#include <cstdio> #include <cstdlib> #include <set> #include <cstring> #include <ctime> #include "Search.h" #include "Utils.h" using namespace std; // // Static Variables // uint64_t nextId = 1; // TODO(gabor) this is not threadsafe inline uint64_t generateUniqueId() { nextId++; } // // Class Path // Path::Path(const Path* parentOrNull, const word* fact, uint8_t factLength, edge_type edgeType) : parent(parentOrNull), fact(fact), factLength(factLength), edgeType(edgeType) { } Path::Path(const word* fact, uint8_t factLength) : parent(NULL), fact(fact), factLength(factLength), edgeType(255) { } Path::~Path() { }; bool Path::operator==(const Path& other) const { // Check metadata if ( !( edgeType == other.edgeType && factLength == other.factLength ) ) { return false; } // Check fact content for (int i = 0; i < factLength; ++i) { if (other.fact[i] != fact[i]) { return false; } } // Return true return true; } // // Class SearchType // // // Class BreadthFirstSearch // BreadthFirstSearch::BreadthFirstSearch() : fringeLength(0), fringeCapacity(1), fringeI(0), poolCapacity(1), poolLength(0), poppedRoot(false), sumOffset(0){ this->fringe = (Path*) malloc(fringeCapacity * sizeof(Path)); this->memoryPool = (word*) malloc(poolCapacity * sizeof(word*)); } BreadthFirstSearch::~BreadthFirstSearch() { free(this->fringe); free(this->memoryPool); delete this->root; } void BreadthFirstSearch::push( const Path* parent, uint8_t mutationIndex, uint8_t replaceLength, word replace1, word replace2, edge_type edge) { // Allocate new fact uint8_t mutatedLength = parent->factLength - 1 + replaceLength; // (ensure space) while (poolLength + mutatedLength >= poolCapacity) { // (re-allocate array) word* newPool = (word*) malloc(2 * poolCapacity * sizeof(word*)); uint64_t startOffset = ((uint64_t) newPool) - ((uint64_t) memoryPool); memcpy(newPool, memoryPool, poolCapacity * sizeof(word*)); free(memoryPool); memoryPool = newPool; poolCapacity = 2 * poolCapacity; // (fix pointers -- and God help me for pointer arithmetic) for (int i = 0; i <fringeLength; ++i) { fringe[i].fact = (word*) (startOffset + ((uint64_t) fringe[i].fact)); } } // (allocate fact) word* mutated = &memoryPool[poolLength]; poolLength += mutatedLength; // (mutate fact) memcpy(mutated, parent->fact, mutationIndex * sizeof(word)); if (replaceLength > 0) { mutated[mutationIndex] = replace1; } if (replaceLength > 1) { mutated[mutationIndex + 1] = replace2; } if (mutationIndex < parent->factLength - 1) { memcpy(&(mutated[mutationIndex + replaceLength]), &(parent->fact[mutationIndex + 1]), (parent->factLength - mutationIndex - 1) * sizeof(word)); } // Allocate new path // (ensure space) while (fringeLength >= fringeCapacity) { // (re-allocate array) Path* newFringe = (Path*) malloc(2 * fringeCapacity * sizeof(Path)); uint64_t startOffset = ((uint64_t) newFringe) - ((uint64_t) fringe); memcpy(newFringe, fringe, fringeCapacity * sizeof(Path)); free(fringe); fringe = newFringe; fringeCapacity = 2 * fringeCapacity; // (fix pointers -- and God help me for pointer arithmetic) for (int i = 0; i < fringeLength; ++i) { if (fringe[i].parent != root) { fringe[i].parent = (Path*) (startOffset + ((uint64_t) fringe[i].parent)); } } if (parent != root) { parent = (Path*) (startOffset + ((uint64_t) parent)); } } // (allocate path) fringeLength += 1; new(&fringe[fringeLength-1]) Path(parent, mutated, mutatedLength, edge); } const Path* BreadthFirstSearch::peek() { if (!poppedRoot && this->fringeI == 0) { poppedRoot = true; return root; } return &this->fringe[this->fringeI]; } const Path* BreadthFirstSearch::pop() { if (!poppedRoot && this->fringeI == 0) { poppedRoot = true; return root; } this->fringeI += 1; return &this->fringe[this->fringeI - 1]; } bool BreadthFirstSearch::isEmpty() { return root == NULL || (poppedRoot && fringeI >= fringeLength); } // // Class CacheStrategy // // // Class CacheStrategyNone // bool CacheStrategyNone::isSeen(const Path&) { return false; } void CacheStrategyNone::add(const Path&) { } // // Function search() // vector<const Path*> Search(Graph* graph, FactDB* knownFacts, const word* queryFact, const uint8_t queryFactLength, SearchType* fringe, CacheStrategy* cache, const uint64_t timeout) { // // Setup // // Create a vector for the return value to occupy vector<const Path*> responses; // Create the start state fringe->root = new Path(queryFact, queryFactLength); // I need the memory to not go away // Initialize timer (number of elements popped from the fringe) uint64_t time = 0; const uint32_t tickTime = 10000; std::clock_t startTime = std::clock(); // // Search // while (!fringe->isEmpty() && time < timeout) { // Get the next element from the fringe if (fringe->isEmpty()) { printf("IMPOSSIBLE: the search fringe is empty. This means (a) there are leaf nodes in the graph, and (b) this would have caused a memory leak.\n"); std::exit(1); } const Path* parent = fringe->pop(); // Update time time += 1; // printf("search tick %lu; popped %s\n", time, toString(*graph, *fringe, parent).c_str()); if (time % tickTime == 0) { const uint32_t tickOOM = tickTime < 1000 ? 1 : (tickTime < 1000000 ? 1000 : (tickTime < 1000000000 ? 1000000 : 1) ); printf("[%lu%s / %lu%s search tick]; %lu paths found (%f ms elapsed)\n", time / tickOOM, tickTime < 1000 ? "" : (tickTime < 999999 ? "k" : (tickTime < 999999999 ? "m" : "") ), timeout / tickOOM, tickTime < 1000 ? "" : (tickTime < 999999 ? "k" : (tickTime < 999999999 ? "m" : "") ), responses.size(), 1000.0 * ( std::clock() - startTime ) / ((double) CLOCKS_PER_SEC)); } // -- Check If Valid -- if (knownFacts->contains(parent->fact, parent->factLength)) { printf("> %s\n", toString(*graph, *fringe, parent).c_str()); responses.push_back(parent); } // -- Mutations -- for (int indexToMutate = 0; indexToMutate < parent->factLength; ++indexToMutate) { // for each index to mutate... const vector<edge>& mutations = graph->outgoingEdges(parent->fact[indexToMutate]); // printf(" mutating index %d; %lu children\n", indexToMutate, mutations.size()); for(vector<edge>::const_iterator it = mutations.begin(); it != mutations.end(); ++it) { // for each possible mutation on that index... if (it->type > 1) { continue; } // TODO(gabor) don't only do WordNet jumps // Add the state to the fringe fringe->push(parent, indexToMutate, 1, it->sink, 0, it->type); } } } printf("Search complete; %lu paths found\n", responses.size()); return responses; } <|endoftext|>
<commit_before>/* * State.cpp * Bloom * * Created by Robert Hodgin on 2/7/11. * Copyright 2011 __MyCompanyName__. All rights reserved. * */ #include "State.h" #include "cinder/gl/gl.h" #include "cinder/Rect.h" using std::stringstream; using namespace ci; using namespace ci::app; using namespace std; State::State() { mAlphaChar = ' '; mSelectedNode = NULL; } void State::draw( const Font &font ) { } void State::setAlphaChar( char c ) { std::cout << "State::setAlphaChar " << c << std::endl; mAlphaChar = c; mCallbacksAlphaCharStateChanged.call( this ); } void State::setSelectedNode( Node* node ) { if (node == NULL) { // clear currently selected node and all parents Node *selection = mSelectedNode; while( selection != NULL ) { selection->deselect(); selection = selection->mParentNode; } mSelectedNode = NULL; } else { // clear currently selected node // assuming that the only thing that can be selected is at the same level or higher if( mSelectedNode != NULL && mSelectedNode->mGen >= node->mGen ){ Node *parent = mSelectedNode; while( parent->mGen > node->mGen ){ parent->deselect(); parent = parent->mParentNode; } // TODO: if parent != NULL && parent->mGen == node->mGen // this would happen if we had a track selected but then // we selected a *different* artist // right now that can happen but we should prevent it in // selection code } // ensure that the new selection is selected node->select(); mSelectedNode = node; } // and then spread the good word mCallbacksNodeSelected.call(mSelectedNode); } vector<string> State::getHierarchy() { vector<string> hierarchy; if( mSelectedNode != NULL ){ Node *parent = mSelectedNode; while( parent != NULL ){ hierarchy.push_back( parent->mName ); parent = parent->mParentNode; } } if(mAlphaChar != ' ') { string s; s += mAlphaChar; hierarchy.push_back( s ); } hierarchy.push_back("Kepler"); if (hierarchy.size() > 1) { reverse( hierarchy.begin(), hierarchy.end() ); } return hierarchy; } <commit_msg>deselect track if another track is selected<commit_after>/* * State.cpp * Bloom * * Created by Robert Hodgin on 2/7/11. * Copyright 2011 __MyCompanyName__. All rights reserved. * */ #include "State.h" #include "cinder/gl/gl.h" #include "cinder/Rect.h" using std::stringstream; using namespace ci; using namespace ci::app; using namespace std; State::State() { mAlphaChar = ' '; mSelectedNode = NULL; } void State::draw( const Font &font ) { } void State::setAlphaChar( char c ) { std::cout << "State::setAlphaChar " << c << std::endl; mAlphaChar = c; mCallbacksAlphaCharStateChanged.call( this ); } void State::setSelectedNode( Node* node ) { if (node == NULL) { // clear currently selected node and all parents Node *selection = mSelectedNode; while( selection != NULL ) { selection->deselect(); selection = selection->mParentNode; } mSelectedNode = NULL; } else { // clear currently selected node // assuming that the only thing that can be selected is at the same level or higher if( mSelectedNode != NULL && mSelectedNode->mGen >= node->mGen ){ Node *parent = mSelectedNode; while( parent != NULL && parent->mGen >= node->mGen ){ parent->deselect(); parent = parent->mParentNode; } // TODO: if parent != NULL && parent->mGen == node->mGen // this would happen if we had a track selected but then // we selected a *different* artist // right now that can happen but we should prevent it in // selection code } // ensure that the new selection is selected node->select(); mSelectedNode = node; } // and then spread the good word mCallbacksNodeSelected.call(mSelectedNode); } vector<string> State::getHierarchy() { vector<string> hierarchy; if( mSelectedNode != NULL ){ Node *parent = mSelectedNode; while( parent != NULL ){ hierarchy.push_back( parent->mName ); parent = parent->mParentNode; } } if(mAlphaChar != ' ') { string s; s += mAlphaChar; hierarchy.push_back( s ); } hierarchy.push_back("Kepler"); if (hierarchy.size() > 1) { reverse( hierarchy.begin(), hierarchy.end() ); } return hierarchy; } <|endoftext|>
<commit_before>#include "persistence.h" PersistentHomology::PersistentHomology(Filtration* _filtration, bool _retainGenerators) { filtration = _filtration; max_d = filtration->maxD(); if( filtration->filtration_size() == 0 ) { // build filtration ComputationTimer filtration_timer("filtration computation time"); filtration_timer.start(); filtration->build_filtration(); filtration_timer.end(); filtration_timer.dump_time(); int filtration_size = filtration->filtration_size(); std::cout << "total number of simplices: " << filtration_size << std::endl; } } PersistentHomology::~PersistentHomology() { } bool PersistentHomology::compute_matrix(std::vector<PHCycle> &reduction) { int filtration_size = filtration->filtration_size(); // construct mapping between simplices and their identifiers -> only necessary for identifying simplex faces std::map<std::string,int> simplex_mapping; for(int i = 0; i < filtration_size; i++) simplex_mapping[filtration->get_simplex(i).unique_unoriented_id()] = i+1; // initialize reduction to boundaries - just a vector of lists reduction.clear(); reduction.resize(filtration_size+1); // initialize chains to identities std::vector<PHCycle> chains(filtration_size+1); // reserve 1st entry as dummy simplex, in line with reduced persistence reduction[0] = PHCycle(); chains[0] = PHCycle(); chains[0].push_back(0); // for each simplex, take its boundary and assign those simplices to its list for(int i = 0; i < filtration_size; i++) { int idx = i+1; reduction[idx] = PHCycle(); chains[idx] = PHCycle(); chains[idx].push_back(idx); Simplex simplex = filtration->get_simplex(i); // if 0-simplex, then reserve face as dummy simplex if(simplex.dim()==0) { reduction[idx].push_back(0); continue; } std::vector<Simplex> faces = simplex.faces(); for(int f = 0; f < faces.size(); f++) { Simplex next_face = faces[f]; int face_id = simplex_mapping[next_face.unique_unoriented_id()]; reduction[idx].push_back(face_id); } // sort list, so we can efficiently add cycles and inspect death cycles reduction[idx].sort(); } simplex_mapping.clear(); std::cout << "doing the pairing..." << std::endl; ComputationTimer persistence_timer("persistence computation time"); persistence_timer.start(); // initialize death cycle reference - nothing there yet, so just give it all -1 std::vector<int> death_cycle_ref(filtration_size+1); for(int i = 0; i < filtration_size+1; i++) death_cycle_ref[i] = -1; // perform pairing - but do so in decreasing simplex dimension //for(int d = max_d; d >= 0; d--) { for(int d = 0; d <= max_d; d++) { for(int i = 0; i < filtration_size; i++) { if(filtration->get_simplex(i).dim() != d) continue; int idx = i+1; double simplex_distance = filtration->get_simplex(i).get_simplex_distance(); // until we are either definitively a birth cycle or a death cycle ... int low_i = reduction[idx].back(); int num_chains_added = 0; while(reduction[idx].size() > 0 && death_cycle_ref[low_i] != -1) { num_chains_added++; // add the prior death cycle to us int death_cycle_ind = death_cycle_ref[low_i]; PHCycle::iterator our_cycle_iter = reduction[idx].begin(), added_cycle_iter = reduction[death_cycle_ind].begin(); while(added_cycle_iter != reduction[death_cycle_ind].end()) { if(our_cycle_iter == reduction[idx].end()) { reduction[idx].push_back(*added_cycle_iter); ++added_cycle_iter; continue; } int sigma_1 = *our_cycle_iter, sigma_2 = *added_cycle_iter; if(sigma_1 == sigma_2) { our_cycle_iter = reduction[idx].erase(our_cycle_iter); ++added_cycle_iter; } else if(sigma_1 < sigma_2) ++our_cycle_iter; else { reduction[idx].insert(our_cycle_iter, sigma_2); ++added_cycle_iter; } } //if(retain_generators && d != max_d) //chains[idx].push_back(death_cycle_ind); low_i = reduction[idx].back(); } // if we are a death cycle then add us to the list, add as persistence pairings if(reduction[idx].size() > 0) { death_cycle_ref[low_i] = idx; // kill cycle at low_i, since it represents a birth reduction[low_i] = PHCycle(); //if(low_i > 0) //persistence_pairing.push_back(std::pair<int,int>(low_i-1,idx-1)); } } } persistence_timer.end(); persistence_timer.dump_time(); return true; } PersistenceDiagram *PersistentHomology::compute_persistence(std::vector<PHCycle> &reduction) { int filtration_size = filtration->filtration_size(); std::vector< std::pair<int,int> > persistence_pairing; for(int d = 0; d <= max_d; d++) { for(int i = 0; i < filtration_size; i++) { if(filtration->get_simplex(i).dim() != d) continue; int idx = i+1; // until we are either definitively a birth cycle or a death cycle ... int low_i = reduction[idx].back(); // if we are a death cycle then add us to the list, add as persistence pairings if(reduction[idx].size() > 0) { if(low_i > 0) persistence_pairing.push_back(std::pair<int,int>(low_i-1,idx-1)); } } } std::vector<PersistentPair> persistent_pairs; for(int i = 0; i < persistence_pairing.size(); i++) { std::pair<int,int> pairing = persistence_pairing[i]; Simplex birth_simplex = filtration->get_simplex(pairing.first), death_simplex = filtration->get_simplex(pairing.second); if(death_simplex.get_simplex_distance() == birth_simplex.get_simplex_distance()) continue; PersistentPair persistent_pair(birth_simplex.dim(), birth_simplex.get_simplex_distance(), death_simplex.get_simplex_distance()); persistent_pairs.push_back(persistent_pair); } PersistenceDiagram *pd = new PersistenceDiagram(persistent_pairs); return pd; } <commit_msg>don't need to order by dimension<commit_after>#include "persistence.h" PersistentHomology::PersistentHomology(Filtration* _filtration, bool _retainGenerators) { filtration = _filtration; max_d = filtration->maxD(); if( filtration->filtration_size() == 0 ) { // build filtration ComputationTimer filtration_timer("filtration computation time"); filtration_timer.start(); filtration->build_filtration(); filtration_timer.end(); filtration_timer.dump_time(); int filtration_size = filtration->filtration_size(); std::cout << "total number of simplices: " << filtration_size << std::endl; } } PersistentHomology::~PersistentHomology() { } bool PersistentHomology::compute_matrix(std::vector<PHCycle> &reduction) { int filtration_size = filtration->filtration_size(); // construct mapping between simplices and their identifiers -> only necessary for identifying simplex faces std::map<std::string,int> simplex_mapping; for(int i = 0; i < filtration_size; i++) simplex_mapping[filtration->get_simplex(i).unique_unoriented_id()] = i+1; // initialize reduction to boundaries - just a vector of lists reduction.clear(); reduction.resize(filtration_size+1); // initialize chains to identities std::vector<PHCycle> chains(filtration_size+1); // reserve 1st entry as dummy simplex, in line with reduced persistence reduction[0] = PHCycle(); chains[0] = PHCycle(); chains[0].push_back(0); // for each simplex, take its boundary and assign those simplices to its list for(int i = 0; i < filtration_size; i++) { int idx = i+1; reduction[idx] = PHCycle(); chains[idx] = PHCycle(); chains[idx].push_back(idx); Simplex simplex = filtration->get_simplex(i); // if 0-simplex, then reserve face as dummy simplex if(simplex.dim()==0) { reduction[idx].push_back(0); continue; } std::vector<Simplex> faces = simplex.faces(); for(int f = 0; f < faces.size(); f++) { Simplex next_face = faces[f]; int face_id = simplex_mapping[next_face.unique_unoriented_id()]; reduction[idx].push_back(face_id); } // sort list, so we can efficiently add cycles and inspect death cycles reduction[idx].sort(); } simplex_mapping.clear(); std::cout << "doing the pairing..." << std::endl; ComputationTimer persistence_timer("persistence computation time"); persistence_timer.start(); // initialize death cycle reference - nothing there yet, so just give it all -1 std::vector<int> death_cycle_ref(filtration_size+1); for(int i = 0; i < filtration_size+1; i++) death_cycle_ref[i] = -1; // perform reduction for(int i = 0; i < filtration_size; i++) { int idx = i+1; double simplex_distance = filtration->get_simplex(i).get_simplex_distance(); // until we are either definitively a birth cycle or a death cycle ... int low_i = reduction[idx].back(); int num_chains_added = 0; while(reduction[idx].size() > 0 && death_cycle_ref[low_i] != -1) { num_chains_added++; // add the prior death cycle to us int death_cycle_ind = death_cycle_ref[low_i]; PHCycle::iterator our_cycle_iter = reduction[idx].begin(), added_cycle_iter = reduction[death_cycle_ind].begin(); while(added_cycle_iter != reduction[death_cycle_ind].end()) { if(our_cycle_iter == reduction[idx].end()) { reduction[idx].push_back(*added_cycle_iter); ++added_cycle_iter; continue; } int sigma_1 = *our_cycle_iter, sigma_2 = *added_cycle_iter; if(sigma_1 == sigma_2) { our_cycle_iter = reduction[idx].erase(our_cycle_iter); ++added_cycle_iter; } else if(sigma_1 < sigma_2) ++our_cycle_iter; else { reduction[idx].insert(our_cycle_iter, sigma_2); ++added_cycle_iter; } } //if(retain_generators && d != max_d) //chains[idx].push_back(death_cycle_ind); low_i = reduction[idx].back(); } // if we are a death cycle then add us to the list, add as persistence pairings if(reduction[idx].size() > 0) { death_cycle_ref[low_i] = idx; // kill cycle at low_i, since it represents a birth reduction[low_i] = PHCycle(); } } persistence_timer.end(); persistence_timer.dump_time(); return true; } PersistenceDiagram *PersistentHomology::compute_persistence(std::vector<PHCycle> &reduction) { int filtration_size = filtration->filtration_size(); std::vector< std::pair<int,int> > persistence_pairing; for(int i = 0; i < filtration_size; i++) { int idx = i+1; // until we are either definitively a birth cycle or a death cycle ... int low_i = reduction[idx].back(); // if we are a death cycle then add us to the list, add as persistence pairings if(reduction[idx].size() > 0) { if(low_i > 0) persistence_pairing.push_back(std::pair<int,int>(low_i-1,idx-1)); } } std::vector<PersistentPair> persistent_pairs; for(int i = 0; i < persistence_pairing.size(); i++) { std::pair<int,int> pairing = persistence_pairing[i]; Simplex birth_simplex = filtration->get_simplex(pairing.first), death_simplex = filtration->get_simplex(pairing.second); if(death_simplex.get_simplex_distance() == birth_simplex.get_simplex_distance()) continue; PersistentPair persistent_pair(birth_simplex.dim(), birth_simplex.get_simplex_distance(), death_simplex.get_simplex_distance()); persistent_pairs.push_back(persistent_pair); } PersistenceDiagram *pd = new PersistenceDiagram(persistent_pairs); return pd; } <|endoftext|>
<commit_before>#include <MEII/MEII.hpp> #include <Mahi/Com.hpp> #include <Mahi/Util.hpp> #include <Mahi/Daq.hpp> #include <Mahi/Robo.hpp> #include <Mahi/Com.hpp> #include <vector> using namespace mahi::util; using namespace mahi::daq; using namespace mahi::robo; using namespace mahi::com; using namespace meii; enum state { to_neutral_0, // 0 to_bottom_elbow, // 1 to_top_elbow, // 2 to_neutral_1, // 3 to_top_wrist, // 4 wrist_circle, // 5 to_neutral_2 // 6 }; // create global stop variable CTRL-C handler function ctrl_bool stop(false); bool handler(CtrlEvent event) { stop = true; return true; } void to_state(state& current_state_, const state next_state_, WayPoint current_position_, WayPoint new_position_, Time traj_length_, MinimumJerk& mj_, Clock& ref_traj_clock_) { current_position_.set_time(seconds(0)); new_position_.set_time(traj_length_); mj_.set_endpoints(current_position_, new_position_); if (!mj_.trajectory().validate()) { LOG(Warning) << "Minimum Jerk trajectory invalid."; stop = true; } current_state_ = next_state_; ref_traj_clock_.restart(); } int main(int argc, char* argv[]) { // register ctrl-c handler register_ctrl_handler(handler); // make options Options options("ex_pos_control_nathan.exe", "Nathan's Position Control Demo"); options.add_options() ("c,calibrate", "Calibrates the MAHI Exo-II") ("n,no_torque", "trajectories are generated, but not torque provided") ("v,virtual", "example is virtual and will communicate with the unity sim") ("h,help", "Prints this help message"); auto result = options.parse(argc, argv); // if -h, print the help option if (result.count("help") > 0) { print_var(options.help()); return 0; } // enable Windows realtime enable_realtime(); ///////////////////////////////// // construct and config MEII // ///////////////////////////////// std::shared_ptr<MahiExoII> meii = nullptr; std::shared_ptr<Q8Usb> q8 = nullptr; if(result.count("virtual") > 0){ MeiiConfigurationVirtual config_vr; meii = std::make_shared<MahiExoIIVirtual>(config_vr); } else{ q8 = std::make_shared<Q8Usb>(); q8->open(); std::vector<TTL> idle_values(8,TTL_HIGH); q8->DO.enable_values.set({0,1,2,3,4,5,6,7},idle_values); q8->DO.disable_values.set({0,1,2,3,4,5,6,7},idle_values); q8->DO.expire_values.write({0,1,2,3,4,5,6,7},idle_values); MeiiConfigurationHardware config_hw(*q8); meii = std::make_shared<MahiExoIIHardware>(config_hw); } Time Ts = milliseconds(1); // sample period for DAQ //////////////////////////////// ////////////////////////////////////////////// // create MahiExoII and bind Q8 channels to it ////////////////////////////////////////////// bool rps_is_init = false; ////////////////////////////////////////////// // calibrate - manually zero the encoders (right arm supinated) if (result.count("calibrate") > 0) { meii->calibrate(stop); LOG(Info) << "MAHI Exo-II encoders calibrated."; return 0; } // make MelShares MelShare ms_pos("ms_pos"); MelShare ms_vel("ms_vel"); MelShare ms_trq("ms_trq"); MelShare ms_ref("ms_ref"); // create ranges for saturating trajectories for safety MIN MAX std::vector<std::vector<double>> setpoint_rad_ranges = {{-90 * DEG2RAD, 0 * DEG2RAD}, {-90 * DEG2RAD, 90 * DEG2RAD}, {-15 * DEG2RAD, 15 * DEG2RAD}, {-15 * DEG2RAD, 15 * DEG2RAD}, {0.08, 0.115}}; // state 0 // state 1 // state 2 // state 3 // state 4 // state 5 // state 6 std::vector<Time> state_times = {seconds(2.0), seconds(2.0), seconds(4.0), seconds(2.0), seconds(1.0), seconds(4.0), seconds(1.0)}; // setup trajectories double t = 0; Time mj_Ts = milliseconds(50); std::vector<double> ref; // waypoints Elbow F/E Forearm P/S Wrist F/E Wrist R/U LastDoF WayPoint neutral_point = WayPoint(Time::Zero, {-35 * DEG2RAD, 00 * DEG2RAD, 00 * DEG2RAD, 00 * DEG2RAD, 0.11}); WayPoint bottom_elbow = WayPoint(Time::Zero, {-65 * DEG2RAD, 30 * DEG2RAD, 00 * DEG2RAD, 00 * DEG2RAD, 0.11}); WayPoint top_elbow = WayPoint(Time::Zero, { -5 * DEG2RAD, -30 * DEG2RAD, 00 * DEG2RAD, 00 * DEG2RAD, 0.11}); WayPoint top_wrist = WayPoint(Time::Zero, {-35 * DEG2RAD, 00 * DEG2RAD, 00 * DEG2RAD, 15 * DEG2RAD, 0.11}); // construct timer in hybrid mode to avoid using 100% CPU Timer timer(Ts, Timer::Hybrid); timer.set_acceptable_miss_rate(0.05); // construct clock for regulating keypress Clock keypress_refract_clock; Time keypress_refract_time = seconds(0.5); std::vector<std::string> dof_str = {"ElbowFE", "WristPS", "WristFE", "WristRU"}; //////////////////////////////////////////////// //////////// State Manager Setup /////////////// //////////////////////////////////////////////// state current_state = to_neutral_0; WayPoint current_position; WayPoint new_position; Time traj_length; WayPoint dummy_waypoint = WayPoint(Time::Zero, {-35 * DEG2RAD, 00 * DEG2RAD, 00 * DEG2RAD, 00 * DEG2RAD, 0.09}); MinimumJerk mj(mj_Ts, dummy_waypoint, neutral_point.set_time(state_times[to_neutral_0])); std::vector<double> traj_max_diff = { 50 * DEG2RAD, 50 * DEG2RAD, 35 * DEG2RAD, 35 * DEG2RAD, 0.1 }; mj.set_trajectory_params(Trajectory::Interp::Linear, traj_max_diff); Clock ref_traj_clock; std::vector<double> aj_positions(5,0.0); std::vector<double> aj_velocities(5,0.0); std::vector<double> command_torques(5,0.0); std::vector<double> rps_command_torques(5,0.0); ref_traj_clock.restart(); // enable DAQ and exo meii->daq_enable(); meii->enable(); meii->daq_watchdog_start(); // trajectory following LOG(Info) << "Starting Movement."; //initialize kinematics meii->daq_read_all(); meii->update_kinematics(); WayPoint start_pos(Time::Zero, meii->get_anatomical_joint_positions()); mj.set_endpoints(start_pos, neutral_point.set_time(state_times[to_neutral_0])); while (!stop) { // update all DAQ input channels meii->daq_read_all(); // update MahiExoII kinematics meii->update_kinematics(); if (current_state != wrist_circle) { // update reference from trajectory ref = mj.trajectory().at_time(ref_traj_clock.get_elapsed_time()); } else { ref[0] = neutral_point.get_pos()[0]; ref[1] = neutral_point.get_pos()[1]; ref[2] = 15.0 * DEG2RAD * sin(2.0 * PI * ref_traj_clock.get_elapsed_time() / state_times[wrist_circle]); ref[3] = 15.0 * DEG2RAD * cos(2.0 * PI * ref_traj_clock.get_elapsed_time() / state_times[wrist_circle]); ref[4] = neutral_point.get_pos()[4]; } // constrain trajectory to be within range for (std::size_t i = 0; i < meii->n_aj; ++i) { ref[i] = clamp(ref[i], setpoint_rad_ranges[i][0], setpoint_rad_ranges[i][1]); } // calculate anatomical command torques if (result.count("no_torque") > 0){ command_torques = {0.0, 0.0, 0.0, 0.0, 0.0}; meii->set_anatomical_raw_joint_torques(command_torques); } else{ command_torques = meii->set_anat_pos_ctrl_torques(ref); } // if enough time has passed, continue to the next state. See to_state function at top of file for details if (ref_traj_clock.get_elapsed_time() > state_times[current_state]) { switch (current_state) { case to_neutral_0: to_state(current_state, to_bottom_elbow, neutral_point, bottom_elbow, state_times[to_bottom_elbow], mj, ref_traj_clock); break; case to_bottom_elbow: to_state(current_state, to_top_elbow, bottom_elbow, top_elbow, state_times[to_top_elbow], mj, ref_traj_clock); break; case to_top_elbow: to_state(current_state, to_neutral_1, top_elbow, neutral_point, state_times[to_neutral_1], mj, ref_traj_clock); break; case to_neutral_1: to_state(current_state, to_top_wrist, neutral_point, top_wrist, state_times[to_top_wrist], mj, ref_traj_clock); break; case to_top_wrist: to_state(current_state, wrist_circle, top_wrist, top_wrist, state_times[wrist_circle], mj, ref_traj_clock); break; case wrist_circle: to_state(current_state, to_neutral_2, top_wrist, neutral_point, state_times[to_neutral_2], mj, ref_traj_clock); break; case to_neutral_2: stop = true; break; } } // update all DAQ output channels meii->daq_write_all(); // kick watchdog if (!meii->daq_watchdog_kick() || meii->any_limit_exceeded()) { stop = true; } ms_ref.write_data(meii->get_robot_joint_positions()); ms_pos.write_data(meii->get_robot_joint_velocities()); // wait for remainder of sample period t = timer.wait().as_seconds(); } meii->disable(); meii->daq_disable(); // delete meii; disable_realtime(); // clear console buffer while (get_key_nb() != 0); print("here"); return 0; }<commit_msg>updating virtual_rom_demo so that slop position doesnt make the exo hit hardstops during movement<commit_after>#include <MEII/MEII.hpp> #include <Mahi/Com.hpp> #include <Mahi/Util.hpp> #include <Mahi/Daq.hpp> #include <Mahi/Robo.hpp> #include <Mahi/Com.hpp> #include <vector> using namespace mahi::util; using namespace mahi::daq; using namespace mahi::robo; using namespace mahi::com; using namespace meii; enum state { to_neutral_0, // 0 to_bottom_elbow, // 1 to_top_elbow, // 2 to_neutral_1, // 3 to_top_wrist, // 4 wrist_circle, // 5 to_neutral_2 // 6 }; // create global stop variable CTRL-C handler function ctrl_bool stop(false); bool handler(CtrlEvent event) { stop = true; return true; } void to_state(state& current_state_, const state next_state_, WayPoint current_position_, WayPoint new_position_, Time traj_length_, MinimumJerk& mj_, Clock& ref_traj_clock_) { current_position_.set_time(seconds(0)); new_position_.set_time(traj_length_); mj_.set_endpoints(current_position_, new_position_); if (!mj_.trajectory().validate()) { LOG(Warning) << "Minimum Jerk trajectory invalid."; stop = true; } current_state_ = next_state_; ref_traj_clock_.restart(); } int main(int argc, char* argv[]) { // register ctrl-c handler register_ctrl_handler(handler); // make options Options options("ex_pos_control_nathan.exe", "Nathan's Position Control Demo"); options.add_options() ("c,calibrate", "Calibrates the MAHI Exo-II") ("n,no_torque", "trajectories are generated, but not torque provided") ("v,virtual", "example is virtual and will communicate with the unity sim") ("h,help", "Prints this help message"); auto result = options.parse(argc, argv); // if -h, print the help option if (result.count("help") > 0) { print_var(options.help()); return 0; } // enable Windows realtime enable_realtime(); ///////////////////////////////// // construct and config MEII // ///////////////////////////////// std::shared_ptr<MahiExoII> meii = nullptr; std::shared_ptr<Q8Usb> q8 = nullptr; if(result.count("virtual") > 0){ MeiiConfigurationVirtual config_vr; meii = std::make_shared<MahiExoIIVirtual>(config_vr); } else{ q8 = std::make_shared<Q8Usb>(); q8->open(); std::vector<TTL> idle_values(8,TTL_HIGH); q8->DO.enable_values.set({0,1,2,3,4,5,6,7},idle_values); q8->DO.disable_values.set({0,1,2,3,4,5,6,7},idle_values); q8->DO.expire_values.write({0,1,2,3,4,5,6,7},idle_values); MeiiConfigurationHardware config_hw(*q8); meii = std::make_shared<MahiExoIIHardware>(config_hw); } Time Ts = milliseconds(1); // sample period for DAQ //////////////////////////////// ////////////////////////////////////////////// // create MahiExoII and bind Q8 channels to it ////////////////////////////////////////////// bool rps_is_init = false; ////////////////////////////////////////////// // calibrate - manually zero the encoders (right arm supinated) if (result.count("calibrate") > 0) { meii->calibrate(stop); LOG(Info) << "MAHI Exo-II encoders calibrated."; return 0; } // make MelShares MelShare ms_pos("ms_pos"); MelShare ms_vel("ms_vel"); MelShare ms_trq("ms_trq"); MelShare ms_ref("ms_ref"); // create ranges for saturating trajectories for safety MIN MAX std::vector<std::vector<double>> setpoint_rad_ranges = {{-90 * DEG2RAD, 0 * DEG2RAD}, {-90 * DEG2RAD, 90 * DEG2RAD}, {-15 * DEG2RAD, 15 * DEG2RAD}, {-15 * DEG2RAD, 15 * DEG2RAD}, {0.08, 0.115}}; // state 0 // state 1 // state 2 // state 3 // state 4 // state 5 // state 6 std::vector<Time> state_times = {seconds(2.0), seconds(2.0), seconds(4.0), seconds(2.0), seconds(1.0), seconds(4.0), seconds(1.0)}; // setup trajectories double t = 0; Time mj_Ts = milliseconds(50); std::vector<double> ref; // waypoints Elbow F/E Forearm P/S Wrist F/E Wrist R/U LastDoF WayPoint neutral_point = WayPoint(Time::Zero, {-35 * DEG2RAD, 00 * DEG2RAD, 00 * DEG2RAD, 00 * DEG2RAD, 0.10}); WayPoint bottom_elbow = WayPoint(Time::Zero, {-65 * DEG2RAD, 30 * DEG2RAD, 00 * DEG2RAD, 00 * DEG2RAD, 0.10}); WayPoint top_elbow = WayPoint(Time::Zero, { -5 * DEG2RAD, -30 * DEG2RAD, 00 * DEG2RAD, 00 * DEG2RAD, 0.10}); WayPoint top_wrist = WayPoint(Time::Zero, {-35 * DEG2RAD, 00 * DEG2RAD, 00 * DEG2RAD, 15 * DEG2RAD, 0.10}); // construct timer in hybrid mode to avoid using 100% CPU Timer timer(Ts, Timer::Hybrid); timer.set_acceptable_miss_rate(0.05); // construct clock for regulating keypress Clock keypress_refract_clock; Time keypress_refract_time = seconds(0.5); std::vector<std::string> dof_str = {"ElbowFE", "WristPS", "WristFE", "WristRU"}; //////////////////////////////////////////////// //////////// State Manager Setup /////////////// //////////////////////////////////////////////// state current_state = to_neutral_0; WayPoint current_position; WayPoint new_position; Time traj_length; WayPoint dummy_waypoint = WayPoint(Time::Zero, {-35 * DEG2RAD, 00 * DEG2RAD, 00 * DEG2RAD, 00 * DEG2RAD, 0.09}); MinimumJerk mj(mj_Ts, dummy_waypoint, neutral_point.set_time(state_times[to_neutral_0])); std::vector<double> traj_max_diff = { 50 * DEG2RAD, 50 * DEG2RAD, 35 * DEG2RAD, 35 * DEG2RAD, 0.1 }; mj.set_trajectory_params(Trajectory::Interp::Linear, traj_max_diff); Clock ref_traj_clock; std::vector<double> aj_positions(5,0.0); std::vector<double> aj_velocities(5,0.0); std::vector<double> command_torques(5,0.0); std::vector<double> rps_command_torques(5,0.0); ref_traj_clock.restart(); // enable DAQ and exo meii->daq_enable(); meii->enable(); meii->daq_watchdog_start(); // trajectory following LOG(Info) << "Starting Movement."; //initialize kinematics meii->daq_read_all(); meii->update_kinematics(); WayPoint start_pos(Time::Zero, meii->get_anatomical_joint_positions()); mj.set_endpoints(start_pos, neutral_point.set_time(state_times[to_neutral_0])); while (!stop) { // update all DAQ input channels meii->daq_read_all(); // update MahiExoII kinematics meii->update_kinematics(); if (current_state != wrist_circle) { // update reference from trajectory ref = mj.trajectory().at_time(ref_traj_clock.get_elapsed_time()); } else { ref[0] = neutral_point.get_pos()[0]; ref[1] = neutral_point.get_pos()[1]; ref[2] = 15.0 * DEG2RAD * sin(2.0 * PI * ref_traj_clock.get_elapsed_time() / state_times[wrist_circle]); ref[3] = 15.0 * DEG2RAD * cos(2.0 * PI * ref_traj_clock.get_elapsed_time() / state_times[wrist_circle]); ref[4] = neutral_point.get_pos()[4]; } // constrain trajectory to be within range for (std::size_t i = 0; i < meii->n_aj; ++i) { ref[i] = clamp(ref[i], setpoint_rad_ranges[i][0], setpoint_rad_ranges[i][1]); } // calculate anatomical command torques if (result.count("no_torque") > 0){ command_torques = {0.0, 0.0, 0.0, 0.0, 0.0}; meii->set_anatomical_raw_joint_torques(command_torques); } else{ command_torques = meii->set_anat_pos_ctrl_torques(ref); } // if enough time has passed, continue to the next state. See to_state function at top of file for details if (ref_traj_clock.get_elapsed_time() > state_times[current_state]) { switch (current_state) { case to_neutral_0: to_state(current_state, to_bottom_elbow, neutral_point, bottom_elbow, state_times[to_bottom_elbow], mj, ref_traj_clock); break; case to_bottom_elbow: to_state(current_state, to_top_elbow, bottom_elbow, top_elbow, state_times[to_top_elbow], mj, ref_traj_clock); break; case to_top_elbow: to_state(current_state, to_neutral_1, top_elbow, neutral_point, state_times[to_neutral_1], mj, ref_traj_clock); break; case to_neutral_1: to_state(current_state, to_top_wrist, neutral_point, top_wrist, state_times[to_top_wrist], mj, ref_traj_clock); break; case to_top_wrist: to_state(current_state, wrist_circle, top_wrist, top_wrist, state_times[wrist_circle], mj, ref_traj_clock); break; case wrist_circle: to_state(current_state, to_neutral_2, top_wrist, neutral_point, state_times[to_neutral_2], mj, ref_traj_clock); break; case to_neutral_2: stop = true; break; } } // update all DAQ output channels meii->daq_write_all(); // kick watchdog if (!meii->daq_watchdog_kick() || meii->any_limit_exceeded()) { stop = true; } ms_ref.write_data(meii->get_robot_joint_positions()); ms_pos.write_data(meii->get_robot_joint_velocities()); // wait for remainder of sample period t = timer.wait().as_seconds(); } meii->daq_disable(); meii->disable(); // delete meii; disable_realtime(); // clear console buffer while (get_key_nb() != 0); print("here"); return 0; }<|endoftext|>
<commit_before>//======================================================================= // Copyright (c) 2014-2015 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include "catch.hpp" #include "template_test.hpp" #include "etl/etl.hpp" #include "etl/stop.hpp" TEMPLATE_TEST_CASE_2( "stop/fast_vector_1", "stop<unary<fast_vec>>", Z, float, double ) { using mat_type = etl::fast_vector<Z, 4>; mat_type test_vector(3.3); auto r = s(log(test_vector)); using type = std::remove_reference_t<std::remove_cv_t<decltype(r)>>; REQUIRE(r.size() == 4); REQUIRE(etl::etl_traits<type>::size(r) == 4); REQUIRE(etl::size(r) == 4); REQUIRE(etl::etl_traits<type>::is_value); REQUIRE(etl::etl_traits<type>::is_fast); constexpr const auto size_1 = etl::etl_traits<type>::size(); REQUIRE(size_1 == 4); constexpr const auto size_2 = etl::size(r); REQUIRE(size_2 == 4); for(std::size_t i = 0; i < r.size(); ++i){ REQUIRE(r[i] == std::log(Z(3.3))); REQUIRE(r(i) == std::log(Z(3.3))); } } TEMPLATE_TEST_CASE_2( "stop/fast_matrix_1", "stop<unary<fast_mat>>", Z, float, double ) { using mat_type = etl::fast_matrix<Z, 3, 2>; mat_type test_matrix(3.3); auto r = s(log(test_matrix)); using type = std::remove_reference_t<std::remove_cv_t<decltype(r)>>; REQUIRE(r.size() == 6); REQUIRE(etl::etl_traits<type>::size(r) == 6); REQUIRE(etl::size(r) == 6); REQUIRE(etl::rows(r) == 3); REQUIRE(etl::columns(r) == 2); REQUIRE(etl::etl_traits<type>::is_value); REQUIRE(etl::etl_traits<type>::is_fast); constexpr const auto size_1 = etl::etl_traits<type>::size(); REQUIRE(size_1 == 6); constexpr const auto size_2 = etl::size(r); constexpr const auto rows_2 = etl::rows(r); constexpr const auto columns_2 = etl::columns(r); REQUIRE(size_2 == 6); REQUIRE(rows_2 == 3); REQUIRE(columns_2 == 2); for(std::size_t i = 0; i < r.size(); ++i){ REQUIRE(r[i] == std::log(Z(3.3))); } } TEMPLATE_TEST_CASE_2( "stop/fast_matrix_2", "stop<binary<fast_mat>>", Z, float, double ) { using mat_type = etl::fast_matrix<Z, 3, 2>; mat_type test_matrix(3.3); auto r = s(test_matrix + test_matrix); using type = std::remove_reference_t<std::remove_cv_t<decltype(r)>>; REQUIRE(r.size() == 6); REQUIRE(etl::etl_traits<type>::size(r) == 6); REQUIRE(etl::size(r) == 6); REQUIRE(etl::rows(r) == 3); REQUIRE(etl::columns(r) == 2); REQUIRE(etl::etl_traits<type>::is_value); REQUIRE(etl::etl_traits<type>::is_fast); constexpr const auto size_1 = etl::etl_traits<type>::size(); REQUIRE(size_1 == 6); constexpr const auto size_2 = size(r); constexpr const auto rows_2 = rows(r); constexpr const auto columns_2 = columns(r); REQUIRE(size_2 == 6); REQUIRE(rows_2 == 3); REQUIRE(columns_2 == 2); for(std::size_t i = 0; i < r.size(); ++i){ REQUIRE(r[i] == Z(6.6)); } } TEMPLATE_TEST_CASE_2( "stop/dyn_vector_1", "stop<unary<dyn_vec>>", Z, float, double ) { using mat_type = etl::dyn_vector<Z>; mat_type test_vector(4, 3.3); auto r = s(log(test_vector)); using type = std::remove_reference_t<std::remove_cv_t<decltype(r)>>; REQUIRE(r.size() == 4); REQUIRE(etl::etl_traits<type>::size(r) == 4); REQUIRE(etl::size(r) == 4); REQUIRE(etl::etl_traits<type>::is_value); REQUIRE(!etl::etl_traits<type>::is_fast); for(std::size_t i = 0; i < r.size(); ++i){ REQUIRE(r[i] == std::log(Z(3.3))); REQUIRE(r(i) == std::log(Z(3.3))); } } TEMPLATE_TEST_CASE_2( "stop/dyn_matrix_1", "stop<unary<dyn_mat>>", Z, float, double ) { using mat_type = etl::dyn_matrix<Z>; mat_type test_matrix(3, 2, 3.3); auto r = s(log(test_matrix)); using type = std::remove_reference_t<std::remove_cv_t<decltype(r)>>; REQUIRE(r.size() == 6); REQUIRE(etl::etl_traits<type>::size(r) == 6); REQUIRE(etl::size(r) == 6); REQUIRE(etl::rows(r) == 3); REQUIRE(etl::columns(r) == 2); REQUIRE(etl::etl_traits<type>::is_value); REQUIRE(!etl::etl_traits<type>::is_fast); for(std::size_t i = 0; i < r.size(); ++i){ REQUIRE(r[i] == std::log(Z(3.3))); } } TEMPLATE_TEST_CASE_2( "stop/dyn_matrix_2", "stop<binary<dyn_mat>>", Z, float, double ) { using mat_type = etl::dyn_matrix<Z>; mat_type test_matrix(3, 2, 3.3); auto r = s(test_matrix + test_matrix); using type = std::remove_reference_t<std::remove_cv_t<decltype(r)>>; REQUIRE(r.size() == 6); REQUIRE(etl::etl_traits<type>::size(r) == 6); REQUIRE(etl::size(r) == 6); REQUIRE(etl::rows(r) == 3); REQUIRE(etl::columns(r) == 2); REQUIRE(etl::etl_traits<type>::is_value); REQUIRE(!etl::etl_traits<type>::is_fast); for(std::size_t i = 0; i < r.size(); ++i){ REQUIRE(r[i] == Z(6.6)); } } <commit_msg>Add some margin to the tests<commit_after>//======================================================================= // Copyright (c) 2014-2015 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include "catch.hpp" #include "template_test.hpp" #include "etl/etl.hpp" #include "etl/stop.hpp" TEMPLATE_TEST_CASE_2( "stop/fast_vector_1", "stop<unary<fast_vec>>", Z, float, double ) { using mat_type = etl::fast_vector<Z, 4>; mat_type test_vector(3.3); auto r = s(log(test_vector)); using type = std::remove_reference_t<std::remove_cv_t<decltype(r)>>; REQUIRE(r.size() == 4); REQUIRE(etl::etl_traits<type>::size(r) == 4); REQUIRE(etl::size(r) == 4); REQUIRE(etl::etl_traits<type>::is_value); REQUIRE(etl::etl_traits<type>::is_fast); constexpr const auto size_1 = etl::etl_traits<type>::size(); REQUIRE(size_1 == 4); constexpr const auto size_2 = etl::size(r); REQUIRE(size_2 == 4); for(std::size_t i = 0; i < r.size(); ++i){ REQUIRE(r[i] == Approx(std::log(Z(3.3)))); REQUIRE(r(i) == Approx(std::log(Z(3.3)))); } } TEMPLATE_TEST_CASE_2( "stop/fast_matrix_1", "stop<unary<fast_mat>>", Z, float, double ) { using mat_type = etl::fast_matrix<Z, 3, 2>; mat_type test_matrix(3.3); auto r = s(log(test_matrix)); using type = std::remove_reference_t<std::remove_cv_t<decltype(r)>>; REQUIRE(r.size() == 6); REQUIRE(etl::etl_traits<type>::size(r) == 6); REQUIRE(etl::size(r) == 6); REQUIRE(etl::rows(r) == 3); REQUIRE(etl::columns(r) == 2); REQUIRE(etl::etl_traits<type>::is_value); REQUIRE(etl::etl_traits<type>::is_fast); constexpr const auto size_1 = etl::etl_traits<type>::size(); REQUIRE(size_1 == 6); constexpr const auto size_2 = etl::size(r); constexpr const auto rows_2 = etl::rows(r); constexpr const auto columns_2 = etl::columns(r); REQUIRE(size_2 == 6); REQUIRE(rows_2 == 3); REQUIRE(columns_2 == 2); for(std::size_t i = 0; i < r.size(); ++i){ REQUIRE(r[i] == Approx(std::log(Z(3.3)))); } } TEMPLATE_TEST_CASE_2( "stop/fast_matrix_2", "stop<binary<fast_mat>>", Z, float, double ) { using mat_type = etl::fast_matrix<Z, 3, 2>; mat_type test_matrix(3.3); auto r = s(test_matrix + test_matrix); using type = std::remove_reference_t<std::remove_cv_t<decltype(r)>>; REQUIRE(r.size() == 6); REQUIRE(etl::etl_traits<type>::size(r) == 6); REQUIRE(etl::size(r) == 6); REQUIRE(etl::rows(r) == 3); REQUIRE(etl::columns(r) == 2); REQUIRE(etl::etl_traits<type>::is_value); REQUIRE(etl::etl_traits<type>::is_fast); constexpr const auto size_1 = etl::etl_traits<type>::size(); REQUIRE(size_1 == 6); constexpr const auto size_2 = size(r); constexpr const auto rows_2 = rows(r); constexpr const auto columns_2 = columns(r); REQUIRE(size_2 == 6); REQUIRE(rows_2 == 3); REQUIRE(columns_2 == 2); for(std::size_t i = 0; i < r.size(); ++i){ REQUIRE(r[i] == Z(6.6)); } } TEMPLATE_TEST_CASE_2( "stop/dyn_vector_1", "stop<unary<dyn_vec>>", Z, float, double ) { using mat_type = etl::dyn_vector<Z>; mat_type test_vector(4, 3.3); auto r = s(log(test_vector)); using type = std::remove_reference_t<std::remove_cv_t<decltype(r)>>; REQUIRE(r.size() == 4); REQUIRE(etl::etl_traits<type>::size(r) == 4); REQUIRE(etl::size(r) == 4); REQUIRE(etl::etl_traits<type>::is_value); REQUIRE(!etl::etl_traits<type>::is_fast); for(std::size_t i = 0; i < r.size(); ++i){ REQUIRE(r[i] == Approx(std::log(Z(3.3)))); REQUIRE(r(i) == Approx(std::log(Z(3.3)))); } } TEMPLATE_TEST_CASE_2( "stop/dyn_matrix_1", "stop<unary<dyn_mat>>", Z, float, double ) { using mat_type = etl::dyn_matrix<Z>; mat_type test_matrix(3, 2, 3.3); auto r = s(log(test_matrix)); using type = std::remove_reference_t<std::remove_cv_t<decltype(r)>>; REQUIRE(r.size() == 6); REQUIRE(etl::etl_traits<type>::size(r) == 6); REQUIRE(etl::size(r) == 6); REQUIRE(etl::rows(r) == 3); REQUIRE(etl::columns(r) == 2); REQUIRE(etl::etl_traits<type>::is_value); REQUIRE(!etl::etl_traits<type>::is_fast); for(std::size_t i = 0; i < r.size(); ++i){ REQUIRE(r[i] == Approx(std::log(Z(3.3)))); } } TEMPLATE_TEST_CASE_2( "stop/dyn_matrix_2", "stop<binary<dyn_mat>>", Z, float, double ) { using mat_type = etl::dyn_matrix<Z>; mat_type test_matrix(3, 2, 3.3); auto r = s(test_matrix + test_matrix); using type = std::remove_reference_t<std::remove_cv_t<decltype(r)>>; REQUIRE(r.size() == 6); REQUIRE(etl::etl_traits<type>::size(r) == 6); REQUIRE(etl::size(r) == 6); REQUIRE(etl::rows(r) == 3); REQUIRE(etl::columns(r) == 2); REQUIRE(etl::etl_traits<type>::is_value); REQUIRE(!etl::etl_traits<type>::is_fast); for(std::size_t i = 0; i < r.size(); ++i){ REQUIRE(r[i] == Z(6.6)); } } <|endoftext|>
<commit_before>#define CATCH_CONFIG_MAIN #include <stdlib.h> #include <string.h> #include "catch.hpp" #include <cserial.h> #ifdef _WIN32 #define snprintf _snprintf_s #define sprintf sprintf_s #define strcat strcat_s #endif TEST_CASE("Loopback send/receive", "[tx][rx][loopback]") { struct cserial_port txPort, rxPort; struct cserial_port_conf conf = { conf.baud = 19200, conf.parity = PARITY_NONE, conf.csize = 8, conf.stopbits = 1, }; char *txDev, *rxDev; char tx[32], rx[32]; int txLen; int ret; memset(tx, 0, sizeof(tx)); memset(rx, 0, sizeof(rx)); snprintf(tx, sizeof(tx), "Erich"); /* Get the device file to transmit data out. */ txDev = getenv("CSERIAL_TX"); INFO("transmitting using: " << txDev); REQUIRE(txDev != 0); /* Get the device file to receive data in. */ rxDev = getenv("CSERIAL_RX"); INFO("receiving using: " << rxDev); REQUIRE(rxDev != 0); ret = cserial_open(&txPort, &conf, txDev); INFO("tx cserial_open: " << cserial_strerror(ret)); REQUIRE(ret == 0); INFO("rx cserial_open: " << cserial_strerror(ret)); ret = cserial_open(&rxPort, &conf, rxDev); REQUIRE(ret == 0); txLen = strlen(tx); ret = cserial_write(&txPort, tx, txLen); REQUIRE(ret == txLen); ret = cserial_read(&rxPort, rx, sizeof(rx)); /* We should receive everything we transmitted. */ REQUIRE(ret == txLen); ret = cserial_close(&txPort); ret = cserial_close(&rxPort); REQUIRE(ret == 0); free(txPort.device); free(rxPort.device); } <commit_msg>Fixed bug where closing txPort would not be detected.<commit_after>#define CATCH_CONFIG_MAIN #include <stdlib.h> #include <string.h> #include "catch.hpp" #include <cserial.h> #ifdef _WIN32 #define snprintf _snprintf_s #define sprintf sprintf_s #define strcat strcat_s #endif TEST_CASE("Loopback send/receive", "[tx][rx][loopback]") { struct cserial_port txPort, rxPort; struct cserial_port_conf conf = { conf.baud = 19200, conf.parity = PARITY_NONE, conf.csize = 8, conf.stopbits = 1, }; char *txDev, *rxDev; char tx[32], rx[32]; int txLen; int ret; memset(tx, 0, sizeof(tx)); memset(rx, 0, sizeof(rx)); snprintf(tx, sizeof(tx), "Erich"); /* Get the device file to transmit data out. */ txDev = getenv("CSERIAL_TX"); INFO("transmitting using: " << txDev); REQUIRE(txDev != 0); /* Get the device file to receive data in. */ rxDev = getenv("CSERIAL_RX"); INFO("receiving using: " << rxDev); REQUIRE(rxDev != 0); ret = cserial_open(&txPort, &conf, txDev); INFO("tx cserial_open: " << cserial_strerror(ret)); REQUIRE(ret == 0); INFO("rx cserial_open: " << cserial_strerror(ret)); ret = cserial_open(&rxPort, &conf, rxDev); REQUIRE(ret == 0); txLen = strlen(tx); ret = cserial_write(&txPort, tx, txLen); REQUIRE(ret == txLen); ret = cserial_read(&rxPort, rx, sizeof(rx)); /* We should receive everything we transmitted. */ REQUIRE(ret == txLen); ret = cserial_close(&txPort); REQUIRE(ret == 0); ret = cserial_close(&rxPort); REQUIRE(ret == 0); free(txPort.device); free(rxPort.device); } <|endoftext|>
<commit_before> #include <stdio.h> #include <stdlib.h> #include <iostream> #include "test.h" #include "commands.h" #include "halley.h" #include "DebugServer.h" #include "BayeuxClientIface.h" #include <readline/readline.h> #include <readline/history.h> // Tells which mode we are in - either lua or command mode // ctrl-d switches between the two modes bool inCmdMode = true; // The current stack that will process commands int currStack = -1; // The list of stacks that have been created std::vector<NamedLuaStack *> luaStacks; char *showPrompt(char *inputBuff = NULL) { #ifdef USING_READLINE char prompt[256]; sprintf(prompt, " %s [ CurrStack = %d] >> ", (inCmdMode ? "cmd" : "lua"), currStack); return readline(prompt); #else std::cout << std::endl << (inCmdMode ? " cmd" : " lua"); if (currStack >= 0) { std::cout << " [ CurrStack = " << currStack << " ] >> "; } else { std::cout << " [ CurrStack = None ] >> "; } return fgets(inputBuff, 1024, stdin); #endif } void usage() { puts("\nCommands: \n"); puts(" open <name> - Creates a new lua stack with the given name."); puts(" close <index> - Closes the lua stack at the given index."); puts(" stack <index> - Sets the index-th stack as the 'current' lua stack."); puts(" stacks - Prints the list of stacks currently opened."); puts(" attach <index> - Enables debugging of the index-th lua stack."); puts(" detach <index> - Disables debugging of the index-th lua stack."); puts(" quit - Quites the test harness."); puts(" ----- - Switch between cmd and lua mode - same as Ctrl-D."); puts(""); } // Strips spaces from the front of a string and returns a pointer to the // first non-space char const char *strip_initial_spaces(const char *input) { while (*input && isspace(*input)) input ++; return input; } NamedLuaStack *GetLuaStack(const std::string &name, bool add) { NamedLuaStack *stack = NULL; for (std::vector<NamedLuaStack *>::iterator iter = luaStacks.begin(); stack == NULL && iter != luaStacks.end(); ++iter) { if ((*iter)->name == name) stack = *iter; } if (stack == NULL && add) { stack = new NamedLuaStack(); stack->debugging = false; stack->name = name; stack->pStack = LuaUtils::NewLuaStack(true, true, name.c_str()); stack->pContext = NULL; luaStacks.push_back(stack); } return stack; } // // Available commands: // open <name> - open a new lua stack with the given name // close <index> - closes a given lua stack // stack <index> - Sets the specific stack as the "current" stack // stacks - Print all the lua stacks // load <file> - Run a lua file in the current stack // bool processCmdString(const char *input) { int cmd = 0; if (strncmp(input, "help", 4) == 0) { usage(); } else { for (;cmd < CMD_COUNT;cmd++) { int cmdlen = strlen(CMD_NAMES[cmd]); if (strncmp(input, CMD_NAMES[cmd], cmdlen) == 0) { input += cmdlen; if (*input == 0 || isspace(*input)) { // command found input = strip_initial_spaces(input); break ; } } } if (cmd < CMD_COUNT) { return CMD_FUNCTIONS[cmd](input); } std::cerr << std::endl << "Invalid Command: '" << input << "'" << std::endl << std::endl; usage(); } return true; } bool processLuaString(const char *input) { if (currStack < 0) { fprintf(stderr, "No stacks selected. Create or select a stack.\n"); } else { LuaUtils::RunLuaString(luaStacks[currStack]->pStack, input); } return true; } void switchMode() { inCmdMode = !inCmdMode; printf("\n\nSwitching to %s mode ... Press Ctrl-C to exit...\n\n", inCmdMode ? "cmd" : "lua"); } bool processCommand(char *command) { command = (char *)strip_initial_spaces(command); char *end = command + strlen(command) - 1; while (end > command && (isspace(*end) || *end == '\n' || *end == '\r')) end--; end[1] = 0; bool running = true; if (*command != 0) { if (strncmp("-----", command, 5) == 0) { switchMode(); } else { running = inCmdMode ? processCmdString(command) : processLuaString(command); } } return running; } LUNARPROBE_NS::LunarProbe *GetLPInstance() { class LPIndexModule : public SHttpModule { public: //! Constructor LPIndexModule(SHttpModule *pNext) : SHttpModule(pNext) { } //! Called to handle input data from another module void ProcessInput(SHttpHandlerData * pHandlerData, SHttpHandlerStage * pStage, SBodyPart * pBodyPart) { SHttpRequest *pRequest = pHandlerData->Request(); SHttpResponse *pResponse = pRequest->Response(); SString links = "<p>" "<h2><a href='/ldb/index.html'>Lua Debugger</a></h2>" "<br><h2><a href='/files/'>/games/</a></h2>" ; SString body = "<hr><center>" + links + "</center><hr>"; SBodyPart *part = pResponse->NewBodyPart(); part->SetBody("<html><head><title>Lua Debugger</title></head>"); part->AppendToBody("<body>" + body + "</body></html>"); pStage->OutputToModule(pHandlerData->pConnection, pNextModule, part); pStage->OutputToModule(pHandlerData->pConnection, pNextModule, pResponse->NewBodyPart(SBodyPart::BP_CONTENT_FINISHED, pNextModule)); } }; static LUNARPROBE_NS::BayeuxClientIface clientIface("/ldb"); static LUNARPROBE_NS::HttpDebugServer debugServer(LUA_DEBUG_PORT, &clientIface); static SThread serverThread(&debugServer); SUrlRouter * pUrlRouter = debugServer.GetUrlRouter(); SFileModule * pFileModule = debugServer.GetFileModule(); static LPIndexModule lpIndexModule(debugServer.GetContentModule()); static SFileModule gameFilesModule(debugServer.GetContentModule()); static SContainsUrlMatcher gameFilesUrlMatch("/files/", SContainsUrlMatcher::PREFIX_MATCH, &gameFilesModule); static SContainsUrlMatcher ldbUrlMatch("/ldb/", SContainsUrlMatcher::PREFIX_MATCH, pFileModule); static SContainsUrlMatcher bayeuxUrlMatch("/bayeux/", SContainsUrlMatcher::PREFIX_MATCH, debugServer.GetBayeuxModule()); LUNARPROBE_NS::LunarProbe *lpInstance = LUNARPROBE_NS::LunarProbe::GetInstance(); if (lpInstance->GetClientIface() == NULL) { // set the different modules we need gameFilesModule.AddDocRoot("/files/", "/games/"); pUrlRouter->AddUrlMatch(&gameFilesUrlMatch); pFileModule->AddDocRoot("/ldb/", "shared/libgameengine/luadb/static/"); pUrlRouter->AddUrlMatch(&ldbUrlMatch); pUrlRouter->AddUrlMatch(&bayeuxUrlMatch); pUrlRouter->SetNextModule(&lpIndexModule); lpInstance->SetClientIface(&clientIface); serverThread.Start(); } return lpInstance; } int main(int argc, char *argv[]) { char inputBuff[1024]; char *command; bool running = true; LuaBindings::LUA_SRC_LOCATION = "../lua/"; if (argc > 1) { // see if we can take inputs from some file first before running // the command prompt FILE *fptr = fopen(argv[1], "r"); if (fptr == NULL) { fprintf(stderr, "\nCannot open file: %s\n\n", argv[1]); // TODO: Should we quit here? } else { while ((command = fgets(inputBuff, 1024, fptr)) != NULL) { processCommand(command); } fclose(fptr); } } while (running) { if ((command = showPrompt(inputBuff)) == NULL) { switchMode(); } else { processCommand(command); } } return 0; } <commit_msg>Dir parent listing fixed<commit_after> #include <stdio.h> #include <stdlib.h> #include <iostream> #include "test.h" #include "commands.h" #include "halley.h" #include "DebugServer.h" #include "BayeuxClientIface.h" #include <readline/readline.h> #include <readline/history.h> // Tells which mode we are in - either lua or command mode // ctrl-d switches between the two modes bool inCmdMode = true; // The current stack that will process commands int currStack = -1; // The list of stacks that have been created std::vector<NamedLuaStack *> luaStacks; char *showPrompt(char *inputBuff = NULL) { #ifdef USING_READLINE char prompt[256]; sprintf(prompt, " %s [ CurrStack = %d] >> ", (inCmdMode ? "cmd" : "lua"), currStack); return readline(prompt); #else std::cout << std::endl << (inCmdMode ? " cmd" : " lua"); if (currStack >= 0) { std::cout << " [ CurrStack = " << currStack << " ] >> "; } else { std::cout << " [ CurrStack = None ] >> "; } return fgets(inputBuff, 1024, stdin); #endif } void prog_usage() { puts("\nUsage: options <optional preample files>"); puts(" Options: \n"); puts(" -l | --lua - Specify folder containing the lua files. Default: ./lua"); puts(" -s | --static - Specify folder containing the static files (for http). Default: ./static"); puts(""); } void command_usage() { puts("\nCommands: \n"); puts(" open <name> - Creates a new lua stack with the given name."); puts(" close <index> - Closes the lua stack at the given index."); puts(" stack <index> - Sets the index-th stack as the 'current' lua stack."); puts(" stacks - Prints the list of stacks currently opened."); puts(" attach <index> - Enables debugging of the index-th lua stack."); puts(" detach <index> - Disables debugging of the index-th lua stack."); puts(" quit - Quites the test harness."); puts(" ----- - Switch between cmd and lua mode - same as Ctrl-D."); puts(""); } // Strips spaces from the front of a string and returns a pointer to the // first non-space char const char *strip_initial_spaces(const char *input) { while (*input && isspace(*input)) input ++; return input; } NamedLuaStack *GetLuaStack(const std::string &name, bool add) { NamedLuaStack *stack = NULL; for (std::vector<NamedLuaStack *>::iterator iter = luaStacks.begin(); stack == NULL && iter != luaStacks.end(); ++iter) { if ((*iter)->name == name) stack = *iter; } if (stack == NULL && add) { stack = new NamedLuaStack(); stack->debugging = false; stack->name = name; stack->pStack = LuaUtils::NewLuaStack(true, true, name.c_str()); stack->pContext = NULL; luaStacks.push_back(stack); } return stack; } // // Available commands: // open <name> - open a new lua stack with the given name // close <index> - closes a given lua stack // stack <index> - Sets the specific stack as the "current" stack // stacks - Print all the lua stacks // load <file> - Run a lua file in the current stack // bool processCmdString(const char *input) { int cmd = 0; if (strncmp(input, "help", 4) == 0) { command_usage(); } else { for (;cmd < CMD_COUNT;cmd++) { int cmdlen = strlen(CMD_NAMES[cmd]); if (strncmp(input, CMD_NAMES[cmd], cmdlen) == 0) { input += cmdlen; if (*input == 0 || isspace(*input)) { // command found input = strip_initial_spaces(input); break ; } } } if (cmd < CMD_COUNT) { return CMD_FUNCTIONS[cmd](input); } std::cerr << std::endl << "Invalid Command: '" << input << "'" << std::endl << std::endl; command_usage(); } return true; } bool processLuaString(const char *input) { if (currStack < 0) { fprintf(stderr, "No stacks selected. Create or select a stack.\n"); } else { LuaUtils::RunLuaString(luaStacks[currStack]->pStack, input); } return true; } void switchMode() { inCmdMode = !inCmdMode; printf("\n\nSwitching to %s mode ... Press Ctrl-C to exit...\n\n", inCmdMode ? "cmd" : "lua"); } bool processCommand(char *command) { command = (char *)strip_initial_spaces(command); char *end = command + strlen(command) - 1; while (end > command && (isspace(*end) || *end == '\n' || *end == '\r')) end--; end[1] = 0; bool running = true; if (*command != 0) { if (strncmp("-----", command, 5) == 0) { switchMode(); } else { running = inCmdMode ? processCmdString(command) : processLuaString(command); } } return running; } void InitLunarProbe(const std::string &staticPath) { class LPIndexModule : public SHttpModule { public: //! Constructor LPIndexModule(SHttpModule *pNext) : SHttpModule(pNext) { } //! Called to handle input data from another module void ProcessInput(SHttpHandlerData * pHandlerData, SHttpHandlerStage * pStage, SBodyPart * pBodyPart) { SHttpRequest *pRequest = pHandlerData->Request(); SHttpResponse *pResponse = pRequest->Response(); SString links = "<p>" "<h2><a href='/ldb/index.html'>Lua Debugger</a></h2>" "<br><h2><a href='/files/'>FileSystem</a></h2>" ; SString body = "<hr><center>" + links + "</center><hr>"; SBodyPart *part = pResponse->NewBodyPart(); part->SetBody("<html><head><title>Lua Debugger</title></head>"); part->AppendToBody("<body>" + body + "</body></html>"); pStage->OutputToModule(pHandlerData->pConnection, pNextModule, part); pStage->OutputToModule(pHandlerData->pConnection, pNextModule, pResponse->NewBodyPart(SBodyPart::BP_CONTENT_FINISHED, pNextModule)); } }; static LUNARPROBE_NS::BayeuxClientIface clientIface("/ldb"); static LUNARPROBE_NS::HttpDebugServer debugServer(LUA_DEBUG_PORT, &clientIface); static SThread serverThread(&debugServer); SUrlRouter * pUrlRouter = debugServer.GetUrlRouter(); SFileModule * pFileModule = debugServer.GetFileModule(); static LPIndexModule lpIndexModule(debugServer.GetContentModule()); static SFileModule gameFilesModule(debugServer.GetContentModule()); static SContainsUrlMatcher gameFilesUrlMatch("/files/", SContainsUrlMatcher::PREFIX_MATCH, &gameFilesModule); static SContainsUrlMatcher ldbUrlMatch("/ldb/", SContainsUrlMatcher::PREFIX_MATCH, pFileModule); static SContainsUrlMatcher bayeuxUrlMatch("/bayeux/", SContainsUrlMatcher::PREFIX_MATCH, debugServer.GetBayeuxModule()); LUNARPROBE_NS::LunarProbe *lpInstance = LUNARPROBE_NS::LunarProbe::GetInstance(); if (lpInstance->GetClientIface() == NULL) { // set the different modules we need gameFilesModule.AddDocRoot("/files/", "/home/spanyam/"); pUrlRouter->AddUrlMatch(&gameFilesUrlMatch); pFileModule->AddDocRoot("/ldb/", staticPath); pUrlRouter->AddUrlMatch(&ldbUrlMatch); pUrlRouter->AddUrlMatch(&bayeuxUrlMatch); pUrlRouter->SetNextModule(&lpIndexModule); lpInstance->SetClientIface(&clientIface); serverThread.Start(); } } LUNARPROBE_NS::LunarProbe *GetLPInstance() { return LUNARPROBE_NS::LunarProbe::GetInstance(); } int main(int argc, char *argv[]) { char pathBuff[1024]; char inputBuff[1024]; char *command; const char *luaPath = "./lua"; const char *staticPath = "./static"; bool running = true; int argCounter = 1; for (;argCounter < argc;argCounter++) { if (strcmp(argv[argCounter], "--lua") == 0 || strcmp(argv[argCounter], "-lua") == 0 || strcmp(argv[argCounter], "-l") == 0) { luaPath = argv[++argCounter]; } else if (strcmp(argv[argCounter], "--help") == 0 || strcmp(argv[argCounter], "-help") == 0 || strcmp(argv[argCounter], "-h") == 0) { prog_usage(); return 0; } else if (strcmp(argv[argCounter], "--static") == 0 || strcmp(argv[argCounter], "-static") == 0 || strcmp(argv[argCounter], "-s") == 0) { staticPath = argv[++argCounter]; } else { break ; } } LuaBindings::LUA_SRC_LOCATION = realpath(luaPath, pathBuff); InitLunarProbe(realpath(staticPath, pathBuff)); for (;argCounter < argc;argCounter++) { FILE *fptr = fopen(argv[argCounter], "r"); if (fptr == NULL) { fprintf(stderr, "\nCannot open file: %s\n\n", argv[1]); // TODO: Should we quit here? } else { while ((command = fgets(inputBuff, 1024, fptr)) != NULL) { processCommand(command); } fclose(fptr); } } while (running) { if ((command = showPrompt(inputBuff)) == NULL) { switchMode(); } else { processCommand(command); } } return 0; } <|endoftext|>
<commit_before>#include "gtest/gtest.h" #include "tools/leosac.hpp" TEST(sample_test_case, sample_test) { EXPECT_EQ(1, 1); } <commit_msg>Fixed last commit<commit_after><|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: DomBuilderContext.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2005-09-09 13:31:45 $ * * 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 "DomBuilderContext.hxx" #include "nmspmap.hxx" #include "xmlimp.hxx" #include "xmlerror.hxx" #include <com/sun/star/lang/XMultiServiceFactory.hpp> #include <com/sun/star/uno/Reference.hxx> #include <com/sun/star/uno/Sequence.hxx> #include <com/sun/star/xml/dom/XAttr.hpp> #include <com/sun/star/xml/dom/XDocumentBuilder.hpp> #include <com/sun/star/xml/dom/XNode.hpp> #include <com/sun/star/xml/dom/XElement.hpp> #include <com/sun/star/xml/sax/XAttributeList.hpp> #include <com/sun/star/xml/dom/NodeType.hpp> #include <rtl/ustring.hxx> #include <tools/debug.hxx> #include <unotools/processfactory.hxx> using com::sun::star::lang::XMultiServiceFactory; using com::sun::star::uno::Reference; using com::sun::star::uno::Sequence; using com::sun::star::uno::UNO_QUERY; using com::sun::star::uno::UNO_QUERY_THROW; using com::sun::star::xml::dom::XAttr; using com::sun::star::xml::dom::XDocument; using com::sun::star::xml::dom::XDocumentBuilder; using com::sun::star::xml::dom::XNode; using com::sun::star::xml::dom::XElement; using com::sun::star::xml::sax::XAttributeList; using com::sun::star::xml::dom::NodeType_ELEMENT_NODE; using rtl::OUString; // helper functions; implemented below Reference<XNode> lcl_createDomInstance(); Reference<XNode> lcl_createElement( SvXMLImport& rImport, USHORT nPrefix, const OUString rLocalName, Reference<XNode> xParent); DomBuilderContext::DomBuilderContext( SvXMLImport& rImport, USHORT nPrefix, const OUString& rLocalName ) : SvXMLImportContext( rImport, nPrefix, rLocalName ), mxNode( lcl_createElement( rImport, nPrefix, rLocalName, lcl_createDomInstance() ) ) { DBG_ASSERT( mxNode.is(), "empty XNode not allowed" ); DBG_ASSERT( Reference<XElement>( mxNode, UNO_QUERY ).is(), "need element" ); DBG_ASSERT( mxNode->getNodeType() == NodeType_ELEMENT_NODE, "need element" ); } DomBuilderContext::DomBuilderContext( SvXMLImport& rImport, USHORT nPrefix, const OUString& rLocalName, Reference<XNode>& xParent ) : SvXMLImportContext( rImport, nPrefix, rLocalName ), mxNode( lcl_createElement( rImport, nPrefix, rLocalName, xParent ) ) { DBG_ASSERT( mxNode.is(), "empty XNode not allowed" ); DBG_ASSERT( Reference<XElement>( mxNode, UNO_QUERY ).is(), "need element" ); DBG_ASSERT( mxNode->getNodeType() == NodeType_ELEMENT_NODE, "need element" ); } DomBuilderContext::~DomBuilderContext() { } Reference<XDocument> DomBuilderContext::getTree() { DBG_ASSERT( mxNode.is(), "empty XNode not allowed" ); return mxNode->getOwnerDocument(); } Reference<XNode> DomBuilderContext::getNode() { return mxNode; } SvXMLImportContext* DomBuilderContext::CreateChildContext( USHORT nPrefix, const OUString& rLocalName, const Reference<XAttributeList>& ) { // create DomBuilder for subtree return new DomBuilderContext( GetImport(), nPrefix, rLocalName, mxNode ); } void DomBuilderContext::StartElement( const Reference<XAttributeList>& xAttrList ) { DBG_ASSERT( mxNode.is(), "empty XNode not allowed" ); DBG_ASSERT( mxNode->getOwnerDocument().is(), "XNode must have XDocument" ); // add attribute nodes to new node sal_Int16 nAttributeCount = xAttrList->getLength(); for( sal_Int16 i = 0; i < nAttributeCount; i++ ) { // get name & value for attribute const OUString& rName = xAttrList->getNameByIndex( i ); const OUString& rValue = xAttrList->getValueByIndex( i ); // namespace handling: determine namespace & namespace keykey OUString sNamespace; sal_uInt16 nNamespaceKey = GetImport().GetNamespaceMap()._GetKeyByAttrName( rName, NULL, NULL, &sNamespace ); // create attribute node and set value Reference<XElement> xElement( mxNode, UNO_QUERY_THROW ); switch( nNamespaceKey ) { case XML_NAMESPACE_NONE: // no namespace: create a non-namespaced attribute xElement->setAttribute( rName, rValue ); break; case XML_NAMESPACE_XMLNS: // namespace declaration: ignore, since the DOM tree handles these // declarations implicitly break; case XML_NAMESPACE_UNKNOWN: // unknown namespace: illegal input. Raise Warning. { Sequence<OUString> aSeq(2); aSeq[0] = rName; aSeq[1] = rValue; GetImport().SetError( XMLERROR_FLAG_WARNING | XMLERROR_NAMESPACE_TROUBLE, aSeq ); } break; default: // a real and proper namespace: create namespaced attribute xElement->setAttributeNS( sNamespace, rName, rValue ); break; } } } void DomBuilderContext::EndElement() { // nothing to be done! } void DomBuilderContext::Characters( const OUString& rCharacters ) { DBG_ASSERT( mxNode.is(), "empty XNode not allowed" ); // TODO: I assume adjacent text nodes should be joined, to preserve // processinf model? (I.e., if the SAX parser breaks a string into 2 // Characters(..) calls, the DOM model would still see only one child.) // create text node and append to parent Reference<XNode> xNew( mxNode->getOwnerDocument()->createTextNode( rCharacters ), UNO_QUERY_THROW ); mxNode->appendChild( xNew ); } // // helper function implementations // const sal_Char sDocumentBuilder[] = "com.sun.star.xml.dom.DocumentBuilder"; Reference<XNode> lcl_createDomInstance() { Reference<XMultiServiceFactory> xFactory = utl::getProcessServiceFactory(); DBG_ASSERT( xFactory.is(), "can't get service factory" ); Reference<XDocumentBuilder> xBuilder( xFactory->createInstance( OUString( RTL_CONSTASCII_USTRINGPARAM( sDocumentBuilder ) ) ), UNO_QUERY_THROW ); return Reference<XNode>( xBuilder->newDocument(), UNO_QUERY_THROW ); } Reference<XNode> lcl_createElement( SvXMLImport& rImport, USHORT nPrefix, const OUString rLocalName, Reference<XNode> xParent) { DBG_ASSERT( xParent.is(), "need parent node" ); Reference<XDocument> xDocument = xParent->getOwnerDocument(); DBG_ASSERT( xDocument.is(), "no XDocument found!" ); // TODO: come up with proper way of handling namespaces; re-creating the // namespace from the key is NOT a good idea, and will not work for // multiple prefixes for the same namespace. Fortunately, those are rare. Reference<XElement> xElement; switch( nPrefix ) { case XML_NAMESPACE_NONE: // no namespace: use local name xElement = xDocument->createElement( rLocalName ); break; case XML_NAMESPACE_XMLNS: case XML_NAMESPACE_UNKNOWN: // both cases are illegal; raise warning (and use only local name) xElement = xDocument->createElement( rLocalName ); { Sequence<OUString> aSeq(1); aSeq[0] = rLocalName; rImport.SetError( XMLERROR_FLAG_WARNING | XMLERROR_NAMESPACE_TROUBLE, aSeq ); } break; default: // We are only given the prefix and the local name; thus we have to ask // the namespace map to create a qualified name for us. Technically, // this is a bug, since this will fail for multiple prefixes used for // the same namespace. xElement = xDocument->createElementNS( rImport.GetNamespaceMap().GetNameByKey( nPrefix ), rImport.GetNamespaceMap().GetQNameByKey( nPrefix, rLocalName ) ); break; } DBG_ASSERT( xElement.is(), "can't create element" ); // add new element to parent and return Reference<XNode> xNode( xElement, UNO_QUERY_THROW ); xParent->appendChild( xNode ); return xNode; } <commit_msg>INTEGRATION: CWS pchfix02 (1.3.160); FILE MERGED 2006/09/01 17:59:25 kaib 1.3.160.1: #i68856# Added header markers and pch files<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: DomBuilderContext.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: obo $ $Date: 2006-09-17 10:18:13 $ * * 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_xmloff.hxx" #include "DomBuilderContext.hxx" #include "nmspmap.hxx" #include "xmlimp.hxx" #include "xmlerror.hxx" #include <com/sun/star/lang/XMultiServiceFactory.hpp> #include <com/sun/star/uno/Reference.hxx> #include <com/sun/star/uno/Sequence.hxx> #include <com/sun/star/xml/dom/XAttr.hpp> #include <com/sun/star/xml/dom/XDocumentBuilder.hpp> #include <com/sun/star/xml/dom/XNode.hpp> #include <com/sun/star/xml/dom/XElement.hpp> #include <com/sun/star/xml/sax/XAttributeList.hpp> #include <com/sun/star/xml/dom/NodeType.hpp> #include <rtl/ustring.hxx> #include <tools/debug.hxx> #include <unotools/processfactory.hxx> using com::sun::star::lang::XMultiServiceFactory; using com::sun::star::uno::Reference; using com::sun::star::uno::Sequence; using com::sun::star::uno::UNO_QUERY; using com::sun::star::uno::UNO_QUERY_THROW; using com::sun::star::xml::dom::XAttr; using com::sun::star::xml::dom::XDocument; using com::sun::star::xml::dom::XDocumentBuilder; using com::sun::star::xml::dom::XNode; using com::sun::star::xml::dom::XElement; using com::sun::star::xml::sax::XAttributeList; using com::sun::star::xml::dom::NodeType_ELEMENT_NODE; using rtl::OUString; // helper functions; implemented below Reference<XNode> lcl_createDomInstance(); Reference<XNode> lcl_createElement( SvXMLImport& rImport, USHORT nPrefix, const OUString rLocalName, Reference<XNode> xParent); DomBuilderContext::DomBuilderContext( SvXMLImport& rImport, USHORT nPrefix, const OUString& rLocalName ) : SvXMLImportContext( rImport, nPrefix, rLocalName ), mxNode( lcl_createElement( rImport, nPrefix, rLocalName, lcl_createDomInstance() ) ) { DBG_ASSERT( mxNode.is(), "empty XNode not allowed" ); DBG_ASSERT( Reference<XElement>( mxNode, UNO_QUERY ).is(), "need element" ); DBG_ASSERT( mxNode->getNodeType() == NodeType_ELEMENT_NODE, "need element" ); } DomBuilderContext::DomBuilderContext( SvXMLImport& rImport, USHORT nPrefix, const OUString& rLocalName, Reference<XNode>& xParent ) : SvXMLImportContext( rImport, nPrefix, rLocalName ), mxNode( lcl_createElement( rImport, nPrefix, rLocalName, xParent ) ) { DBG_ASSERT( mxNode.is(), "empty XNode not allowed" ); DBG_ASSERT( Reference<XElement>( mxNode, UNO_QUERY ).is(), "need element" ); DBG_ASSERT( mxNode->getNodeType() == NodeType_ELEMENT_NODE, "need element" ); } DomBuilderContext::~DomBuilderContext() { } Reference<XDocument> DomBuilderContext::getTree() { DBG_ASSERT( mxNode.is(), "empty XNode not allowed" ); return mxNode->getOwnerDocument(); } Reference<XNode> DomBuilderContext::getNode() { return mxNode; } SvXMLImportContext* DomBuilderContext::CreateChildContext( USHORT nPrefix, const OUString& rLocalName, const Reference<XAttributeList>& ) { // create DomBuilder for subtree return new DomBuilderContext( GetImport(), nPrefix, rLocalName, mxNode ); } void DomBuilderContext::StartElement( const Reference<XAttributeList>& xAttrList ) { DBG_ASSERT( mxNode.is(), "empty XNode not allowed" ); DBG_ASSERT( mxNode->getOwnerDocument().is(), "XNode must have XDocument" ); // add attribute nodes to new node sal_Int16 nAttributeCount = xAttrList->getLength(); for( sal_Int16 i = 0; i < nAttributeCount; i++ ) { // get name & value for attribute const OUString& rName = xAttrList->getNameByIndex( i ); const OUString& rValue = xAttrList->getValueByIndex( i ); // namespace handling: determine namespace & namespace keykey OUString sNamespace; sal_uInt16 nNamespaceKey = GetImport().GetNamespaceMap()._GetKeyByAttrName( rName, NULL, NULL, &sNamespace ); // create attribute node and set value Reference<XElement> xElement( mxNode, UNO_QUERY_THROW ); switch( nNamespaceKey ) { case XML_NAMESPACE_NONE: // no namespace: create a non-namespaced attribute xElement->setAttribute( rName, rValue ); break; case XML_NAMESPACE_XMLNS: // namespace declaration: ignore, since the DOM tree handles these // declarations implicitly break; case XML_NAMESPACE_UNKNOWN: // unknown namespace: illegal input. Raise Warning. { Sequence<OUString> aSeq(2); aSeq[0] = rName; aSeq[1] = rValue; GetImport().SetError( XMLERROR_FLAG_WARNING | XMLERROR_NAMESPACE_TROUBLE, aSeq ); } break; default: // a real and proper namespace: create namespaced attribute xElement->setAttributeNS( sNamespace, rName, rValue ); break; } } } void DomBuilderContext::EndElement() { // nothing to be done! } void DomBuilderContext::Characters( const OUString& rCharacters ) { DBG_ASSERT( mxNode.is(), "empty XNode not allowed" ); // TODO: I assume adjacent text nodes should be joined, to preserve // processinf model? (I.e., if the SAX parser breaks a string into 2 // Characters(..) calls, the DOM model would still see only one child.) // create text node and append to parent Reference<XNode> xNew( mxNode->getOwnerDocument()->createTextNode( rCharacters ), UNO_QUERY_THROW ); mxNode->appendChild( xNew ); } // // helper function implementations // const sal_Char sDocumentBuilder[] = "com.sun.star.xml.dom.DocumentBuilder"; Reference<XNode> lcl_createDomInstance() { Reference<XMultiServiceFactory> xFactory = utl::getProcessServiceFactory(); DBG_ASSERT( xFactory.is(), "can't get service factory" ); Reference<XDocumentBuilder> xBuilder( xFactory->createInstance( OUString( RTL_CONSTASCII_USTRINGPARAM( sDocumentBuilder ) ) ), UNO_QUERY_THROW ); return Reference<XNode>( xBuilder->newDocument(), UNO_QUERY_THROW ); } Reference<XNode> lcl_createElement( SvXMLImport& rImport, USHORT nPrefix, const OUString rLocalName, Reference<XNode> xParent) { DBG_ASSERT( xParent.is(), "need parent node" ); Reference<XDocument> xDocument = xParent->getOwnerDocument(); DBG_ASSERT( xDocument.is(), "no XDocument found!" ); // TODO: come up with proper way of handling namespaces; re-creating the // namespace from the key is NOT a good idea, and will not work for // multiple prefixes for the same namespace. Fortunately, those are rare. Reference<XElement> xElement; switch( nPrefix ) { case XML_NAMESPACE_NONE: // no namespace: use local name xElement = xDocument->createElement( rLocalName ); break; case XML_NAMESPACE_XMLNS: case XML_NAMESPACE_UNKNOWN: // both cases are illegal; raise warning (and use only local name) xElement = xDocument->createElement( rLocalName ); { Sequence<OUString> aSeq(1); aSeq[0] = rLocalName; rImport.SetError( XMLERROR_FLAG_WARNING | XMLERROR_NAMESPACE_TROUBLE, aSeq ); } break; default: // We are only given the prefix and the local name; thus we have to ask // the namespace map to create a qualified name for us. Technically, // this is a bug, since this will fail for multiple prefixes used for // the same namespace. xElement = xDocument->createElementNS( rImport.GetNamespaceMap().GetNameByKey( nPrefix ), rImport.GetNamespaceMap().GetQNameByKey( nPrefix, rLocalName ) ); break; } DBG_ASSERT( xElement.is(), "can't create element" ); // add new element to parent and return Reference<XNode> xNode( xElement, UNO_QUERY_THROW ); xParent->appendChild( xNode ); return xNode; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: HCatalog.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2005-09-08 06:02: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 CONNECTIVITY_HSQLDB_CATALOG_HXX #include "hsqldb/HCatalog.hxx" #endif #ifndef _CONNECTIVITY_HSQLDB_USERS_HXX_ #include "hsqldb/HUsers.hxx" #endif #ifndef CONNECTIVITY_HSQLDB_TABLES_HXX #include "hsqldb/HTables.hxx" #endif #ifndef _CONNECTIVITY_HSQLDB_VIEWS_HXX_ #include "hsqldb/HViews.hxx" #endif #ifndef _COM_SUN_STAR_SDBC_XROW_HPP_ #include <com/sun/star/sdbc/XRow.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_ #include <com/sun/star/sdbc/XResultSet.hpp> #endif #ifndef _COMPHELPER_TYPES_HXX_ #include <comphelper/types.hxx> #endif // ------------------------------------------------------------------------- using namespace connectivity; using namespace connectivity::hsqldb; //using namespace connectivity::sdbcx; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::sdbcx; using namespace ::com::sun::star::sdbc; using namespace ::com::sun::star::container; using namespace ::com::sun::star::lang; // ------------------------------------------------------------------------- OHCatalog::OHCatalog(const Reference< XConnection >& _xConnection) : sdbcx::OCatalog(_xConnection) ,m_xConnection(_xConnection) { } // ----------------------------------------------------------------------------- void OHCatalog::refreshObjects(const Sequence< ::rtl::OUString >& _sKindOfObject,TStringVector& _rNames) { Reference< XResultSet > xResult = m_xMetaData->getTables(Any(), ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("%")), ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("%")), _sKindOfObject); fillNames(xResult,_rNames); } // ------------------------------------------------------------------------- void OHCatalog::refreshTables() { TStringVector aVector; static const ::rtl::OUString s_sTableTypeView(RTL_CONSTASCII_USTRINGPARAM("VIEW")); static const ::rtl::OUString s_sTableTypeTable(RTL_CONSTASCII_USTRINGPARAM("TABLE")); Sequence< ::rtl::OUString > sTableTypes(2); sTableTypes[0] = s_sTableTypeView; sTableTypes[1] = s_sTableTypeTable; refreshObjects(sTableTypes,aVector); if ( m_pTables ) m_pTables->reFill(aVector); else m_pTables = new OTables(m_xMetaData,*this,m_aMutex,aVector); } // ------------------------------------------------------------------------- void OHCatalog::refreshViews() { Sequence< ::rtl::OUString > aTypes(1); aTypes[0] = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("VIEW")); sal_Bool bSupportsViews = sal_False; try { Reference<XResultSet> xRes = m_xMetaData->getTableTypes(); Reference<XRow> xRow(xRes,UNO_QUERY); while ( xRow.is() && xRes->next() ) { if ( bSupportsViews = xRow->getString(1).equalsIgnoreAsciiCase(aTypes[0]) ) { break; } } } catch(const SQLException&) { } TStringVector aVector; if ( bSupportsViews ) refreshObjects(aTypes,aVector); if ( m_pViews ) m_pViews->reFill(aVector); else m_pViews = new OViews(m_xMetaData,*this,m_aMutex,aVector); } // ------------------------------------------------------------------------- void OHCatalog::refreshGroups() { } // ------------------------------------------------------------------------- void OHCatalog::refreshUsers() { TStringVector aVector; Reference< XStatement > xStmt = m_xConnection->createStatement( ); Reference< XResultSet > xResult = xStmt->executeQuery(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("select User from hsqldb.user group by User"))); if ( xResult.is() ) { Reference< XRow > xRow(xResult,UNO_QUERY); TString2IntMap aMap; while( xResult->next() ) aVector.push_back(xRow->getString(1)); ::comphelper::disposeComponent(xResult); } ::comphelper::disposeComponent(xStmt); if(m_pUsers) m_pUsers->reFill(aVector); else m_pUsers = new OUsers(*this,m_aMutex,aVector,m_xConnection,this); } // ----------------------------------------------------------------------------- Any SAL_CALL OHCatalog::queryInterface( const Type & rType ) throw(RuntimeException) { if ( rType == ::getCppuType((const Reference<XGroupsSupplier>*)0) ) return Any(); return OCatalog::queryInterface(rType); } // ----------------------------------------------------------------------------- Sequence< Type > SAL_CALL OHCatalog::getTypes( ) throw(RuntimeException) { Sequence< Type > aTypes = OCatalog::getTypes(); ::std::vector<Type> aOwnTypes; aOwnTypes.reserve(aTypes.getLength()); const Type* pBegin = aTypes.getConstArray(); const Type* pEnd = pBegin + aTypes.getLength(); for(;pBegin != pEnd;++pBegin) { if ( !(*pBegin == ::getCppuType((const Reference<XGroupsSupplier>*)0))) { aOwnTypes.push_back(*pBegin); } } const Type* pTypes = aOwnTypes.empty() ? 0 : &aOwnTypes[0]; return Sequence< Type >(pTypes, aOwnTypes.size()); } // ----------------------------------------------------------------------------- <commit_msg>INTEGRATION: CWS warningfixes02 (1.4.128); FILE MERGED 2006/06/30 11:44:34 sb 1.4.128.1: #i66577# Made the code compile (warning-free) on a unxlngi6.pro GCC 4.1.1 Linux box.<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: HCatalog.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: kz $ $Date: 2006-07-19 15:52:55 $ * * 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_HSQLDB_CATALOG_HXX #include "hsqldb/HCatalog.hxx" #endif #ifndef _CONNECTIVITY_HSQLDB_USERS_HXX_ #include "hsqldb/HUsers.hxx" #endif #ifndef CONNECTIVITY_HSQLDB_TABLES_HXX #include "hsqldb/HTables.hxx" #endif #ifndef _CONNECTIVITY_HSQLDB_VIEWS_HXX_ #include "hsqldb/HViews.hxx" #endif #ifndef _COM_SUN_STAR_SDBC_XROW_HPP_ #include <com/sun/star/sdbc/XRow.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_ #include <com/sun/star/sdbc/XResultSet.hpp> #endif #ifndef _COMPHELPER_TYPES_HXX_ #include <comphelper/types.hxx> #endif // ------------------------------------------------------------------------- using namespace connectivity; using namespace connectivity::hsqldb; //using namespace connectivity::sdbcx; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::sdbcx; using namespace ::com::sun::star::sdbc; using namespace ::com::sun::star::container; using namespace ::com::sun::star::lang; // ------------------------------------------------------------------------- OHCatalog::OHCatalog(const Reference< XConnection >& _xConnection) : sdbcx::OCatalog(_xConnection) ,m_xConnection(_xConnection) { } // ----------------------------------------------------------------------------- void OHCatalog::refreshObjects(const Sequence< ::rtl::OUString >& _sKindOfObject,TStringVector& _rNames) { Reference< XResultSet > xResult = m_xMetaData->getTables(Any(), ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("%")), ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("%")), _sKindOfObject); fillNames(xResult,_rNames); } // ------------------------------------------------------------------------- void OHCatalog::refreshTables() { TStringVector aVector; static const ::rtl::OUString s_sTableTypeView(RTL_CONSTASCII_USTRINGPARAM("VIEW")); static const ::rtl::OUString s_sTableTypeTable(RTL_CONSTASCII_USTRINGPARAM("TABLE")); Sequence< ::rtl::OUString > sTableTypes(2); sTableTypes[0] = s_sTableTypeView; sTableTypes[1] = s_sTableTypeTable; refreshObjects(sTableTypes,aVector); if ( m_pTables ) m_pTables->reFill(aVector); else m_pTables = new OTables(m_xMetaData,*this,m_aMutex,aVector); } // ------------------------------------------------------------------------- void OHCatalog::refreshViews() { Sequence< ::rtl::OUString > aTypes(1); aTypes[0] = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("VIEW")); sal_Bool bSupportsViews = sal_False; try { Reference<XResultSet> xRes = m_xMetaData->getTableTypes(); Reference<XRow> xRow(xRes,UNO_QUERY); while ( xRow.is() && xRes->next() ) { if ( (bSupportsViews = xRow->getString(1).equalsIgnoreAsciiCase(aTypes[0])) ) { break; } } } catch(const SQLException&) { } TStringVector aVector; if ( bSupportsViews ) refreshObjects(aTypes,aVector); if ( m_pViews ) m_pViews->reFill(aVector); else m_pViews = new OViews(m_xMetaData,*this,m_aMutex,aVector); } // ------------------------------------------------------------------------- void OHCatalog::refreshGroups() { } // ------------------------------------------------------------------------- void OHCatalog::refreshUsers() { TStringVector aVector; Reference< XStatement > xStmt = m_xConnection->createStatement( ); Reference< XResultSet > xResult = xStmt->executeQuery(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("select User from hsqldb.user group by User"))); if ( xResult.is() ) { Reference< XRow > xRow(xResult,UNO_QUERY); TString2IntMap aMap; while( xResult->next() ) aVector.push_back(xRow->getString(1)); ::comphelper::disposeComponent(xResult); } ::comphelper::disposeComponent(xStmt); if(m_pUsers) m_pUsers->reFill(aVector); else m_pUsers = new OUsers(*this,m_aMutex,aVector,m_xConnection,this); } // ----------------------------------------------------------------------------- Any SAL_CALL OHCatalog::queryInterface( const Type & rType ) throw(RuntimeException) { if ( rType == ::getCppuType((const Reference<XGroupsSupplier>*)0) ) return Any(); return OCatalog::queryInterface(rType); } // ----------------------------------------------------------------------------- Sequence< Type > SAL_CALL OHCatalog::getTypes( ) throw(RuntimeException) { Sequence< Type > aTypes = OCatalog::getTypes(); ::std::vector<Type> aOwnTypes; aOwnTypes.reserve(aTypes.getLength()); const Type* pBegin = aTypes.getConstArray(); const Type* pEnd = pBegin + aTypes.getLength(); for(;pBegin != pEnd;++pBegin) { if ( !(*pBegin == ::getCppuType((const Reference<XGroupsSupplier>*)0))) { aOwnTypes.push_back(*pBegin); } } const Type* pTypes = aOwnTypes.empty() ? 0 : &aOwnTypes[0]; return Sequence< Type >(pTypes, aOwnTypes.size()); } // ----------------------------------------------------------------------------- <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: Connection.hxx,v $ * * $Revision: 1.8 $ * * last change: $Author: oj $ $Date: 2002-11-21 15:46:31 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _CONNECTIVITY_JAVA_SQL_CONNECTION_HXX_ #define _CONNECTIVITY_JAVA_SQL_CONNECTION_HXX_ #ifndef _CONNECTIVITY_JAVA_LANG_OBJECT_HXX_ #include "java/lang/Object.hxx" #endif #ifndef CONNECTIVITY_CONNECTION_HXX #include "TConnection.hxx" #endif #ifndef _CONNECTIVITY_COMMONTOOLS_HXX_ #include "connectivity/CommonTools.hxx" #endif #ifndef _CONNECTIVITY_OSUBCOMPONENT_HXX_ #include "OSubComponent.hxx" #endif #ifndef _CPPUHELPER_WEAKREF_HXX_ #include <cppuhelper/weakref.hxx> #endif #ifndef _CONNECTIVITY_AUTOKEYRETRIEVINGBASE_HXX_ #include "AutoRetrievingBase.hxx" #endif namespace connectivity { class java_sql_Driver; typedef OMetaConnection java_sql_Connection_BASE; class java_sql_Connection : public java_sql_Connection_BASE, public java_lang_Object, public OSubComponent<java_sql_Connection, java_sql_Connection_BASE>, public OAutoRetrievingBase { friend class OSubComponent<java_sql_Connection, java_sql_Connection_BASE>; ::com::sun::star::uno::WeakReference< ::com::sun::star::sdbc::XDatabaseMetaData > m_xMetaData; OWeakRefArray m_aStatements; // vector containing a list // of all the Statement objects // for this Connection java_sql_Driver* m_pDriver; sal_Bool m_bParameterSubstitution; /** transform named parameter into unnamed one. @param _sSQL The SQL statement to transform. @return The new statement witgh unnamed parameters. */ ::rtl::OUString transFormPreparedStatement(const ::rtl::OUString& _sSQL); protected: // statische Daten fuer die Klasse static jclass theClass; // der Destruktor um den Object-Counter zu aktualisieren static void saveClassRef( jclass pClass ); virtual ~java_sql_Connection(); public: static int TRANSACTION_NONE; static int TRANSACTION_READ_COMMITTED; static int TRANSACTION_READ_UNCOMMITTED; static int TRANSACTION_REPEATABLE_READ; static int TRANSACTION_SERIALIZABLE; static jclass getMyClass(); DECLARE_SERVICE_INFO(); // ein Konstruktor, der fuer das Returnen des Objektes benoetigt wird: java_sql_Connection( JNIEnv * pEnv , jobject myObj ,java_sql_Driver* _pDriver ,const ::rtl::OUString& _sGeneredStmt ,sal_Bool _bGenEnabled ,sal_Bool _bParameterSubstitution); // OComponentHelper virtual void SAL_CALL disposing(void); // XInterface virtual void SAL_CALL release() throw(); // XConnection virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XStatement > SAL_CALL createStatement( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XPreparedStatement > SAL_CALL prepareStatement( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XPreparedStatement > SAL_CALL prepareCall( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual ::rtl::OUString SAL_CALL nativeSQL( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setAutoCommit( sal_Bool autoCommit ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL getAutoCommit( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL commit( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL rollback( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL isClosed( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData > SAL_CALL getMetaData( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setReadOnly( sal_Bool readOnly ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL isReadOnly( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setCatalog( const ::rtl::OUString& catalog ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual ::rtl::OUString SAL_CALL getCatalog( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setTransactionIsolation( sal_Int32 level ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual sal_Int32 SAL_CALL getTransactionIsolation( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess > SAL_CALL getTypeMap( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setTypeMap( const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess >& typeMap ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); // XCloseable virtual void SAL_CALL close( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); // XWarningsSupplier virtual ::com::sun::star::uno::Any SAL_CALL getWarnings( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL clearWarnings( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); }; } #endif // _CONNECTIVITY_JAVA_SQL_CONNECTION_HXX_ <commit_msg>INTEGRATION: CWS dba04 (1.8.44); FILE MERGED 2003/03/26 17:36:21 oj 1.8.44.1: #i12664# introduce IgnoreDriverPrivileges<commit_after>/************************************************************************* * * $RCSfile: Connection.hxx,v $ * * $Revision: 1.9 $ * * last change: $Author: vg $ $Date: 2003-04-11 14:41:59 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _CONNECTIVITY_JAVA_SQL_CONNECTION_HXX_ #define _CONNECTIVITY_JAVA_SQL_CONNECTION_HXX_ #ifndef _CONNECTIVITY_JAVA_LANG_OBJECT_HXX_ #include "java/lang/Object.hxx" #endif #ifndef CONNECTIVITY_CONNECTION_HXX #include "TConnection.hxx" #endif #ifndef _CONNECTIVITY_COMMONTOOLS_HXX_ #include "connectivity/CommonTools.hxx" #endif #ifndef _CONNECTIVITY_OSUBCOMPONENT_HXX_ #include "OSubComponent.hxx" #endif #ifndef _CPPUHELPER_WEAKREF_HXX_ #include <cppuhelper/weakref.hxx> #endif #ifndef _CONNECTIVITY_AUTOKEYRETRIEVINGBASE_HXX_ #include "AutoRetrievingBase.hxx" #endif namespace connectivity { class java_sql_Driver; typedef OMetaConnection java_sql_Connection_BASE; class java_sql_Connection : public java_sql_Connection_BASE, public java_lang_Object, public OSubComponent<java_sql_Connection, java_sql_Connection_BASE>, public OAutoRetrievingBase { friend class OSubComponent<java_sql_Connection, java_sql_Connection_BASE>; ::com::sun::star::uno::WeakReference< ::com::sun::star::sdbc::XDatabaseMetaData > m_xMetaData; OWeakRefArray m_aStatements; // vector containing a list // of all the Statement objects // for this Connection java_sql_Driver* m_pDriver; sal_Bool m_bParameterSubstitution; sal_Bool m_bIgnoreDriverPrivileges; /** transform named parameter into unnamed one. @param _sSQL The SQL statement to transform. @return The new statement witgh unnamed parameters. */ ::rtl::OUString transFormPreparedStatement(const ::rtl::OUString& _sSQL); protected: // statische Daten fuer die Klasse static jclass theClass; // der Destruktor um den Object-Counter zu aktualisieren static void saveClassRef( jclass pClass ); virtual ~java_sql_Connection(); public: static int TRANSACTION_NONE; static int TRANSACTION_READ_COMMITTED; static int TRANSACTION_READ_UNCOMMITTED; static int TRANSACTION_REPEATABLE_READ; static int TRANSACTION_SERIALIZABLE; static jclass getMyClass(); DECLARE_SERVICE_INFO(); // ein Konstruktor, der fuer das Returnen des Objektes benoetigt wird: java_sql_Connection( JNIEnv * pEnv , jobject myObj ,java_sql_Driver* _pDriver ,const ::rtl::OUString& _sGeneredStmt ,sal_Bool _bGenEnabled ,sal_Bool _bParameterSubstitution ,sal_Bool _bIgnoreDriverPrivileges); inline sal_Bool isIgnoreDriverPrivilegesEnabled() const { return m_bIgnoreDriverPrivileges;} // OComponentHelper virtual void SAL_CALL disposing(void); // XInterface virtual void SAL_CALL release() throw(); // XConnection virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XStatement > SAL_CALL createStatement( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XPreparedStatement > SAL_CALL prepareStatement( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XPreparedStatement > SAL_CALL prepareCall( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual ::rtl::OUString SAL_CALL nativeSQL( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setAutoCommit( sal_Bool autoCommit ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL getAutoCommit( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL commit( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL rollback( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL isClosed( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData > SAL_CALL getMetaData( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setReadOnly( sal_Bool readOnly ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL isReadOnly( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setCatalog( const ::rtl::OUString& catalog ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual ::rtl::OUString SAL_CALL getCatalog( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setTransactionIsolation( sal_Int32 level ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual sal_Int32 SAL_CALL getTransactionIsolation( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess > SAL_CALL getTypeMap( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setTypeMap( const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess >& typeMap ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); // XCloseable virtual void SAL_CALL close( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); // XWarningsSupplier virtual ::com::sun::star::uno::Any SAL_CALL getWarnings( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL clearWarnings( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); }; } #endif // _CONNECTIVITY_JAVA_SQL_CONNECTION_HXX_ <|endoftext|>
<commit_before>// TODO: remove hardcoded limits #include <iostream> #include <time.h> #define randomize() (srand((unsigned)time(NULL))) // Do not changed or you break everything static int ANZAHL_WUERFE = 10; static int ANZAHL_SPIELER = 10; int main() { using namespace std; randomize(); cout << "=======================================================" << endl; cout << " Das Würfelspiel" << endl; cout << "=======================================================" << endl << endl; //unsigned int ANZAHL_SPIELER; //cout << "Anzahl Spieler: "; //cin >> ANZAHL_SPIELER; //cout << endl; //ANZAHL_SPIELER = 8; // Array mit Ergebnissen unsigned int aiZMZ[ANZAHL_WUERFE][ANZAHL_SPIELER] = {0}; // Array mit Anzahl der Augen //unsigned int aiAnzahl[6][ANZAHL_SPIELER] = {0}; unsigned int aiAnzahl[6][11] = {0}; for(int Spieler = 0; Spieler < ANZAHL_SPIELER; Spieler++) { cout << "Spieler " << Spieler + 1 << ":\t"; for(int WNr = 0; WNr < ANZAHL_WUERFE; WNr++) { int wurf = rand() % 6 + 1; cout << wurf << " "; aiZMZ[WNr][Spieler] = wurf; //cout << aiAnzahl[wurf-1][Spieler] << " "; aiAnzahl[wurf - 1][Spieler] += 1; aiAnzahl[wurf - 1][10] += 1; //cout << aiZMZ[WNr][Spieler] << " "; //cout << aiAnzahl[wurf-1][Spieler] << " "; } cout << endl; } cout << endl; float afProzent[6][ANZAHL_SPIELER + 1] = {{0, 0}, {0, 0}}; for(int Spieler = 0; Spieler <= ANZAHL_SPIELER; Spieler++) { for(int WNr = 0; WNr < 6; WNr++) { float f = ANZAHL_WUERFE; if(Spieler == 11) { float f = (ANZAHL_WUERFE * ANZAHL_SPIELER); } afProzent[WNr][Spieler] = aiAnzahl[WNr][Spieler] / f * 10; } } for(int Spieler = 0; Spieler <= ANZAHL_SPIELER; Spieler++) { if(Spieler == 10) { cout << "\nGesamt" << ":\n"; } else { cout << "\nSpieler " << Spieler + 1 << ":\n"; } for (int WNr = 0; WNr < 6; WNr++) { cout << "Anzahl " << WNr + 1 << ": " << aiAnzahl[WNr][Spieler] << "\tProzent: " << afProzent[WNr][Spieler] << "%" << endl; } } return 0; } <commit_msg>Revert "Added "wuerfel" programm"<commit_after><|endoftext|>
<commit_before>/* * eos - A 3D Morphable Model fitting library written in modern C++11/14. * * File: utils/generate-python-bindings.cpp * * Copyright 2016 Patrik Huber * * 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 "eos/morphablemodel/PcaModel.hpp" #include "eos/morphablemodel/MorphableModel.hpp" #include "opencv2/core/core.hpp" #include "pybind11/pybind11.h" #include "pybind11/stl.h" #include <iostream> #include <stdexcept> #include <string> namespace py = pybind11; using namespace eos; /** * Generate python bindings for the eos library using pybind11. */ PYBIND11_PLUGIN(eos) { py::module eos_module("eos", "Python bindings to the 3D Morphable Face Model fitting library"); /** * General bindings, for OpenCV vector types and cv::Mat: * - cv::Vec2f * - cv::Vec4f * - cv::Mat (only 1-channel matrices and only conversion of CV_32F C++ matrices to Python, and conversion of CV_32FC1 and CV_64FC1 matrices from Python to C++) */ py::class_<cv::Vec2f>(eos_module, "Vec2f", "Wrapper for OpenCV's cv::Vec2f type.") .def("__init__", [](cv::Vec2f& vec, py::buffer b) { py::buffer_info info = b.request(); if (info.ndim != 1) throw std::runtime_error("Buffer ndim is " + std::to_string(info.ndim) + ", please hand a buffer with dimension == 1 to create a Vec2f."); if (info.strides.size() != 1) throw std::runtime_error("strides.size() is " + std::to_string(info.strides.size()) + ", please hand a buffer with strides.size() == 1 to create a Vec2f."); // Todo: Should add a check that checks for default stride sizes, everything else would not work yet I think. if (info.shape.size() != 1) throw std::runtime_error("shape.size() is " + std::to_string(info.shape.size()) + ", please hand a buffer with shape dimension == 1 to create a Vec2f."); if (info.shape[0] != 2) throw std::runtime_error("shape[0] is " + std::to_string(info.shape[0]) + ", please hand a buffer with 2 entries to create a Vec2f."); if (info.format == py::format_descriptor<float>::format()) { cv::Mat temp(1, 2, CV_32FC1, info.ptr); std::cout << temp << std::endl; new (&vec) cv::Vec2f(temp); } else { throw std::runtime_error("Not given a buffer of type float - please hand a buffer of type float to create a Vec2f."); } }) .def_buffer([](cv::Vec2f& vec) -> py::buffer_info { return py::buffer_info( &vec.val, /* Pointer to buffer */ sizeof(float), /* Size of one scalar */ py::format_descriptor<float>::format(), /* Python struct-style format descriptor */ 2, /* Number of dimensions */ { vec.rows, vec.cols }, /* Buffer dimensions */ { sizeof(float), /* Strides (in bytes) for each index */ sizeof(float) } /* => both sizeof(float), since the data is hold in an array, i.e. contiguous memory */ ); }); py::class_<cv::Vec4f>(eos_module, "Vec4f", "Wrapper for OpenCV's cv::Vec4f type.") .def("__init__", [](cv::Vec4f& vec, py::buffer b) { py::buffer_info info = b.request(); if (info.ndim != 1) throw std::runtime_error("Buffer ndim is " + std::to_string(info.ndim) + ", please hand a buffer with dimension == 1 to create a Vec4f."); if (info.strides.size() != 1) throw std::runtime_error("strides.size() is " + std::to_string(info.strides.size()) + ", please hand a buffer with strides.size() == 1 to create a Vec4f."); // Todo: Should add a check that checks for default stride sizes, everything else would not work yet I think. if (info.shape.size() != 1) throw std::runtime_error("shape.size() is " + std::to_string(info.shape.size()) + ", please hand a buffer with shape dimension == 1 to create a Vec4f."); if (info.shape[0] != 4) throw std::runtime_error("shape[0] is " + std::to_string(info.shape[0]) + ", please hand a buffer with 4 entries to create a Vec4f."); if (info.format == py::format_descriptor<float>::format()) { cv::Mat temp(1, 4, CV_32FC1, info.ptr); std::cout << temp << std::endl; new (&vec) cv::Vec4f(temp); } else { throw std::runtime_error("Not given a buffer of type float - please hand a buffer of type float to create a Vec4f."); } }) .def_buffer([](cv::Vec4f& vec) -> py::buffer_info { return py::buffer_info( &vec.val, /* Pointer to buffer */ sizeof(float), /* Size of one scalar */ py::format_descriptor<float>::format(), /* Python struct-style format descriptor */ 2, /* Number of dimensions */ { vec.rows, vec.cols }, /* Buffer dimensions */ { sizeof(float), /* Strides (in bytes) for each index */ sizeof(float) } /* => both sizeof(float), since the data is hold in an array, i.e. contiguous memory */ ); }); py::class_<cv::Mat>(eos_module, "Mat", "Wrapper for OpenCV's cv::Mat type (currently only 1-channel matrices are supported and only conversion of CV_32F C++ matrices to Python, and conversion of CV_32FC1 and CV_64FC1 matrices from Python to C++).") // This adds support for creating eos.Mat objects in Python from buffers like NumPy arrays: .def("__init__", [](cv::Mat& mat, py::buffer b) { py::buffer_info info = b.request(); if (info.ndim != 2) throw std::runtime_error("Buffer ndim is " + std::to_string(info.ndim) + ", only buffer dimension == 2 is currently supported."); if (info.strides.size() != 2) throw std::runtime_error("strides.size() is " + std::to_string(info.strides.size()) + ", only strides.size() == 2 is currently supported."); // Todo: Should add a check that checks for default stride sizes, everything else would not work yet I think. if (info.shape.size() != 2) throw std::runtime_error("shape.size() is " + std::to_string(info.shape.size()) + ", only shape dimensions of == 2 are currently supported - i.e. only 2-dimensional matrices with rows and colums."); if (info.format == py::format_descriptor<float>::format()) { new (&mat) cv::Mat(info.shape[0], info.shape[1], CV_32FC1, info.ptr); // uses AUTO_STEP } else if (info.format == py::format_descriptor<double>::format()) { new (&mat) cv::Mat(info.shape[0], info.shape[1], CV_64FC1, info.ptr); // uses AUTO_STEP } else { throw std::runtime_error("Only the cv::Mat types CV_32FC1 and CV_64FC1 are currently supported. If needed, it should not be too hard to add other types."); } }) // This gives cv::Mat a Python buffer interface, so the data can be used as NumPy array in Python: .def_buffer([](cv::Mat& mat) -> py::buffer_info { // Note: Exceptions within def_buffer don't seem to be shown in Python, use cout for now. if (!mat.isContinuous()) { std::string error_msg("Only continuous (contiguous) cv::Mat objects are currently supported."); std::cout << error_msg << std::endl; throw std::runtime_error(error_msg); } // Note: Also stride/step should be 1 too, but I think this is covered by isContinuous(). auto dimensions = mat.dims; if (dimensions != 2) { std::string error_msg("Only cv::Mat objects with dims == 2 are currently supported."); std::cout << error_msg << std::endl; throw std::runtime_error(error_msg); } if (mat.channels() != 1) { std::string error_msg("Only cv::Mat objects with channels() == 1 are currently supported."); std::cout << error_msg << std::endl; throw std::runtime_error(error_msg); } std::size_t rows = mat.rows; std::size_t cols = mat.cols; if (mat.type() == CV_32F) { return py::buffer_info( mat.data, /* Pointer to buffer */ sizeof(float), /* Size of one scalar */ py::format_descriptor<float>::format(), /* Python struct-style format descriptor */ dimensions, /* Number of dimensions */ { rows, cols }, /* Buffer dimensions */ { sizeof(float) * cols, /* Strides (in bytes) for each index */ sizeof(float) } // this way is correct for row-major memory layout (OpenCV) ); } else { std::string error_msg("Only the cv::Mat type CV_32F is currently supported. If needed, it would be easy to add CV_8U and CV_64F."); std::cout << error_msg << std::endl; throw std::runtime_error(error_msg); } // Will never reach here. }) ; /** * Bindings for the eos::morphablemodel namespace: */ py::module morphablemodel_module = eos_module.def_submodule("morphablemodel", "Doc for submodule."); py::class_<morphablemodel::PcaModel>(morphablemodel_module, "PcaModel", "Class representing a PcaModel with a mean, eigenvectors and eigenvalues, as well as a list of triangles to build a mesh.") .def("get_num_principal_components", &morphablemodel::PcaModel::get_num_principal_components, "Returns the number of principal components in the model.") .def("get_data_dimension", &morphablemodel::PcaModel::get_data_dimension, "Returns the dimension of the data, i.e. the number of shape dimensions.") .def("get_triangle_list", &morphablemodel::PcaModel::get_triangle_list, "Returns a list of triangles on how to assemble the vertices into a mesh.") .def("get_mean", &morphablemodel::PcaModel::get_mean, "Returns the mean of the model.") .def("get_mean_at_point", &morphablemodel::PcaModel::get_mean_at_point, "Return the value of the mean at a given vertex index.") .def("draw_sample", (cv::Mat (morphablemodel::PcaModel::*)(std::vector<float>) const)&morphablemodel::PcaModel::draw_sample, "Returns a sample from the model with the given PCA coefficients. The given coefficients should follow a standard normal distribution, i.e. not be \"normalised\" with their eigenvalues/variances.") ; py::class_<morphablemodel::MorphableModel>(morphablemodel_module, "MorphableModel", "A class representing a 3D Morphable Model, consisting of a shape- and colour (albedo) PCA model, as well as texture (uv) coordinates.") .def("get_shape_model", [](const morphablemodel::MorphableModel& m) { return m.get_shape_model(); }, "Returns the PCA shape model of this Morphable Model.") // Not sure if that'll really be const in Python? I think Python does a copy each time this gets called? .def("get_color_model", [](const morphablemodel::MorphableModel& m) { return m.get_color_model(); }, "Returns the PCA colour (albedo) model of this Morphable Model.") ; morphablemodel_module.def("load_model", &morphablemodel::load_model, "Load a Morphable Model from a cereal::BinaryInputArchive (.bin) from the harddisk."); return eos_module.ptr(); }; <commit_msg>Added bindings for blendshapes and &fitting::estimate_orthographic_camera<commit_after>/* * eos - A 3D Morphable Model fitting library written in modern C++11/14. * * File: utils/generate-python-bindings.cpp * * Copyright 2016 Patrik Huber * * 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 "eos/morphablemodel/PcaModel.hpp" #include "eos/morphablemodel/MorphableModel.hpp" #include "eos/morphablemodel/Blendshape.hpp" #include "eos/fitting/nonlinear_camera_estimation.hpp" #include "opencv2/core/core.hpp" #include "pybind11/pybind11.h" #include "pybind11/stl.h" #include <iostream> #include <stdexcept> #include <string> namespace py = pybind11; using namespace eos; /** * Generate python bindings for the eos library using pybind11. */ PYBIND11_PLUGIN(eos) { py::module eos_module("eos", "Python bindings to the eos 3D Morphable Face Model fitting library"); /** * General bindings, for OpenCV vector types and cv::Mat: * - cv::Vec2f * - cv::Vec4f * - cv::Mat (only 1-channel matrices and only conversion of CV_32F C++ matrices to Python, and conversion of CV_32FC1 and CV_64FC1 matrices from Python to C++) */ py::class_<cv::Vec2f>(eos_module, "Vec2f", "Wrapper for OpenCV's cv::Vec2f type.") .def("__init__", [](cv::Vec2f& vec, py::buffer b) { py::buffer_info info = b.request(); if (info.ndim != 1) throw std::runtime_error("Buffer ndim is " + std::to_string(info.ndim) + ", please hand a buffer with dimension == 1 to create a Vec2f."); if (info.strides.size() != 1) throw std::runtime_error("strides.size() is " + std::to_string(info.strides.size()) + ", please hand a buffer with strides.size() == 1 to create a Vec2f."); // Todo: Should add a check that checks for default stride sizes, everything else would not work yet I think. if (info.shape.size() != 1) throw std::runtime_error("shape.size() is " + std::to_string(info.shape.size()) + ", please hand a buffer with shape dimension == 1 to create a Vec2f."); if (info.shape[0] != 2) throw std::runtime_error("shape[0] is " + std::to_string(info.shape[0]) + ", please hand a buffer with 2 entries to create a Vec2f."); if (info.format == py::format_descriptor<float>::format()) { cv::Mat temp(1, 2, CV_32FC1, info.ptr); std::cout << temp << std::endl; new (&vec) cv::Vec2f(temp); } else { throw std::runtime_error("Not given a buffer of type float - please hand a buffer of type float to create a Vec2f."); } }) .def_buffer([](cv::Vec2f& vec) -> py::buffer_info { return py::buffer_info( &vec.val, /* Pointer to buffer */ sizeof(float), /* Size of one scalar */ py::format_descriptor<float>::format(), /* Python struct-style format descriptor */ 2, /* Number of dimensions */ { vec.rows, vec.cols }, /* Buffer dimensions */ { sizeof(float), /* Strides (in bytes) for each index */ sizeof(float) } /* => both sizeof(float), since the data is hold in an array, i.e. contiguous memory */ ); }); py::class_<cv::Vec4f>(eos_module, "Vec4f", "Wrapper for OpenCV's cv::Vec4f type.") .def("__init__", [](cv::Vec4f& vec, py::buffer b) { py::buffer_info info = b.request(); if (info.ndim != 1) throw std::runtime_error("Buffer ndim is " + std::to_string(info.ndim) + ", please hand a buffer with dimension == 1 to create a Vec4f."); if (info.strides.size() != 1) throw std::runtime_error("strides.size() is " + std::to_string(info.strides.size()) + ", please hand a buffer with strides.size() == 1 to create a Vec4f."); // Todo: Should add a check that checks for default stride sizes, everything else would not work yet I think. if (info.shape.size() != 1) throw std::runtime_error("shape.size() is " + std::to_string(info.shape.size()) + ", please hand a buffer with shape dimension == 1 to create a Vec4f."); if (info.shape[0] != 4) throw std::runtime_error("shape[0] is " + std::to_string(info.shape[0]) + ", please hand a buffer with 4 entries to create a Vec4f."); if (info.format == py::format_descriptor<float>::format()) { cv::Mat temp(1, 4, CV_32FC1, info.ptr); std::cout << temp << std::endl; new (&vec) cv::Vec4f(temp); } else { throw std::runtime_error("Not given a buffer of type float - please hand a buffer of type float to create a Vec4f."); } }) .def_buffer([](cv::Vec4f& vec) -> py::buffer_info { return py::buffer_info( &vec.val, /* Pointer to buffer */ sizeof(float), /* Size of one scalar */ py::format_descriptor<float>::format(), /* Python struct-style format descriptor */ 2, /* Number of dimensions */ { vec.rows, vec.cols }, /* Buffer dimensions */ { sizeof(float), /* Strides (in bytes) for each index */ sizeof(float) } /* => both sizeof(float), since the data is hold in an array, i.e. contiguous memory */ ); }); py::class_<cv::Mat>(eos_module, "Mat", "Wrapper for OpenCV's cv::Mat type (currently only 1-channel matrices are supported and only conversion of CV_32F C++ matrices to Python, and conversion of CV_32FC1 and CV_64FC1 matrices from Python to C++).") // This adds support for creating eos.Mat objects in Python from buffers like NumPy arrays: .def("__init__", [](cv::Mat& mat, py::buffer b) { py::buffer_info info = b.request(); if (info.ndim != 2) throw std::runtime_error("Buffer ndim is " + std::to_string(info.ndim) + ", only buffer dimension == 2 is currently supported."); if (info.strides.size() != 2) throw std::runtime_error("strides.size() is " + std::to_string(info.strides.size()) + ", only strides.size() == 2 is currently supported."); // Todo: Should add a check that checks for default stride sizes, everything else would not work yet I think. if (info.shape.size() != 2) throw std::runtime_error("shape.size() is " + std::to_string(info.shape.size()) + ", only shape dimensions of == 2 are currently supported - i.e. only 2-dimensional matrices with rows and colums."); if (info.format == py::format_descriptor<float>::format()) { new (&mat) cv::Mat(info.shape[0], info.shape[1], CV_32FC1, info.ptr); // uses AUTO_STEP } else if (info.format == py::format_descriptor<double>::format()) { new (&mat) cv::Mat(info.shape[0], info.shape[1], CV_64FC1, info.ptr); // uses AUTO_STEP } else { throw std::runtime_error("Only the cv::Mat types CV_32FC1 and CV_64FC1 are currently supported. If needed, it should not be too hard to add other types."); } }) // This gives cv::Mat a Python buffer interface, so the data can be used as NumPy array in Python: .def_buffer([](cv::Mat& mat) -> py::buffer_info { // Note: Exceptions within def_buffer don't seem to be shown in Python, use cout for now. if (!mat.isContinuous()) { std::string error_msg("Only continuous (contiguous) cv::Mat objects are currently supported."); std::cout << error_msg << std::endl; throw std::runtime_error(error_msg); } // Note: Also stride/step should be 1 too, but I think this is covered by isContinuous(). auto dimensions = mat.dims; if (dimensions != 2) { std::string error_msg("Only cv::Mat objects with dims == 2 are currently supported."); std::cout << error_msg << std::endl; throw std::runtime_error(error_msg); } if (mat.channels() != 1) { std::string error_msg("Only cv::Mat objects with channels() == 1 are currently supported."); std::cout << error_msg << std::endl; throw std::runtime_error(error_msg); } std::size_t rows = mat.rows; std::size_t cols = mat.cols; if (mat.type() == CV_32F) { return py::buffer_info( mat.data, /* Pointer to buffer */ sizeof(float), /* Size of one scalar */ py::format_descriptor<float>::format(), /* Python struct-style format descriptor */ dimensions, /* Number of dimensions */ { rows, cols }, /* Buffer dimensions */ { sizeof(float) * cols, /* Strides (in bytes) for each index */ sizeof(float) } // this way is correct for row-major memory layout (OpenCV) ); } else { std::string error_msg("Only the cv::Mat type CV_32F is currently supported. If needed, it would be easy to add CV_8U and CV_64F."); std::cout << error_msg << std::endl; throw std::runtime_error(error_msg); } // Will never reach here. }) ; /** * Bindings for the eos::morphablemodel namespace: * - PcaModel * - MorphableModel * - load_model() */ py::module morphablemodel_module = eos_module.def_submodule("morphablemodel", "Functionality to represent a Morphable Model, its PCA models, and functions to load models and blendshapes."); py::class_<morphablemodel::PcaModel>(morphablemodel_module, "PcaModel", "Class representing a PcaModel with a mean, eigenvectors and eigenvalues, as well as a list of triangles to build a mesh.") .def("get_num_principal_components", &morphablemodel::PcaModel::get_num_principal_components, "Returns the number of principal components in the model.") .def("get_data_dimension", &morphablemodel::PcaModel::get_data_dimension, "Returns the dimension of the data, i.e. the number of shape dimensions.") .def("get_triangle_list", &morphablemodel::PcaModel::get_triangle_list, "Returns a list of triangles on how to assemble the vertices into a mesh.") .def("get_mean", &morphablemodel::PcaModel::get_mean, "Returns the mean of the model.") .def("get_mean_at_point", &morphablemodel::PcaModel::get_mean_at_point, "Return the value of the mean at a given vertex index.") .def("draw_sample", (cv::Mat (morphablemodel::PcaModel::*)(std::vector<float>) const)&morphablemodel::PcaModel::draw_sample, "Returns a sample from the model with the given PCA coefficients. The given coefficients should follow a standard normal distribution, i.e. not be \"normalised\" with their eigenvalues/variances.") ; py::class_<morphablemodel::MorphableModel>(morphablemodel_module, "MorphableModel", "A class representing a 3D Morphable Model, consisting of a shape- and colour (albedo) PCA model, as well as texture (uv) coordinates.") .def("get_shape_model", [](const morphablemodel::MorphableModel& m) { return m.get_shape_model(); }, "Returns the PCA shape model of this Morphable Model.") // Not sure if that'll really be const in Python? I think Python does a copy each time this gets called? .def("get_color_model", [](const morphablemodel::MorphableModel& m) { return m.get_color_model(); }, "Returns the PCA colour (albedo) model of this Morphable Model.") ; morphablemodel_module.def("load_model", &morphablemodel::load_model, "Load a Morphable Model from a cereal::BinaryInputArchive (.bin) from the harddisk."); /** * - Blendshape * - load_blendshapes() */ py::class_<morphablemodel::Blendshape>(morphablemodel_module, "Blendshape", "A class representing a 3D blendshape.") .def_readwrite("name", &morphablemodel::Blendshape::name, "Name of the blendshape.") .def_readwrite("deformation", &morphablemodel::Blendshape::deformation, "A 3m x 1 col-vector (xyzxyz...)', where m is the number of model-vertices. Has the same format as PcaModel::mean.") ; morphablemodel_module.def("load_blendshapes", &morphablemodel::load_blendshapes, "Load a file with blendshapes from a cereal::BinaryInputArchive (.bin) from the harddisk."); /** * Bindings for the eos::fitting namespace: * - RenderingParameters * - estimate_orthographic_camera() */ py::module fitting_module = eos_module.def_submodule("fitting", "Pose and shape fitting of a 3D Morphable Model."); py::class_<fitting::RenderingParameters>(fitting_module, "RenderingParameters", "Represents a set of estimated model parameters (rotation, translation) and camera parameters (viewing frustum). Angles are applied using the RPY convention.") .def_readwrite("r_x", &fitting::RenderingParameters::r_x, "Pitch angle, in radians.") .def_readwrite("r_y", &fitting::RenderingParameters::r_y, "Yaw angle, in radians.") .def_readwrite("r_z", &fitting::RenderingParameters::r_z, "Roll angle, in radians.") .def_readwrite("t_x", &fitting::RenderingParameters::t_x, "Model x translation.") .def_readwrite("t_y", &fitting::RenderingParameters::t_y, "Model y translation.") ; fitting_module.def("estimate_orthographic_camera", &fitting::estimate_orthographic_camera, "This algorithm estimates the rotation angles and translation of the model, as well as the viewing frustum of the camera, given a set of corresponding 2D-3D points."); return eos_module.ptr(); }; <|endoftext|>
<commit_before>#include <QtCore> #include <QMetaObject> #include "priv/quickfluxfunctions.h" #include "qffilter.h" /*! \qmltype Filter \brief Add filter rule to AppListener Filter component listens for the parent's dispatched signal, if a dispatched signal match with its type, it will emit its own "dispatched" signal. Otherwise, it will simply ignore the signal. This component provides an alternative way to filter incoming message which is suitable for making Store component. Example: \code pragma Singleton import QtQuick 2.0 import QuickFlux 1.0 import "../actions" AppListener { id: store property ListModel model: ListModel { } Filter { type: ActionTypes.addTask onDispatched: { model.append({task: message.task}); } } } \endcode It is not suggested to use nested AppListener in a Store component. Because nested AppListener do not share the same AppListener::listenerId, it will be difficult to control the order of message reception between store component. In contrast, Filter share the same listenerId with its parent, and therefore it is a solution for above problem. */ /*! \qmlsignal Filter::dispatched(string type, object message) It is a proxy of parent's dispatched signal. If the parent emits a signal matched with the Filter::type / Filter::types property, it will emit this signal */ QFFilter::QFFilter(QObject *parent) : QObject(parent) { } /*! \qmlproperty string Filter::type These types determine the filtering rule for incoming message. Only type matched will emit the "dispatched" signal. \code AppListener { Filter { type: "action1" onDispatched: { // handle the action } } } \endcode \sa Filter::types */ QString QFFilter::type() const { if (m_types.size() == 0) { return ""; } else { return m_types[0]; } } void QFFilter::setType(const QString &type) { m_types = QStringList() << type; emit typeChanged(); emit typesChanged(); } void QFFilter::classBegin() { } void QFFilter::componentComplete() { QObject* object = parent(); m_engine = qmlEngine(this); if (!object) { qDebug() << "Filter - Disabled due to missing parent."; return; } const QMetaObject* meta = object->metaObject(); if (meta->indexOfSignal("dispatched(QString,QJSValue)") >= 0) { connect(object,SIGNAL(dispatched(QString,QJSValue)), this,SLOT(filter(QString,QJSValue))); } else if (meta->indexOfSignal("dispatched(QString,QVariant)") >= 0) { connect(object,SIGNAL(dispatched(QString,QVariant)), this,SLOT(filter(QString,QVariant))); } else { qDebug() << "Filter - Disabled due to missing dispatched signal in parent object."; return; } } void QFFilter::filter(QString type, QJSValue message) { if (m_types.indexOf(type) >= 0) { QF_PRECHECK_DISPATCH(m_engine.data(), type, message); emit dispatched(type, message); } } void QFFilter::filter(QString type, QVariant message) { if (m_types.indexOf(type) >= 0) { QJSValue value = message.value<QJSValue>(); QF_PRECHECK_DISPATCH(m_engine.data(), type, value); emit dispatched(type, value); } } /*! \qmlproperty array Filter::types These types determine the filtering rule for incoming message. Only type matched will emit the "dispatched" signal. \code AppListener { Filter { types: ["action1", "action2"] onDispatched: { // handle the action } } } \endcode \sa Filter::type */ QStringList QFFilter::types() const { return m_types; } void QFFilter::setTypes(const QStringList &types) { m_types = types; } QQmlListProperty<QObject> QFFilter::children() { return QQmlListProperty<QObject>(qobject_cast<QObject*>(this), m_children); } <commit_msg>Fix a broken build issue on travis<commit_after>#include <QtCore> #include <QMetaObject> #include <QtQml> #include "priv/quickfluxfunctions.h" #include "qffilter.h" /*! \qmltype Filter \brief Add filter rule to AppListener Filter component listens for the parent's dispatched signal, if a dispatched signal match with its type, it will emit its own "dispatched" signal. Otherwise, it will simply ignore the signal. This component provides an alternative way to filter incoming message which is suitable for making Store component. Example: \code pragma Singleton import QtQuick 2.0 import QuickFlux 1.0 import "../actions" AppListener { id: store property ListModel model: ListModel { } Filter { type: ActionTypes.addTask onDispatched: { model.append({task: message.task}); } } } \endcode It is not suggested to use nested AppListener in a Store component. Because nested AppListener do not share the same AppListener::listenerId, it will be difficult to control the order of message reception between store component. In contrast, Filter share the same listenerId with its parent, and therefore it is a solution for above problem. */ /*! \qmlsignal Filter::dispatched(string type, object message) It is a proxy of parent's dispatched signal. If the parent emits a signal matched with the Filter::type / Filter::types property, it will emit this signal */ QFFilter::QFFilter(QObject *parent) : QObject(parent) { } /*! \qmlproperty string Filter::type These types determine the filtering rule for incoming message. Only type matched will emit the "dispatched" signal. \code AppListener { Filter { type: "action1" onDispatched: { // handle the action } } } \endcode \sa Filter::types */ QString QFFilter::type() const { if (m_types.size() == 0) { return ""; } else { return m_types[0]; } } void QFFilter::setType(const QString &type) { m_types = QStringList() << type; emit typeChanged(); emit typesChanged(); } void QFFilter::classBegin() { } void QFFilter::componentComplete() { QObject* object = parent(); m_engine = qmlEngine(this); if (!object) { qDebug() << "Filter - Disabled due to missing parent."; return; } const QMetaObject* meta = object->metaObject(); if (meta->indexOfSignal("dispatched(QString,QJSValue)") >= 0) { connect(object,SIGNAL(dispatched(QString,QJSValue)), this,SLOT(filter(QString,QJSValue))); } else if (meta->indexOfSignal("dispatched(QString,QVariant)") >= 0) { connect(object,SIGNAL(dispatched(QString,QVariant)), this,SLOT(filter(QString,QVariant))); } else { qDebug() << "Filter - Disabled due to missing dispatched signal in parent object."; return; } } void QFFilter::filter(QString type, QJSValue message) { if (m_types.indexOf(type) >= 0) { QF_PRECHECK_DISPATCH(m_engine.data(), type, message); emit dispatched(type, message); } } void QFFilter::filter(QString type, QVariant message) { if (m_types.indexOf(type) >= 0) { QJSValue value = message.value<QJSValue>(); QF_PRECHECK_DISPATCH(m_engine.data(), type, value); emit dispatched(type, value); } } /*! \qmlproperty array Filter::types These types determine the filtering rule for incoming message. Only type matched will emit the "dispatched" signal. \code AppListener { Filter { types: ["action1", "action2"] onDispatched: { // handle the action } } } \endcode \sa Filter::type */ QStringList QFFilter::types() const { return m_types; } void QFFilter::setTypes(const QStringList &types) { m_types = types; } QQmlListProperty<QObject> QFFilter::children() { return QQmlListProperty<QObject>(qobject_cast<QObject*>(this), m_children); } <|endoftext|>
<commit_before>/* * This file is part of dui-keyboard * * * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * Contact: Nokia Corporation (directui@nokia.com) * * If you have questions regarding the use of this file, please contact * Nokia at directui@nokia.com. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1 as published by the Free Software Foundation * and appearing in the file LICENSE.LGPL included in the packaging * of this file. */ #include "layoutmenu.h" #include "duivirtualkeyboardstyle.h" #include <DuiButtonGroup> #ifndef NOCONTROLPANEL #include <DuiControlPanelIf> #endif #include <DuiButton> #include <DuiDialog> #include <DuiGridLayoutPolicy> #include <DuiLabel> #include <DuiLayout> #include <DuiLinearLayoutPolicy> #include <DuiLocale> #include <DuiPopupList> #include <DuiSceneManager> #include <DuiTheme> #include <DuiNamespace> #include <DuiWidget> #include <duireactionmap.h> #include <duiplainwindow.h> #include <QDebug> #include <QGraphicsItemAnimation> #include <QGraphicsLinearLayout> #include <QGraphicsSceneMouseEvent> #include <QPainter> #include <QStringListModel> namespace { //! spacing for language menue items const int Spacing = 10; //! Control panel language page name const QString CpLanguagePage("Language"); }; // FIXME: when menu is shown and a click is made outside it (that is, on the keyboard) // the menu disappears and bottom button isn't shown // FIXME: parent LayoutMenu::LayoutMenu(DuiVirtualKeyboardStyleContainer *style, QGraphicsWidget */* parent */) : styleContainer(style), active(false), savedActive(false), centralWidget(0), titleLabel(0), errorCorrectionLabel(0), errorCorrectionButton(0), layoutListLabel(0), layoutListHeader(0), layoutList(0), languageSettingLabel(0), languageSettingButton(0), keyboardOptionDialog(0), menuWidget(0), mainLayout(0), correctionAndLanguageLandscapeLayout(0) { setObjectName("LayoutMenu"); getStyleValues(); loadLanguageMenu(); } void LayoutMenu::loadLanguageMenu() { //create dialog and widgets centralWidget = new DuiWidget; centralWidget->setGeometry(0, 0, baseSize.width(), baseSize.height() + buttonSize.height()); //% "Keyboard options" keyboardOptionDialog = new DuiDialog(qtTrId("qtn_vkb_keyboard_options"), centralWidget, Dui::NoButton); connect(keyboardOptionDialog, SIGNAL(visibilityChanged(bool)), SLOT(visibilityChangeHandler(bool))); /* Create widgets and put then into the layout policy */ //% "Error correction" errorCorrectionLabel = new DuiLabel(qtTrId("qtn_vkb_error_correction"), centralWidget); errorCorrectionLabel->setAlignment(Qt::AlignCenter); errorCorrectionLabel->setWordWrap(true); //% "On" errorCorrectionButton = new DuiButton(qtTrId("qtn_comm_on"), centralWidget); errorCorrectionButton->setObjectName("MenuToggleButton"); errorCorrectionButton->setCheckable(true); errorCorrectionButton->setChecked(true); errorCorrectionButton->setMaximumWidth(baseSize.width() / 2); connect(errorCorrectionButton, SIGNAL(clicked()), this, SLOT(synchronizeErrorCorrection())); //% "Input language" layoutListLabel = new DuiLabel(qtTrId("qtn_vkb_input_language"), centralWidget); layoutListLabel->setAlignment(Qt::AlignCenter); layoutListHeader = new DuiButton(centralWidget); layoutListHeader->setMaximumWidth(baseSize.width() / 2); layoutList = new DuiPopupList(); layoutList->setItemModel(new QStringListModel()); connect(layoutListHeader, SIGNAL(clicked()), this, SLOT(showLanguageList())); //% "To modify the input languages, go to" languageSettingLabel = new DuiLabel(qtTrId("qtn_vkb_language_setting_label"), centralWidget); languageSettingLabel->setAlignment(Qt::AlignHCenter); //TODO: connect languageSettingButton with language setting //% "Language settings" languageSettingButton = new DuiButton(qtTrId("qtn_vkb_language_setting"), centralWidget); languageSettingButton->setMaximumWidth(baseSize.width() / 2); connect(languageSettingButton, SIGNAL(clicked()), this, SLOT(openLanguageApplet())); //create layout QGraphicsLinearLayout *correctionLayout = new QGraphicsLinearLayout(Qt::Vertical); correctionLayout->setSpacing(Spacing); correctionLayout->addItem(errorCorrectionLabel); correctionLayout->addItem(errorCorrectionButton); correctionLayout->setAlignment(errorCorrectionLabel, Qt::AlignCenter); correctionLayout->setAlignment(errorCorrectionButton, Qt::AlignCenter); QGraphicsLinearLayout *languageLayout = new QGraphicsLinearLayout(Qt::Vertical); languageLayout->setSpacing(Spacing); languageLayout->addItem(layoutListLabel); languageLayout->addItem(layoutListHeader); languageLayout->setAlignment(layoutListLabel, Qt::AlignCenter); languageLayout->setAlignment(layoutListHeader, Qt::AlignCenter); correctionAndLanguageLandscapeLayout = new QGraphicsLinearLayout(Qt::Horizontal); correctionAndLanguageLandscapeLayout->setSpacing(Spacing); correctionAndLanguageLandscapeLayout->addItem(correctionLayout); correctionAndLanguageLandscapeLayout->addItem(languageLayout); QGraphicsLinearLayout *languageSettingLayout = new QGraphicsLinearLayout(Qt::Vertical); languageSettingLayout->setSpacing(Spacing); languageSettingLayout->addItem(languageSettingLabel); languageSettingLayout->addItem(languageSettingButton); languageSettingLayout->setAlignment(languageSettingLabel, Qt::AlignCenter); languageSettingLayout->setAlignment(languageSettingButton, Qt::AlignCenter); mainLayout = new DuiLayout; //for landscape DuiLinearLayoutPolicy *landscapePolicy = new DuiLinearLayoutPolicy(mainLayout, Qt::Vertical); landscapePolicy->setSpacing(2 * Spacing); landscapePolicy->addItem(correctionAndLanguageLandscapeLayout); landscapePolicy->addItem(languageSettingLayout); //for portrait DuiLinearLayoutPolicy *portraitPolicy = new DuiLinearLayoutPolicy(mainLayout, Qt::Vertical); portraitPolicy->setSpacing(2 * Spacing); portraitPolicy->addItem(correctionLayout); portraitPolicy->addItem(languageLayout); portraitPolicy->addItem(languageSettingLayout); centralWidget->setLayout(mainLayout); mainLayout->setLandscapePolicy(landscapePolicy); mainLayout->setPortraitPolicy(portraitPolicy); // layoutList seems to be initially visible before calling appear() layoutList->hide(); } LayoutMenu::~LayoutMenu() { //clear correctionAndLanguageLandscapeLayout manually for (int i = 0; i < correctionAndLanguageLandscapeLayout->count(); i++) correctionAndLanguageLandscapeLayout->removeAt(i); //mainlayout will delete correctionAndLanguageLandscapeLayout within removeItem mainLayout->removeItem(correctionAndLanguageLandscapeLayout); // DuiPopupList does not take ownership of its model if (layoutList->itemModel()) { QAbstractItemModel *model = layoutList->itemModel(); layoutList->setItemModel(0); delete model; } delete languageSettingLabel; delete languageSettingButton; delete titleLabel; delete errorCorrectionLabel; delete errorCorrectionButton; delete menuWidget; delete layoutListLabel; delete layoutListHeader; delete layoutList; // DuiDialog's view will destroy centralWidget delete keyboardOptionDialog; } void LayoutMenu::setLanguageList(const QStringList &titles, int selected) { QStringListModel *model = qobject_cast<QStringListModel *>(layoutList->itemModel()); model->setStringList(titles); QModelIndex index = model->index(selected); layoutList->setCurrentIndex(index); layoutListHeader->setText(index.data().toString()); } void LayoutMenu::show() { if (!active) { active = true; QSize visibleSceneSize = DuiPlainWindow::instance()->visibleSceneSize(); centralWidget->setPos(0, visibleSceneSize.height() - baseSize.height()); DuiPlainWindow::instance()->sceneManager()->execDialog(keyboardOptionDialog); } } void LayoutMenu::visibilityChangeHandler(bool visibility) { if (!visibility) { active = false; emit hidden(); emit regionUpdated(QRegion()); } else { const QSize visibleSceneSize = DuiPlainWindow::instance()->visibleSceneSize(); emit regionUpdated(QRegion(0, 0, visibleSceneSize.width(), visibleSceneSize.height())); } } bool LayoutMenu::isActive() const { return active; } void LayoutMenu::save() { savedActive = active; } void LayoutMenu::restore() { if (savedActive) { savedActive = false; show(); } } void LayoutMenu::getStyleValues() { baseSize = style()->menuSize(); buttonSize = style()->tabButtonSize(); } void LayoutMenu::organizeContent(Dui::Orientation /* orientation */) { getStyleValues(); keyboardOptionDialog->reject(); } void LayoutMenu::enableErrorCorrection() { if (!errorCorrectionButton->isChecked()) { errorCorrectionButton->click(); } } void LayoutMenu::disableErrorCorrection() { if (errorCorrectionButton->isChecked()) { errorCorrectionButton->click(); } } void LayoutMenu::redrawReactionMaps() { if (!keyboardOptionDialog || !keyboardOptionDialog->scene()) return; foreach (QGraphicsView *view, keyboardOptionDialog->scene()->views()) { DuiReactionMap *reactionMap = DuiReactionMap::instance(view); if (!reactionMap) continue; // Clear all with inactive color. reactionMap->setInactiveDrawingValue(); reactionMap->setTransform(QTransform()); reactionMap->fillRectangle(0, 0, reactionMap->width(), reactionMap->height()); // We have no active areas, buttons take care of feedback playing. } } DuiVirtualKeyboardStyleContainer &LayoutMenu::style() { return *styleContainer; } void LayoutMenu::showLanguageList() { if (layoutList && layoutListHeader) { DuiPlainWindow::instance()->sceneManager()->execDialog(layoutList); QModelIndex index = layoutList->currentIndex(); layoutListHeader->setText(index.data(Qt::DisplayRole).toString()); emit languageSelected(index.row()); // QStringListModel has only rows. } } void LayoutMenu::synchronizeErrorCorrection() { if (errorCorrectionButton->isChecked()) { emit errorCorrectionToggled(true); //% "On" errorCorrectionButton->setText(qtTrId("qtn_comm_on")); } else { emit errorCorrectionToggled(false); //% "Off" errorCorrectionButton->setText(qtTrId("qtn_comm_off")); } } void LayoutMenu::openLanguageApplet() { #ifndef NOCONTROLPANEL DuiControlPanelIf *dcpIf = new DuiControlPanelIf(); if (dcpIf->isValid()) { dcpIf->appletPage(CpLanguagePage); } delete dcpIf; dcpIf = NULL; #endif } <commit_msg>Changes: use setCentralWidget for DuiDialog instead of passing in constructor<commit_after>/* * This file is part of dui-keyboard * * * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * Contact: Nokia Corporation (directui@nokia.com) * * If you have questions regarding the use of this file, please contact * Nokia at directui@nokia.com. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1 as published by the Free Software Foundation * and appearing in the file LICENSE.LGPL included in the packaging * of this file. */ #include "layoutmenu.h" #include "duivirtualkeyboardstyle.h" #include <DuiButtonGroup> #ifndef NOCONTROLPANEL #include <DuiControlPanelIf> #endif #include <DuiButton> #include <DuiDialog> #include <DuiGridLayoutPolicy> #include <DuiLabel> #include <DuiLayout> #include <DuiLinearLayoutPolicy> #include <DuiLocale> #include <DuiPopupList> #include <DuiSceneManager> #include <DuiTheme> #include <DuiNamespace> #include <DuiWidget> #include <duireactionmap.h> #include <duiplainwindow.h> #include <QDebug> #include <QGraphicsItemAnimation> #include <QGraphicsLinearLayout> #include <QGraphicsSceneMouseEvent> #include <QPainter> #include <QStringListModel> namespace { //! spacing for language menue items const int Spacing = 10; //! Control panel language page name const QString CpLanguagePage("Language"); }; // FIXME: when menu is shown and a click is made outside it (that is, on the keyboard) // the menu disappears and bottom button isn't shown // FIXME: parent LayoutMenu::LayoutMenu(DuiVirtualKeyboardStyleContainer *style, QGraphicsWidget */* parent */) : styleContainer(style), active(false), savedActive(false), centralWidget(0), titleLabel(0), errorCorrectionLabel(0), errorCorrectionButton(0), layoutListLabel(0), layoutListHeader(0), layoutList(0), languageSettingLabel(0), languageSettingButton(0), keyboardOptionDialog(0), menuWidget(0), mainLayout(0), correctionAndLanguageLandscapeLayout(0) { setObjectName("LayoutMenu"); getStyleValues(); loadLanguageMenu(); } void LayoutMenu::loadLanguageMenu() { //create dialog and widgets centralWidget = new DuiWidget; centralWidget->setGeometry(0, 0, baseSize.width(), baseSize.height() + buttonSize.height()); //% "Keyboard options" keyboardOptionDialog = new DuiDialog(qtTrId("qtn_vkb_keyboard_options"), Dui::NoButton); keyboardOptionDialog->setCentralWidget(centralWidget); connect(keyboardOptionDialog, SIGNAL(visibilityChanged(bool)), SLOT(visibilityChangeHandler(bool))); /* Create widgets and put then into the layout policy */ //% "Error correction" errorCorrectionLabel = new DuiLabel(qtTrId("qtn_vkb_error_correction"), centralWidget); errorCorrectionLabel->setAlignment(Qt::AlignCenter); errorCorrectionLabel->setWordWrap(true); //% "On" errorCorrectionButton = new DuiButton(qtTrId("qtn_comm_on"), centralWidget); errorCorrectionButton->setObjectName("MenuToggleButton"); errorCorrectionButton->setCheckable(true); errorCorrectionButton->setChecked(true); errorCorrectionButton->setMaximumWidth(baseSize.width() / 2); connect(errorCorrectionButton, SIGNAL(clicked()), this, SLOT(synchronizeErrorCorrection())); //% "Input language" layoutListLabel = new DuiLabel(qtTrId("qtn_vkb_input_language"), centralWidget); layoutListLabel->setAlignment(Qt::AlignCenter); layoutListHeader = new DuiButton(centralWidget); layoutListHeader->setMaximumWidth(baseSize.width() / 2); layoutList = new DuiPopupList(); layoutList->setItemModel(new QStringListModel()); connect(layoutListHeader, SIGNAL(clicked()), this, SLOT(showLanguageList())); //% "To modify the input languages, go to" languageSettingLabel = new DuiLabel(qtTrId("qtn_vkb_language_setting_label"), centralWidget); languageSettingLabel->setAlignment(Qt::AlignHCenter); //TODO: connect languageSettingButton with language setting //% "Language settings" languageSettingButton = new DuiButton(qtTrId("qtn_vkb_language_setting"), centralWidget); languageSettingButton->setMaximumWidth(baseSize.width() / 2); connect(languageSettingButton, SIGNAL(clicked()), this, SLOT(openLanguageApplet())); //create layout QGraphicsLinearLayout *correctionLayout = new QGraphicsLinearLayout(Qt::Vertical); correctionLayout->setSpacing(Spacing); correctionLayout->addItem(errorCorrectionLabel); correctionLayout->addItem(errorCorrectionButton); correctionLayout->setAlignment(errorCorrectionLabel, Qt::AlignCenter); correctionLayout->setAlignment(errorCorrectionButton, Qt::AlignCenter); QGraphicsLinearLayout *languageLayout = new QGraphicsLinearLayout(Qt::Vertical); languageLayout->setSpacing(Spacing); languageLayout->addItem(layoutListLabel); languageLayout->addItem(layoutListHeader); languageLayout->setAlignment(layoutListLabel, Qt::AlignCenter); languageLayout->setAlignment(layoutListHeader, Qt::AlignCenter); correctionAndLanguageLandscapeLayout = new QGraphicsLinearLayout(Qt::Horizontal); correctionAndLanguageLandscapeLayout->setSpacing(Spacing); correctionAndLanguageLandscapeLayout->addItem(correctionLayout); correctionAndLanguageLandscapeLayout->addItem(languageLayout); QGraphicsLinearLayout *languageSettingLayout = new QGraphicsLinearLayout(Qt::Vertical); languageSettingLayout->setSpacing(Spacing); languageSettingLayout->addItem(languageSettingLabel); languageSettingLayout->addItem(languageSettingButton); languageSettingLayout->setAlignment(languageSettingLabel, Qt::AlignCenter); languageSettingLayout->setAlignment(languageSettingButton, Qt::AlignCenter); mainLayout = new DuiLayout; //for landscape DuiLinearLayoutPolicy *landscapePolicy = new DuiLinearLayoutPolicy(mainLayout, Qt::Vertical); landscapePolicy->setSpacing(2 * Spacing); landscapePolicy->addItem(correctionAndLanguageLandscapeLayout); landscapePolicy->addItem(languageSettingLayout); //for portrait DuiLinearLayoutPolicy *portraitPolicy = new DuiLinearLayoutPolicy(mainLayout, Qt::Vertical); portraitPolicy->setSpacing(2 * Spacing); portraitPolicy->addItem(correctionLayout); portraitPolicy->addItem(languageLayout); portraitPolicy->addItem(languageSettingLayout); centralWidget->setLayout(mainLayout); mainLayout->setLandscapePolicy(landscapePolicy); mainLayout->setPortraitPolicy(portraitPolicy); // layoutList seems to be initially visible before calling appear() layoutList->hide(); } LayoutMenu::~LayoutMenu() { //clear correctionAndLanguageLandscapeLayout manually for (int i = 0; i < correctionAndLanguageLandscapeLayout->count(); i++) correctionAndLanguageLandscapeLayout->removeAt(i); //mainlayout will delete correctionAndLanguageLandscapeLayout within removeItem mainLayout->removeItem(correctionAndLanguageLandscapeLayout); // DuiPopupList does not take ownership of its model if (layoutList->itemModel()) { QAbstractItemModel *model = layoutList->itemModel(); layoutList->setItemModel(0); delete model; } delete languageSettingLabel; delete languageSettingButton; delete titleLabel; delete errorCorrectionLabel; delete errorCorrectionButton; delete menuWidget; delete layoutListLabel; delete layoutListHeader; delete layoutList; // DuiDialog's view will destroy centralWidget delete keyboardOptionDialog; } void LayoutMenu::setLanguageList(const QStringList &titles, int selected) { QStringListModel *model = qobject_cast<QStringListModel *>(layoutList->itemModel()); model->setStringList(titles); QModelIndex index = model->index(selected); layoutList->setCurrentIndex(index); layoutListHeader->setText(index.data().toString()); } void LayoutMenu::show() { if (!active) { active = true; QSize visibleSceneSize = DuiPlainWindow::instance()->visibleSceneSize(); centralWidget->setPos(0, visibleSceneSize.height() - baseSize.height()); DuiPlainWindow::instance()->sceneManager()->execDialog(keyboardOptionDialog); } } void LayoutMenu::visibilityChangeHandler(bool visibility) { if (!visibility) { active = false; emit hidden(); emit regionUpdated(QRegion()); } else { const QSize visibleSceneSize = DuiPlainWindow::instance()->visibleSceneSize(); emit regionUpdated(QRegion(0, 0, visibleSceneSize.width(), visibleSceneSize.height())); } } bool LayoutMenu::isActive() const { return active; } void LayoutMenu::save() { savedActive = active; } void LayoutMenu::restore() { if (savedActive) { savedActive = false; show(); } } void LayoutMenu::getStyleValues() { baseSize = style()->menuSize(); buttonSize = style()->tabButtonSize(); } void LayoutMenu::organizeContent(Dui::Orientation /* orientation */) { getStyleValues(); keyboardOptionDialog->reject(); } void LayoutMenu::enableErrorCorrection() { if (!errorCorrectionButton->isChecked()) { errorCorrectionButton->click(); } } void LayoutMenu::disableErrorCorrection() { if (errorCorrectionButton->isChecked()) { errorCorrectionButton->click(); } } void LayoutMenu::redrawReactionMaps() { if (!keyboardOptionDialog || !keyboardOptionDialog->scene()) return; foreach (QGraphicsView *view, keyboardOptionDialog->scene()->views()) { DuiReactionMap *reactionMap = DuiReactionMap::instance(view); if (!reactionMap) continue; // Clear all with inactive color. reactionMap->setInactiveDrawingValue(); reactionMap->setTransform(QTransform()); reactionMap->fillRectangle(0, 0, reactionMap->width(), reactionMap->height()); // We have no active areas, buttons take care of feedback playing. } } DuiVirtualKeyboardStyleContainer &LayoutMenu::style() { return *styleContainer; } void LayoutMenu::showLanguageList() { if (layoutList && layoutListHeader) { DuiPlainWindow::instance()->sceneManager()->execDialog(layoutList); QModelIndex index = layoutList->currentIndex(); layoutListHeader->setText(index.data(Qt::DisplayRole).toString()); emit languageSelected(index.row()); // QStringListModel has only rows. } } void LayoutMenu::synchronizeErrorCorrection() { if (errorCorrectionButton->isChecked()) { emit errorCorrectionToggled(true); //% "On" errorCorrectionButton->setText(qtTrId("qtn_comm_on")); } else { emit errorCorrectionToggled(false); //% "Off" errorCorrectionButton->setText(qtTrId("qtn_comm_off")); } } void LayoutMenu::openLanguageApplet() { #ifndef NOCONTROLPANEL DuiControlPanelIf *dcpIf = new DuiControlPanelIf(); if (dcpIf->isValid()) { dcpIf->appletPage(CpLanguagePage); } delete dcpIf; dcpIf = NULL; #endif } <|endoftext|>
<commit_before><commit_msg>FENNEL: (LER-5301) fix handling of EAGAIN failures on io_submit<commit_after><|endoftext|>
<commit_before>#include <gtest/gtest.h> #include "getcomputername.h" TEST(GetComputerName,simple) { char hostname[HOST_NAME_MAX]; std::string hostnameFunctionTest; DWORD hostSize = HOST_NAME_MAX; BOOL getComputerName = GetComputerName(&hostnameFunctionTest[0], &hostSize); BOOL host = gethostname(hostname, sizeof hostname); if(host == 0) { host = TRUE; } else { host = FALSE; } std::string hostnameString(hostname); std::string hostnameStringTest(&hostnameFunctionTest[0]); ASSERT_TRUE(getComputerName == TRUE); ASSERT_EQ(host,TRUE); ASSERT_EQ(hostnameString,hostnameStringTest); }<commit_msg>Added failure casex<commit_after>#include <gtest/gtest.h> #include "getcomputername.h" TEST(GetComputerName,simple) { char hostname[HOST_NAME_MAX]; std::string hostnameFunctionTest; DWORD hostSize = HOST_NAME_MAX; BOOL getComputerName = GetComputerName(&hostnameFunctionTest[0], &hostSize); BOOL host = gethostname(hostname, sizeof hostname); if(host == 0) { host = TRUE; } else { host = FALSE; } std::string hostnameString(hostname); std::string hostnameStringTest(&hostnameFunctionTest[0]); ASSERT_TRUE(getComputerName == TRUE); ASSERT_EQ(host,TRUE); ASSERT_EQ(hostnameString,hostnameStringTest); } TEST(GetComputerName,buffertosmall) { char hostname[HOST_NAME_MAX]; std::string hostnameFunctionTest; DWORD hostSize = 0; BOOL getComputerName = GetComputerName(&hostnameFunctionTest[0], &hostSize); ASSERT_TRUE(getComputerName != 0); }<|endoftext|>
<commit_before>/* * Arm.cpp * * Created on: Jan 13, 2011 * Author: Nick Alberts */ #include "Arm.h" void Arm::control_arm_motor( void *object ) { Arm *instance = (Arm *) object; instance->upperArmAngle = instance->GetTilt(); // Runs when the difference in angles is large enough //TODO: fix kCloseEnough with real value while ( fabs( instance->upperArmangle - instance->arm_control_angle ) < kCloseEnough ) { // Conversion factor is from clicks to angles and k is to fix the angle instance->upperArmAngle = instance->GetTilt(); instance->armMotor.Set( ( instance->arm_control_angle - instance->upperArmAngle ) / 500.0 ); } instance->upperArmMotor.Set( 0.0 ); } // TODO: needs actual arguments and ports Arm::Arm(): armMotor( 4 ), armSolenoidRaise( 1 ), armSolenoidLower( 2 ), armEncoder( 4 ) { lowerArm = false; } void Arm::SetLowerArm( bool position ) { if ( (! lowerArm && position) ) { //fires the arm solenoid armSolenoidRaise->Set( true ); armSolenoidLower->Set( false ); } else if ( lowerArm && ! position ) { armSolenoidLower->Set( true ); armSolenoidRaise->Set( false ); } } void Arm::SetUpperArm( double angle ) { // TODO: Constants and real angle factors if ( ! arm_control_mutex.TryLock() ) { arm_control_thread.Stop(); } arm_control_thread.Start( (void *) this ); arm_control_angle = angle; } // TODO: fix this for real values with actual correction value double Arm::GetTilt() { return armEncoder.Get(); } <commit_msg>This is the rough draft arm code with improved commenting<commit_after>/* * Arm.cpp * * Created on: Jan 13, 2011 * Author: Nick Alberts */ #include "Arm.h" /** * This function runs in the control thread, and continually sets the motors to the correct speed. * The speed is determined by the difference in angle divided by a constant. */ void Arm::control_arm_motor( void *object ) { Arm *instance = (Arm *) object; instance->upperArmAngle = instance->GetTilt(); // Runs when the difference in angles is large enough //TODO: fix kCloseEnough with real value while ( fabs( instance->upperArmangle - instance->arm_control_angle ) < kCloseEnough ) { // Conversion factor is from clicks to angles and k is to fix the angle instance->upperArmAngle = instance->GetTilt(); instance->armMotor.Set( ( instance->arm_control_angle - instance->upperArmAngle ) / 500.0 ); } instance->upperArmMotor.Set( 0.0 ); } // TODO: needs actual arguments and ports /** * constructor for arm class */ Arm::Arm(): armMotor( 4 ), armSolenoidRaise( 1 ), armSolenoidLower( 2 ), armEncoder( 4 ) { lowerArm = false; } /** * THis function sets the lower arm to a boolean position value:true corresponds to raised and false corresponds to lower */ void Arm::SetLowerArm( bool position ) { if ( (! lowerArm && position) ) { //fires the arm solenoid armSolenoidRaise->Set( true ); armSolenoidLower->Set( false ); } else if ( lowerArm && ! position ) { armSolenoidLower->Set( true ); armSolenoidRaise->Set( false ); } } void Arm::SetUpperArm( double angle ) { // TODO: Constants and real angle factors if ( ! arm_control_mutex.TryLock() ) { arm_control_thread.Stop(); } arm_control_thread.Start( (void *) this ); arm_control_angle = angle; } // TODO: fix this for real values with actual correction value double Arm::GetTilt() { return armEncoder.Get(); } <|endoftext|>
<commit_before>#include <numeric> #include <set> #include <arbiter/util/time.hpp> #include <arbiter/arbiter.hpp> #include <arbiter/util/transforms.hpp> #include "config.hpp" #include "gtest/gtest.h" using namespace arbiter; TEST(Env, HomeDir) { std::string home; ASSERT_NO_THROW(home = arbiter::fs::expandTilde("~")); EXPECT_NE(home, "~"); EXPECT_FALSE(home.empty()); } TEST(Arbiter, HttpDerivation) { Arbiter a; EXPECT_TRUE(a.isHttpDerived("http://arbitercpp.com")); EXPECT_FALSE(a.isHttpDerived("~/data")); EXPECT_FALSE(a.isHttpDerived(".")); } TEST(Arbiter, Time) { Time a; Time b(a.str()); EXPECT_EQ(a.str(), b.str()); EXPECT_EQ(a - b, 0); Time x("2016-03-18T03:14:42Z"); Time y("2016-03-18T04:24:54Z"); const int64_t delta(1 * 60 * 60 + 10 * 60 + 12); EXPECT_EQ(y - x, delta); EXPECT_EQ(x - y, -delta); } TEST(Arbiter, Base64) { EXPECT_EQ(crypto::encodeBase64(""), ""); EXPECT_EQ(crypto::encodeBase64("f"), "Zg=="); EXPECT_EQ(crypto::encodeBase64("fo"), "Zm8="); EXPECT_EQ(crypto::encodeBase64("foo"), "Zm9v"); EXPECT_EQ(crypto::encodeBase64("foob"), "Zm9vYg=="); EXPECT_EQ(crypto::encodeBase64("fooba"), "Zm9vYmE="); EXPECT_EQ(crypto::encodeBase64("foobar"), "Zm9vYmFy"); } class DriverTest : public ::testing::TestWithParam<std::string> { }; TEST_P(DriverTest, PutGet) { Arbiter a; const std::string root(GetParam()); const std::string path(root + "test.txt"); const std::string data("Testing path " + path); if (a.isLocal(root)) fs::mkdirp(root); EXPECT_NO_THROW(a.put(path, data)); EXPECT_EQ(a.get(path), data); } TEST_P(DriverTest, HttpRange) { Arbiter a; const std::string root(GetParam()); const std::string path(root + "range.txt"); const std::string data("0123456789"); const std::size_t x(2); const std::size_t y(8); const http::Headers headers{ // The range header is inclusive of the end, so subtract 1 here. { "Range", "bytes=" + std::to_string(x) + "-" + std::to_string(y - 1) } }; if (!a.isHttpDerived(root)) return; EXPECT_NO_THROW(a.put(path, data)); EXPECT_EQ(a.get(path, headers), data.substr(x, y - x)); } TEST_P(DriverTest, Glob) { using Paths = std::set<std::string>; Arbiter a; const std::string rawRoot(GetParam()); // Local directories explicitly prefixed with file:// will be returned // without that prefix, so strip that off. const std::string root( a.isLocal(rawRoot) ? Arbiter::stripType(rawRoot) : rawRoot); const std::string type(Arbiter::getType(root)); // No `ls` for plain HTTP/s. if (type == "http" || type == "https") return; auto put([&a, root](std::string p) { EXPECT_NO_THROW(a.put(root + p, p)); }); if (a.isLocal(root)) { fs::mkdirp(root + "a"); fs::mkdirp(root + "a/b"); } put("one.txt"); put("two.txt"); put("a/one.txt"); put("a/two.txt"); put("a/b/one.txt"); put("a/b/two.txt"); auto resolve([&a, root](std::string p) { const auto v = a.resolve(root + p); return Paths(v.begin(), v.end()); }); auto check([&](std::string p, Paths exp) { const auto got(resolve(p)); EXPECT_GE(got.size(), exp.size()); for (const auto& s : exp) { EXPECT_TRUE(got.count(root + s)) << p << ": " << root << s; } }); // Non-recursive. check("*", Paths { "one.txt", "two.txt" }); check("a/*", Paths { "a/one.txt", "a/two.txt" }); check("a/b/*", Paths { "a/b/one.txt", "a/b/two.txt" }); // Recursive. check("**", Paths { "one.txt", "two.txt", "a/one.txt", "a/two.txt", "a/b/one.txt", "a/b/two.txt" } ); check("a/**", Paths { "a/one.txt", "a/two.txt", "a/b/one.txt", "a/b/two.txt" } ); check("a/b/**", Paths { "a/b/one.txt", "a/b/two.txt" }); // Not globs - files resolve to themselves. check("", Paths { "" }); check("asdf", Paths { "asdf" }); check("asdf.txt", Paths { "asdf.txt" }); } const auto tests = std::accumulate( Config::get().begin(), Config::get().end(), std::vector<std::string>(), [](const std::vector<std::string>& in, const Json::Value& entry) { if (in.empty()) { std::cout << "Testing PUT/GET/LS with:" << std::endl; } auto out(in); const std::string path(entry.asString()); out.push_back(path + (path.back() != '/' ? "/" : "")); std::cout << "\t" << out.back() << std::endl; return out; }); INSTANTIATE_TEST_CASE_P( ConfiguredTests, DriverTest, ::testing::ValuesIn(tests)); int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <commit_msg>Add unix time epoch test.<commit_after>#include <numeric> #include <set> #include <arbiter/util/time.hpp> #include <arbiter/arbiter.hpp> #include <arbiter/util/transforms.hpp> #include "config.hpp" #include "gtest/gtest.h" using namespace arbiter; TEST(Env, HomeDir) { std::string home; ASSERT_NO_THROW(home = arbiter::fs::expandTilde("~")); EXPECT_NE(home, "~"); EXPECT_FALSE(home.empty()); } TEST(Arbiter, HttpDerivation) { Arbiter a; EXPECT_TRUE(a.isHttpDerived("http://arbitercpp.com")); EXPECT_FALSE(a.isHttpDerived("~/data")); EXPECT_FALSE(a.isHttpDerived(".")); } TEST(Arbiter, Time) { Time a; Time b(a.str()); EXPECT_EQ(a.str(), b.str()); EXPECT_EQ(a - b, 0); Time x("2016-03-18T03:14:42Z"); Time y("2016-03-18T04:24:54Z"); const int64_t delta(1 * 60 * 60 + 10 * 60 + 12); EXPECT_EQ(y - x, delta); EXPECT_EQ(x - y, -delta); Time epoch("1970-01-01T00:00:00Z"); EXPECT_EQ(epoch.asUnix(), 0); } TEST(Arbiter, Base64) { EXPECT_EQ(crypto::encodeBase64(""), ""); EXPECT_EQ(crypto::encodeBase64("f"), "Zg=="); EXPECT_EQ(crypto::encodeBase64("fo"), "Zm8="); EXPECT_EQ(crypto::encodeBase64("foo"), "Zm9v"); EXPECT_EQ(crypto::encodeBase64("foob"), "Zm9vYg=="); EXPECT_EQ(crypto::encodeBase64("fooba"), "Zm9vYmE="); EXPECT_EQ(crypto::encodeBase64("foobar"), "Zm9vYmFy"); } class DriverTest : public ::testing::TestWithParam<std::string> { }; TEST_P(DriverTest, PutGet) { Arbiter a; const std::string root(GetParam()); const std::string path(root + "test.txt"); const std::string data("Testing path " + path); if (a.isLocal(root)) fs::mkdirp(root); EXPECT_NO_THROW(a.put(path, data)); EXPECT_EQ(a.get(path), data); } TEST_P(DriverTest, HttpRange) { Arbiter a; const std::string root(GetParam()); const std::string path(root + "range.txt"); const std::string data("0123456789"); const std::size_t x(2); const std::size_t y(8); const http::Headers headers{ // The range header is inclusive of the end, so subtract 1 here. { "Range", "bytes=" + std::to_string(x) + "-" + std::to_string(y - 1) } }; if (!a.isHttpDerived(root)) return; EXPECT_NO_THROW(a.put(path, data)); EXPECT_EQ(a.get(path, headers), data.substr(x, y - x)); } TEST_P(DriverTest, Glob) { using Paths = std::set<std::string>; Arbiter a; const std::string rawRoot(GetParam()); // Local directories explicitly prefixed with file:// will be returned // without that prefix, so strip that off. const std::string root( a.isLocal(rawRoot) ? Arbiter::stripType(rawRoot) : rawRoot); const std::string type(Arbiter::getType(root)); // No `ls` for plain HTTP/s. if (type == "http" || type == "https") return; auto put([&a, root](std::string p) { EXPECT_NO_THROW(a.put(root + p, p)); }); if (a.isLocal(root)) { fs::mkdirp(root + "a"); fs::mkdirp(root + "a/b"); } put("one.txt"); put("two.txt"); put("a/one.txt"); put("a/two.txt"); put("a/b/one.txt"); put("a/b/two.txt"); auto resolve([&a, root](std::string p) { const auto v = a.resolve(root + p); return Paths(v.begin(), v.end()); }); auto check([&](std::string p, Paths exp) { const auto got(resolve(p)); EXPECT_GE(got.size(), exp.size()); for (const auto& s : exp) { EXPECT_TRUE(got.count(root + s)) << p << ": " << root << s; } }); // Non-recursive. check("*", Paths { "one.txt", "two.txt" }); check("a/*", Paths { "a/one.txt", "a/two.txt" }); check("a/b/*", Paths { "a/b/one.txt", "a/b/two.txt" }); // Recursive. check("**", Paths { "one.txt", "two.txt", "a/one.txt", "a/two.txt", "a/b/one.txt", "a/b/two.txt" } ); check("a/**", Paths { "a/one.txt", "a/two.txt", "a/b/one.txt", "a/b/two.txt" } ); check("a/b/**", Paths { "a/b/one.txt", "a/b/two.txt" }); // Not globs - files resolve to themselves. check("", Paths { "" }); check("asdf", Paths { "asdf" }); check("asdf.txt", Paths { "asdf.txt" }); } const auto tests = std::accumulate( Config::get().begin(), Config::get().end(), std::vector<std::string>(), [](const std::vector<std::string>& in, const Json::Value& entry) { if (in.empty()) { std::cout << "Testing PUT/GET/LS with:" << std::endl; } auto out(in); const std::string path(entry.asString()); out.push_back(path + (path.back() != '/' ? "/" : "")); std::cout << "\t" << out.back() << std::endl; return out; }); INSTANTIATE_TEST_CASE_P( ConfiguredTests, DriverTest, ::testing::ValuesIn(tests)); int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <|endoftext|>
<commit_before>#include <new> #include <re2/prog.h> #include <re2/regexp.h> #include "it.h" #include "threads.h" #include "rewriter.h" #if RE2JIT_VM #include "it.vm.cc" #elif __x86_64__ #include "it.x64.cc" #else #error "unsupported target platform, try ENABLE_VM=1" #endif static const std::map<int, std::string> __empty_map; namespace re2jit { it::it(const re2::StringPiece& pattern, int max_mem) : _capturing_groups(NULL) { auto pattern2 = pattern.as_string(); auto pure_re2 = rewrite(pattern2); re2::RegexpStatus status; // Some other parsing options: // re2::Regexp::DotNL -- use `(?s)` instead // re2::Regexp::FoldCase -- use `(?i)` instead // re2::Regexp::NeverCapture -- write `(?:...)`, don't be lazy _regexp = re2::Regexp::Parse(pattern2, re2::Regexp::LikePerl, &status); if (_regexp == NULL) { _error = status.Text(); return; } _bytecode = _regexp->CompileToProg(max_mem / 2); if (_bytecode == NULL) { _error = "out of memory: could not compile regexp"; return; } _native = new (std::nothrow) native{_bytecode}; if (_native == NULL || _native->state == NULL) { _error = "JIT compilation error"; return; } if (pure_re2) { re2::Regexp *r = re2::Regexp::Parse(pattern, re2::Regexp::LikePerl, &status); if (r != NULL) { // don't care if NULL, simply won't use DFA. _forward = r->CompileToProg(max_mem / 4); _reverse = r->CompileToReverseProg(max_mem / 4); r->Decref(); } } } it::~it() { delete _native; delete _bytecode; delete _forward; delete _reverse; delete _capturing_groups.load(); if (_regexp) _regexp->Decref(); } bool it::match(re2::StringPiece text, RE2::Anchor anchor, re2::StringPiece* groups, int ngroups) const { if (!ok()) return 0; unsigned int flags = 0; if (anchor == RE2::ANCHOR_BOTH || _bytecode->anchor_end()) flags |= RE2JIT_ANCHOR_END; if (anchor != RE2::UNANCHORED || _bytecode->anchor_start()) flags |= RE2JIT_ANCHOR_START; else if (_forward && _reverse) { re2::StringPiece found; bool failed = false; bool matched = _forward->SearchDFA(text, text, re2::Prog::kUnanchored, re2::Prog::kFirstMatch, &found, &failed, NULL); if (!failed) { if (!matched) return 0; if (!ngroups) return 1; matched = !_reverse->SearchDFA(found, text, re2::Prog::kAnchored, re2::Prog::kLongestMatch, &found, &failed, NULL); if (!failed && matched) { text = groups[0] = found; flags = RE2JIT_ANCHOR_START | RE2JIT_ANCHOR_END; if (ngroups < 2) return 1; } } } struct rejit_threadset_t nfa; nfa.input = text.data(); nfa.length = text.size(); nfa.groups = 2 * ngroups + 2; nfa.data = _native; nfa.space = _native->space; nfa.entry = _native->entry; nfa.initial = _native->state; nfa.flags = flags; int *gs, r = rejit_thread_dispatch(&nfa, &gs); if (r == 1) for (int i = 0; i < ngroups; i++, gs += 2) { if (gs[1] < 0) groups[i].set((const char *) NULL, 0); else groups[i].set(text.data() + gs[0], gs[1] - gs[0]); } rejit_thread_free(&nfa); return r; } const std::map<int, std::string> &it::named_groups() const { if (!ok()) return __empty_map; auto p = _capturing_groups.load(); if (p == NULL) { auto q = _regexp->CaptureNames(); if (!_capturing_groups.compare_exchange_strong(p, q)) delete q; else if ((p = q) == NULL) return __empty_map; } return *p; } std::string it::lastgroup(const re2::StringPiece *groups, int ngroups) const { if (ngroups < 2 || groups->data() == NULL) return ""; int last = 0; auto map = named_groups(); auto end = groups++->data(); for (int i = 1; i < ngroups; i++, groups++) if (groups->data() >= end) { last = i; end = groups->data() + groups->size(); } auto it = map.find(last); return it == map.end() ? "" : it->second; } } <commit_msg>Construct a new empty map every time.<commit_after>#include <new> #include <re2/prog.h> #include <re2/regexp.h> #include "it.h" #include "threads.h" #include "rewriter.h" #if RE2JIT_VM #include "it.vm.cc" #elif __x86_64__ #include "it.x64.cc" #else #error "unsupported target platform, try ENABLE_VM=1" #endif namespace re2jit { it::it(const re2::StringPiece& pattern, int max_mem) : _capturing_groups(NULL) { auto pattern2 = pattern.as_string(); auto pure_re2 = rewrite(pattern2); re2::RegexpStatus status; // Some other parsing options: // re2::Regexp::DotNL -- use `(?s)` instead // re2::Regexp::FoldCase -- use `(?i)` instead // re2::Regexp::NeverCapture -- write `(?:...)`, don't be lazy _regexp = re2::Regexp::Parse(pattern2, re2::Regexp::LikePerl, &status); if (_regexp == NULL) { _error = status.Text(); return; } _bytecode = _regexp->CompileToProg(max_mem / 2); if (_bytecode == NULL) { _error = "out of memory: could not compile regexp"; return; } _native = new (std::nothrow) native{_bytecode}; if (_native == NULL || _native->state == NULL) { _error = "JIT compilation error"; return; } if (pure_re2) { re2::Regexp *r = re2::Regexp::Parse(pattern, re2::Regexp::LikePerl, &status); if (r != NULL) { // don't care if NULL, simply won't use DFA. _forward = r->CompileToProg(max_mem / 4); _reverse = r->CompileToReverseProg(max_mem / 4); r->Decref(); } } } it::~it() { delete _native; delete _bytecode; delete _forward; delete _reverse; delete _capturing_groups.load(); if (_regexp) _regexp->Decref(); } bool it::match(re2::StringPiece text, RE2::Anchor anchor, re2::StringPiece* groups, int ngroups) const { if (!ok()) return 0; unsigned int flags = 0; if (anchor == RE2::ANCHOR_BOTH || _bytecode->anchor_end()) flags |= RE2JIT_ANCHOR_END; if (anchor != RE2::UNANCHORED || _bytecode->anchor_start()) flags |= RE2JIT_ANCHOR_START; else if (_forward && _reverse) { re2::StringPiece found; bool failed = false; bool matched = _forward->SearchDFA(text, text, re2::Prog::kUnanchored, re2::Prog::kFirstMatch, &found, &failed, NULL); if (!failed) { if (!matched) return 0; if (!ngroups) return 1; matched = !_reverse->SearchDFA(found, text, re2::Prog::kAnchored, re2::Prog::kLongestMatch, &found, &failed, NULL); if (!failed && matched) { text = groups[0] = found; flags = RE2JIT_ANCHOR_START | RE2JIT_ANCHOR_END; if (ngroups < 2) return 1; } } } struct rejit_threadset_t nfa; nfa.input = text.data(); nfa.length = text.size(); nfa.groups = 2 * ngroups + 2; nfa.data = _native; nfa.space = _native->space; nfa.entry = _native->entry; nfa.initial = _native->state; nfa.flags = flags; int *gs, r = rejit_thread_dispatch(&nfa, &gs); if (r == 1) for (int i = 0; i < ngroups; i++, gs += 2) { if (gs[1] < 0) groups[i].set((const char *) NULL, 0); else groups[i].set(text.data() + gs[0], gs[1] - gs[0]); } rejit_thread_free(&nfa); return r; } const std::map<int, std::string> &it::named_groups() const { auto p = _capturing_groups.load(); if (p == NULL) { auto q = _regexp->CaptureNames(); if (q == NULL) q = new std::map<int, std::string>; if (_capturing_groups.compare_exchange_strong(p, q)) return *q; delete q; } return *p; } std::string it::lastgroup(const re2::StringPiece *groups, int ngroups) const { if (ngroups < 2 || groups->data() == NULL) return ""; int last = 0; auto map = named_groups(); auto end = groups++->data(); for (int i = 1; i < ngroups; i++, groups++) if (groups->data() >= end) { last = i; end = groups->data() + groups->size(); } auto it = map.find(last); return it == map.end() ? "" : it->second; } } <|endoftext|>
<commit_before>// Copyright 2020 Google LLC // // 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 "xls/ir/jit_wrapper_generator.h" #include "absl/strings/substitute.h" namespace xls { namespace { // Returns the string representation of the packed view type corresponding to // the given Type. std::string PackedTypeString(const Type& type) { if (type.IsBits()) { return absl::StrCat("PackedBitsView<", type.GetFlatBitCount(), ">"); } else if (type.IsArray()) { const ArrayType* array_type = type.AsArrayOrDie(); std::string element_type_str = PackedTypeString(*array_type->element_type()); return absl::StrFormat("PackedArrayView<%s, %d>", element_type_str, array_type->size()); } else { // Is tuple! const TupleType* tuple_type = type.AsTupleOrDie(); std::vector<std::string> element_type_strs; for (const Type* element_type : tuple_type->element_types()) { element_type_strs.push_back(PackedTypeString(*element_type)); } return absl::StrFormat("PackedTupleView<%s>", absl::StrJoin(element_type_strs, ", ")); } } // Returns true if the given type matches the C float type layout. bool MatchFloat(const Type& type) { if (!type.IsTuple()) { return false; } const TupleType* tuple_type = type.AsTupleOrDie(); auto element_types = tuple_type->element_types(); if (element_types[0]->IsBits() && element_types[0]->GetFlatBitCount() == 23 && element_types[1]->IsBits() && element_types[1]->GetFlatBitCount() == 8 && element_types[2]->IsBits() && element_types[2]->GetFlatBitCount() == 1) { return true; } return false; } // Emits the code necessary to convert a float value to its corresponding // packed view. std::string ConvertFloat(const std::string& name) { return absl::StrCat( "PackedTupleView<PackedBitsView<23>, PackedBitsView<8>, " "PackedBitsView<1>> ", name, "_view(reinterpret_cast<uint8*>(&", name, "), 0)"); } // Determines if the input type matches some other/simpler data type, and if so, // returns it. // Does not currently match > 1 specialization; i.e., if there were two types // that could be specializations of a param. absl::optional<std::string> MatchTypeSpecialization(const Type& type) { // No need at present for anything fancy. Cascading if/else works. if (MatchFloat(type)) { return "float"; } return absl::nullopt; } // Simple matching "driver" for emitting logic to convert a simple type into an // XLS view. // Pretty bare-bones at present, but will be expanded depending on need. absl::optional<std::string> CreateConversion(const std::string& name, const Type& type) { if (MatchFloat(type)) { return ConvertFloat(name); } return absl::nullopt; } // Currently, we only support specialized interfaces if all the params and // returns are specializable, as that's our current use case. // To change this, we'd need to convert any non-specializable Values or // non-packed views into packed views. bool IsSpecializable(const Function& function) { for (const Param* param : function.params()) { const Type& param_type = *param->GetType(); if (!MatchTypeSpecialization(param_type).has_value()) { return false; } } const Type& return_type = *function.return_value()->GetType(); return MatchTypeSpecialization(return_type).has_value(); } // Returns the specialized decl of the given function or an empty string, if not // applicable. std::string CreateDeclSpecialization(const Function& function, std::string prepend_class_name = "") { if (!IsSpecializable(function)) { return ""; } // From here on, we know all elements are specializable, so we can directly // the values out of the absl::optionals. std::vector<std::string> params; for (const Param* param : function.params()) { const Type& param_type = *param->GetType(); std::string specialization = MatchTypeSpecialization(param_type).value(); params.push_back(absl::StrCat(specialization, " ", param->name())); } const Type& return_type = *function.return_value()->GetType(); std::string return_type_string = MatchTypeSpecialization(return_type).value(); if (!prepend_class_name.empty()) { absl::StrAppend(&prepend_class_name, "::"); } return absl::StrFormat("xabsl::StatusOr<%s> %sRun(%s);", return_type_string, prepend_class_name, absl::StrJoin(params, ", ")); } std::string CreateImplSpecialization(const Function& function, absl::string_view class_name) { if (!IsSpecializable(function)) { return ""; } // Get the decl, but remove the trailing semicolon. std::string signature = CreateDeclSpecialization(function, std::string(class_name)); signature.pop_back(); // Convert all "simple" types to their XLS equivalents. std::vector<std::string> param_conversions; std::vector<std::string> param_names; for (const Param* param : function.params()) { // As with decls, we know conversions for all elements are possible, so we // can get values directly from the result absl::optionals. std::string conversion = CreateConversion(param->name(), *param->GetType()).value(); param_conversions.push_back(absl::StrCat(" ", conversion)); param_names.push_back(absl::StrCat(param->name(), "_view")); } // Do the same for the return type - this requires allocating "buffer" space const Type& return_type = *function.return_value()->GetType(); std::string return_spec = MatchTypeSpecialization(return_type).value(); param_conversions.push_back(absl::StrFormat( " %s return_value;\n" " %s", return_spec, CreateConversion("return_value", return_type).value())); param_names.push_back("return_value_view"); return absl::StrFormat(R"(%s { %s; XLS_RETURN_IF_ERROR(jit_->RunWithPackedViews(%s)); return return_value; })", signature, absl::StrJoin(param_conversions, ";\n"), absl::StrJoin(param_names, ", ")); } } // namespace std::string GenerateWrapperHeader(const Function& function, absl::string_view class_name) { // $0 : Class name // $1 : Function params // $2 : Function name // $3 : Packed view params // $4 : Any interfaces for specially-matched types, e.g., an interface that // takes a float for a PackedTupleView<PackedBitsView<23>, ...>. constexpr const char header_template[] = R"(// Automatically-generated file! DO NOT EDIT! #include <memory> #include "absl/status/status.h" #include "xls/common/status/statusor.h" #include "xls/ir/llvm_ir_jit.h" #include "xls/ir/package.h" #include "xls/ir/value.h" #include "xls/ir/value_view.h" namespace xls { // JIT execution wrapper for the $2 XLS IR module. class $0 { public: static xabsl::StatusOr<std::unique_ptr<$0>> Create(); LlvmIrJit* jit() { return jit_.get(); } xabsl::StatusOr<Value> Run($1); absl::Status Run($3); $4 private: $0(std::unique_ptr<Package> package, std::unique_ptr<LlvmIrJit> jit); std::unique_ptr<Package> package_; std::unique_ptr<LlvmIrJit> jit_; }; } // namespace xls )"; std::vector<std::string> params; std::vector<std::string> packed_params; for (const Param* param : function.params()) { params.push_back(absl::StrCat("Value ", param->name())); packed_params.push_back( absl::StrCat(PackedTypeString(*param->GetType()), " ", param->name())); } packed_params.push_back(absl::StrCat( PackedTypeString(*function.return_value()->GetType()), " result")); return absl::Substitute( header_template, class_name, absl::StrJoin(params, ", "), function.name(), absl::StrJoin(packed_params, ", "), CreateDeclSpecialization(function)); } std::string GenerateWrapperSource(const Function& function, absl::string_view class_name, const std::filesystem::path& header_path) { // Use an extra '-' delimiter so we can embed a traditional-looking raw string // in the source. // $0 : Class name // $1 : IR text // $2 : Param list // $3 : Arg list // $4 : Arg list size // $5 : Header path // $6 : Function name (not camelized) // $7 : Packed Run() params // $8 : Packed RunWithPackedViews() arguments // $9 : Specially-matched type implementations (if any) constexpr const char source_template[] = R"-(// Automatically-generated file! DO NOT EDIT! #include "$5" #include "xls/common/status/status_macros.h" #include "xls/ir/ir_parser.h" namespace xls { constexpr const char ir_text[] = R"($1 )"; xabsl::StatusOr<std::unique_ptr<$0>> $0::Create() { XLS_ASSIGN_OR_RETURN(auto package, Parser::ParsePackage(ir_text)); XLS_ASSIGN_OR_RETURN(Function* function, package->GetFunction("$6")); XLS_ASSIGN_OR_RETURN(auto jit, LlvmIrJit::Create(function)); return absl::WrapUnique(new $0(std::move(package), std::move(jit))); } $0::$0(std::unique_ptr<Package> package, std::unique_ptr<LlvmIrJit> jit) : package_(std::move(package)), jit_(std::move(jit)) { } xabsl::StatusOr<Value> $0::Run($2) { Value args[$4] = { $3 }; // Special form to handle zero-argument spans. return jit_->Run(absl::MakeSpan(args, $4)); } absl::Status $0::Run($7) { return jit_->RunWithPackedViews($8); } $9 } // namespace xls )-"; std::vector<std::string> param_list; std::vector<std::string> packed_param_list; for (const Param* param : function.params()) { param_list.push_back(absl::StrCat("Value ", param->name())); packed_param_list.push_back( absl::StrCat(PackedTypeString(*param->GetType()), " ", param->name())); } packed_param_list.push_back(absl::StrCat( PackedTypeString(*function.return_value()->GetType()), " result")); std::string params = absl::StrJoin(param_list, ", "); std::string packed_params = absl::StrJoin(packed_param_list, ", "); std::vector<std::string> arg_list; for (const Param* param : function.params()) { arg_list.push_back(param->name()); } int num_unpacked_args = arg_list.size(); std::string unpacked_args = absl::StrJoin(arg_list, ", "); arg_list.push_back("result"); std::string packed_args = absl::StrJoin(arg_list, ", "); std::string specialization = CreateImplSpecialization(function, class_name); return absl::Substitute( source_template, class_name, function.package()->DumpIr(), params, unpacked_args, num_unpacked_args, header_path.string(), function.name(), packed_params, packed_args, specialization); } GeneratedJitWrapper GenerateJitWrapper( const Function& function, const std::string& class_name, const std::filesystem::path& header_path) { GeneratedJitWrapper wrapper; wrapper.header = GenerateWrapperHeader(function, class_name); wrapper.source = GenerateWrapperSource(function, class_name, header_path); return wrapper; } } // namespace xls <commit_msg>Suppress spurious MSAN warning.<commit_after>// Copyright 2020 Google LLC // // 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 "xls/ir/jit_wrapper_generator.h" #include "absl/strings/substitute.h" namespace xls { namespace { // Returns the string representation of the packed view type corresponding to // the given Type. std::string PackedTypeString(const Type& type) { if (type.IsBits()) { return absl::StrCat("PackedBitsView<", type.GetFlatBitCount(), ">"); } else if (type.IsArray()) { const ArrayType* array_type = type.AsArrayOrDie(); std::string element_type_str = PackedTypeString(*array_type->element_type()); return absl::StrFormat("PackedArrayView<%s, %d>", element_type_str, array_type->size()); } else { // Is tuple! const TupleType* tuple_type = type.AsTupleOrDie(); std::vector<std::string> element_type_strs; for (const Type* element_type : tuple_type->element_types()) { element_type_strs.push_back(PackedTypeString(*element_type)); } return absl::StrFormat("PackedTupleView<%s>", absl::StrJoin(element_type_strs, ", ")); } } // Returns true if the given type matches the C float type layout. bool MatchFloat(const Type& type) { if (!type.IsTuple()) { return false; } const TupleType* tuple_type = type.AsTupleOrDie(); auto element_types = tuple_type->element_types(); if (element_types[0]->IsBits() && element_types[0]->GetFlatBitCount() == 23 && element_types[1]->IsBits() && element_types[1]->GetFlatBitCount() == 8 && element_types[2]->IsBits() && element_types[2]->GetFlatBitCount() == 1) { return true; } return false; } // Emits the code necessary to convert a float value to its corresponding // packed view. std::string ConvertFloat(const std::string& name) { return absl::StrCat( "PackedTupleView<PackedBitsView<23>, PackedBitsView<8>, " "PackedBitsView<1>> ", name, "_view(reinterpret_cast<uint8*>(&", name, "), 0)"); } // Determines if the input type matches some other/simpler data type, and if so, // returns it. // Does not currently match > 1 specialization; i.e., if there were two types // that could be specializations of a param. absl::optional<std::string> MatchTypeSpecialization(const Type& type) { // No need at present for anything fancy. Cascading if/else works. if (MatchFloat(type)) { return "float"; } return absl::nullopt; } // Simple matching "driver" for emitting logic to convert a simple type into an // XLS view. // Pretty bare-bones at present, but will be expanded depending on need. absl::optional<std::string> CreateConversion(const std::string& name, const Type& type) { if (MatchFloat(type)) { return ConvertFloat(name); } return absl::nullopt; } // Currently, we only support specialized interfaces if all the params and // returns are specializable, as that's our current use case. // To change this, we'd need to convert any non-specializable Values or // non-packed views into packed views. bool IsSpecializable(const Function& function) { for (const Param* param : function.params()) { const Type& param_type = *param->GetType(); if (!MatchTypeSpecialization(param_type).has_value()) { return false; } } const Type& return_type = *function.return_value()->GetType(); return MatchTypeSpecialization(return_type).has_value(); } // Returns the specialized decl of the given function or an empty string, if not // applicable. std::string CreateDeclSpecialization(const Function& function, std::string prepend_class_name = "") { if (!IsSpecializable(function)) { return ""; } // From here on, we know all elements are specializable, so we can directly // the values out of the absl::optionals. std::vector<std::string> params; for (const Param* param : function.params()) { const Type& param_type = *param->GetType(); std::string specialization = MatchTypeSpecialization(param_type).value(); params.push_back(absl::StrCat(specialization, " ", param->name())); } const Type& return_type = *function.return_value()->GetType(); std::string return_type_string = MatchTypeSpecialization(return_type).value(); if (!prepend_class_name.empty()) { absl::StrAppend(&prepend_class_name, "::"); } return absl::StrFormat("xabsl::StatusOr<%s> %sRun(%s);", return_type_string, prepend_class_name, absl::StrJoin(params, ", ")); } std::string CreateImplSpecialization(const Function& function, absl::string_view class_name) { if (!IsSpecializable(function)) { return ""; } // Get the decl, but remove the trailing semicolon. std::string signature = CreateDeclSpecialization(function, std::string(class_name)); signature.pop_back(); // Convert all "simple" types to their XLS equivalents. std::vector<std::string> param_conversions; std::vector<std::string> param_names; for (const Param* param : function.params()) { // As with decls, we know conversions for all elements are possible, so we // can get values directly from the result absl::optionals. std::string conversion = CreateConversion(param->name(), *param->GetType()).value(); param_conversions.push_back(absl::StrCat(" ", conversion)); param_names.push_back(absl::StrCat(param->name(), "_view")); } // Do the same for the return type - this requires allocating "buffer" space const Type& return_type = *function.return_value()->GetType(); std::string return_spec = MatchTypeSpecialization(return_type).value(); param_conversions.push_back( absl::StrFormat(" %s return_value;\n" "#if __has_feature(memory_sanitizer)\n" " __msan_unpoison(&return_value, sizeof(%s));\n" "#endif\n" " %s", return_spec, return_spec, CreateConversion("return_value", return_type).value())); param_names.push_back("return_value_view"); return absl::StrFormat(R"(%s { %s; XLS_RETURN_IF_ERROR(jit_->RunWithPackedViews(%s)); return return_value; })", signature, absl::StrJoin(param_conversions, ";\n"), absl::StrJoin(param_names, ", ")); } } // namespace std::string GenerateWrapperHeader(const Function& function, absl::string_view class_name) { // $0 : Class name // $1 : Function params // $2 : Function name // $3 : Packed view params // $4 : Any interfaces for specially-matched types, e.g., an interface that // takes a float for a PackedTupleView<PackedBitsView<23>, ...>. constexpr const char header_template[] = R"(// Automatically-generated file! DO NOT EDIT! #include <memory> #include "absl/status/status.h" #include "xls/common/status/statusor.h" #include "xls/ir/llvm_ir_jit.h" #include "xls/ir/package.h" #include "xls/ir/value.h" #include "xls/ir/value_view.h" namespace xls { // JIT execution wrapper for the $2 XLS IR module. class $0 { public: static xabsl::StatusOr<std::unique_ptr<$0>> Create(); LlvmIrJit* jit() { return jit_.get(); } xabsl::StatusOr<Value> Run($1); absl::Status Run($3); $4 private: $0(std::unique_ptr<Package> package, std::unique_ptr<LlvmIrJit> jit); std::unique_ptr<Package> package_; std::unique_ptr<LlvmIrJit> jit_; }; } // namespace xls )"; std::vector<std::string> params; std::vector<std::string> packed_params; for (const Param* param : function.params()) { params.push_back(absl::StrCat("Value ", param->name())); packed_params.push_back( absl::StrCat(PackedTypeString(*param->GetType()), " ", param->name())); } packed_params.push_back(absl::StrCat( PackedTypeString(*function.return_value()->GetType()), " result")); return absl::Substitute( header_template, class_name, absl::StrJoin(params, ", "), function.name(), absl::StrJoin(packed_params, ", "), CreateDeclSpecialization(function)); } std::string GenerateWrapperSource(const Function& function, absl::string_view class_name, const std::filesystem::path& header_path) { // Use an extra '-' delimiter so we can embed a traditional-looking raw string // in the source. // $0 : Class name // $1 : IR text // $2 : Param list // $3 : Arg list // $4 : Arg list size // $5 : Header path // $6 : Function name (not camelized) // $7 : Packed Run() params // $8 : Packed RunWithPackedViews() arguments // $9 : Specially-matched type implementations (if any) constexpr const char source_template[] = R"-(// Automatically-generated file! DO NOT EDIT! #include "$5" #include "xls/common/status/status_macros.h" #include "xls/ir/ir_parser.h" namespace xls { constexpr const char ir_text[] = R"($1 )"; xabsl::StatusOr<std::unique_ptr<$0>> $0::Create() { XLS_ASSIGN_OR_RETURN(auto package, Parser::ParsePackage(ir_text)); XLS_ASSIGN_OR_RETURN(Function* function, package->GetFunction("$6")); XLS_ASSIGN_OR_RETURN(auto jit, LlvmIrJit::Create(function)); return absl::WrapUnique(new $0(std::move(package), std::move(jit))); } $0::$0(std::unique_ptr<Package> package, std::unique_ptr<LlvmIrJit> jit) : package_(std::move(package)), jit_(std::move(jit)) { } xabsl::StatusOr<Value> $0::Run($2) { Value args[$4] = { $3 }; // Special form to handle zero-argument spans. return jit_->Run(absl::MakeSpan(args, $4)); } absl::Status $0::Run($7) { return jit_->RunWithPackedViews($8); } $9 } // namespace xls )-"; std::vector<std::string> param_list; std::vector<std::string> packed_param_list; for (const Param* param : function.params()) { param_list.push_back(absl::StrCat("Value ", param->name())); packed_param_list.push_back( absl::StrCat(PackedTypeString(*param->GetType()), " ", param->name())); } packed_param_list.push_back(absl::StrCat( PackedTypeString(*function.return_value()->GetType()), " result")); std::string params = absl::StrJoin(param_list, ", "); std::string packed_params = absl::StrJoin(packed_param_list, ", "); std::vector<std::string> arg_list; for (const Param* param : function.params()) { arg_list.push_back(param->name()); } int num_unpacked_args = arg_list.size(); std::string unpacked_args = absl::StrJoin(arg_list, ", "); arg_list.push_back("result"); std::string packed_args = absl::StrJoin(arg_list, ", "); std::string specialization = CreateImplSpecialization(function, class_name); return absl::Substitute( source_template, class_name, function.package()->DumpIr(), params, unpacked_args, num_unpacked_args, header_path.string(), function.name(), packed_params, packed_args, specialization); } GeneratedJitWrapper GenerateJitWrapper( const Function& function, const std::string& class_name, const std::filesystem::path& header_path) { GeneratedJitWrapper wrapper; wrapper.header = GenerateWrapperHeader(function, class_name); wrapper.source = GenerateWrapperSource(function, class_name, header_path); return wrapper; } } // namespace xls <|endoftext|>
<commit_before><commit_msg>Resolves: fdo#87108 crash on saving fodg<commit_after><|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: ximpshow.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: hr $ $Date: 2007-06-27 15:12:13 $ * * 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_XIMPSHOW_HXX #define _XMLOFF_XIMPSHOW_HXX #ifndef _XMLOFF_XMLICTXT_HXX #include <xmloff/xmlictxt.hxx> #endif #ifndef _SDXMLIMP_IMPL_HXX #include "sdxmlimp_impl.hxx" #endif class ShowsImpImpl; ////////////////////////////////////////////////////////////////////////////// // presentations:animations class SdXMLShowsContext : public SvXMLImportContext { ShowsImpImpl* mpImpl; public: TYPEINFO(); SdXMLShowsContext( SdXMLImport& rImport, sal_uInt16 nPrfx, const rtl::OUString& rLocalName, const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList); virtual ~SdXMLShowsContext(); virtual SvXMLImportContext * CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLocalName, const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList ); }; #endif // _XMLOFF_XIMPSHOW_HXX <commit_msg>INTEGRATION: CWS changefileheader (1.3.162); FILE MERGED 2008/04/01 13:04:47 thb 1.3.162.2: #i85898# Stripping all external header guards 2008/03/31 16:28:09 rt 1.3.162.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: ximpshow.hxx,v $ * $Revision: 1.4 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef _XMLOFF_XIMPSHOW_HXX #define _XMLOFF_XIMPSHOW_HXX #include <xmloff/xmlictxt.hxx> #include "sdxmlimp_impl.hxx" class ShowsImpImpl; ////////////////////////////////////////////////////////////////////////////// // presentations:animations class SdXMLShowsContext : public SvXMLImportContext { ShowsImpImpl* mpImpl; public: TYPEINFO(); SdXMLShowsContext( SdXMLImport& rImport, sal_uInt16 nPrfx, const rtl::OUString& rLocalName, const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList); virtual ~SdXMLShowsContext(); virtual SvXMLImportContext * CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLocalName, const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList ); }; #endif // _XMLOFF_XIMPSHOW_HXX <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: logging.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: hr $ $Date: 2003-03-27 18:20:25 $ * * 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_FORMS_LOGGING_HXX #define XMLOFF_FORMS_LOGGING_HXX #ifndef _SAL_TYPES_H_ #include <sal/types.h> #endif #include <stack> namespace rtl { class Logfile; } //......................................................................... namespace xmloff { //......................................................................... #ifdef TIMELOG //===================================================================== //= OStackedLogging //===================================================================== class OStackedLogging { private: ::std::stack< ::rtl::Logfile* > m_aLogger; protected: OStackedLogging() { } protected: void enterContext( const sal_Char* _pContextName ); void leaveTopContext( ); }; #define ENTER_LOG_CONTEXT( name ) enterContext( name ) #define LEAVE_LOG_CONTEXT( ) leaveTopContext( ) #else struct OStackedLogging { }; #define ENTER_LOG_CONTEXT( name ) #define LEAVE_LOG_CONTEXT( ) #endif //......................................................................... } // namespace xmloff //......................................................................... #endif // XMLOFF_FORMS_LOGGING_HXX <commit_msg>INTEGRATION: CWS ooo19126 (1.2.538); FILE MERGED 2005/09/05 14:39:02 rt 1.2.538.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: logging.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2005-09-09 14:14:08 $ * * 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_FORMS_LOGGING_HXX #define XMLOFF_FORMS_LOGGING_HXX #ifndef _SAL_TYPES_H_ #include <sal/types.h> #endif #include <stack> namespace rtl { class Logfile; } //......................................................................... namespace xmloff { //......................................................................... #ifdef TIMELOG //===================================================================== //= OStackedLogging //===================================================================== class OStackedLogging { private: ::std::stack< ::rtl::Logfile* > m_aLogger; protected: OStackedLogging() { } protected: void enterContext( const sal_Char* _pContextName ); void leaveTopContext( ); }; #define ENTER_LOG_CONTEXT( name ) enterContext( name ) #define LEAVE_LOG_CONTEXT( ) leaveTopContext( ) #else struct OStackedLogging { }; #define ENTER_LOG_CONTEXT( name ) #define LEAVE_LOG_CONTEXT( ) #endif //......................................................................... } // namespace xmloff //......................................................................... #endif // XMLOFF_FORMS_LOGGING_HXX <|endoftext|>
<commit_before>// Copyright (c) 2018 The Gulden developers // Authored by: Malcolm MacLeod (mmacleod@gmx.com) // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "chain.h" #include "init.h" #include "rpc/register.h" #include "rpc/server.h" #ifdef ENABLE_WALLET #include "wallet/rpcwallet.h" #endif #include "unity/djinni/cpp/legacy_wallet_result.hpp" #include "unity/djinni/cpp/i_library_controller.hpp" #include <boost/thread.hpp> extern std::string HelpMessage(HelpMessageMode mode) { return ""; } void InitRegisterRPC() { RegisterAllCoreRPCCommands(tableRPC); #ifdef ENABLE_WALLET RegisterWalletRPCCommands(tableRPC); #endif } void ServerInterrupt(boost::thread_group& threadGroup) { //InterruptRPC(); } bool InitRPCWarmup(boost::thread_group& threadGroup) { return true; } /*void SetRPCWarmupFinished() { }*/ /*void RPCNotifyBlockChange(bool ibd, const CBlockIndex * pindex) { }*/ void ServerShutdown(boost::thread_group& threadGroup) { //StopRPC(); } /*void InitRPCMining() { }*/ bool InitTor(boost::thread_group& threadGroup, CScheduler& scheduler) { return true; } bool ILibraryController::InitWalletFromAndroidLegacyProtoWallet(const std::string& walletFile, const std::string& oldPassword, const std::string& newPassword) { // only exists here to keep the compiler happy, never call this on iOS LogPrintf("DO NOT call ILibraryController::InitWalletFromAndroidLegacyProtoWallet on iOS\n"); assert(false); } LegacyWalletResult ILibraryController::isValidAndroidLegacyProtoWallet(const std::string& walletFile, const std::string& oldPassword) { // only exists here to keep the compiler happy, never call this on iOS LogPrintf("DO NOT call ILibraryController::isValidAndroidLegacyProtoWallet on iOS\n"); assert(false); return LegacyWalletResult::INVALID_OR_CORRUPT; } <commit_msg>ELECTRON: Fix RPC timeout on walletpassphrase<commit_after>// Copyright (c) 2018 The Gulden developers // Authored by: Malcolm MacLeod (mmacleod@gmx.com) // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "chain.h" #include "init.h" #include "rpc/register.h" #include "rpc/server.h" #ifdef ENABLE_WALLET #include "wallet/rpcwallet.h" #endif #include "unity/djinni/cpp/legacy_wallet_result.hpp" #include "unity/djinni/cpp/i_library_controller.hpp" #include <boost/thread.hpp> #include <thread> class NodeRPCTimer : public RPCTimerBase { public: NodeRPCTimer(std::function<void(void)>& func, int64_t millis) { std::thread([=]() { MilliSleep(millis); func(); }).detach(); } private: }; class NodeRPCTimerInterface : public RPCTimerInterface { public: NodeRPCTimerInterface() { } const char* Name() { return "Node"; } RPCTimerBase* NewTimer(std::function<void(void)>& func, int64_t millis) { return new NodeRPCTimer(func, millis); } private: }; extern std::string HelpMessage(HelpMessageMode mode) { return ""; } NodeRPCTimerInterface* timerInterface = nullptr; void InitRegisterRPC() { RegisterAllCoreRPCCommands(tableRPC); #ifdef ENABLE_WALLET RegisterWalletRPCCommands(tableRPC); #endif timerInterface = new NodeRPCTimerInterface(); RPCSetTimerInterface(timerInterface); } void ServerInterrupt(boost::thread_group& threadGroup) { //InterruptRPC(); } bool InitRPCWarmup(boost::thread_group& threadGroup) { return true; } /*void SetRPCWarmupFinished() { }*/ /*void RPCNotifyBlockChange(bool ibd, const CBlockIndex * pindex) { }*/ void ServerShutdown(boost::thread_group& threadGroup) { RPCUnsetTimerInterface(timerInterface); //StopRPC(); } /*void InitRPCMining() { }*/ bool InitTor(boost::thread_group& threadGroup, CScheduler& scheduler) { return true; } bool ILibraryController::InitWalletFromAndroidLegacyProtoWallet(const std::string& walletFile, const std::string& oldPassword, const std::string& newPassword) { // only exists here to keep the compiler happy, never call this on iOS LogPrintf("DO NOT call ILibraryController::InitWalletFromAndroidLegacyProtoWallet on iOS\n"); assert(false); } LegacyWalletResult ILibraryController::isValidAndroidLegacyProtoWallet(const std::string& walletFile, const std::string& oldPassword) { // only exists here to keep the compiler happy, never call this on iOS LogPrintf("DO NOT call ILibraryController::isValidAndroidLegacyProtoWallet on iOS\n"); assert(false); return LegacyWalletResult::INVALID_OR_CORRUPT; } <|endoftext|>
<commit_before>/** * Result * ====== * * Rust's `std::result` in C++17. * * Note: Compile with -std=c++17. */ #include <iostream> #include <variant> #include <optional> template <typename T, typename E> class result { public: result() = delete; ~result() = default; result(const result<T, E>&) = delete; result& operator=(const result<T, E>&) = delete; result(result<T, E>&&) = delete; result& operator=(result<T, E>&&) = delete; explicit constexpr result(const T& v) : v_{v} { } explicit constexpr result(const E& e) : v_{e} { } explicit constexpr result(const E& e, const std::nullopt_t&) : v_{e} { } constexpr auto& val() const noexcept { return std::get<T>(v_); } constexpr auto& err() const noexcept { return std::get<E>(v_); } operator bool() const noexcept { return std::get_if<T>(&v_); } private: std::variant<T, E> v_; }; template <typename T, typename E> constexpr auto ok(const T& v) noexcept { return result<T, E>(v); } template <typename T, typename E> constexpr auto err(const E& e) noexcept { return result<T, E>(e); } template <typename T, typename E> constexpr auto err(const E& e, const std::nullopt_t& nil) noexcept { return result<T, E>(e, nil); } result<int, std::string> foo(bool c) { if (c) { return ok<int, std::string>(42); } else { return err<int, std::string>("failed"); } } int main() { auto a = foo(42); std::cout << std::boolalpha << "a (" << a << ") = "; std::cout << a.val() << std::endl; auto b = foo(2 + 2 == 5); std::cout << std::boolalpha << "b (" << b << ") = "; std::cout << b.err() << std::endl; return 0; } <commit_msg>updated result: updated some Rust-like APIs, but finally not a totally zero-cost abstraction :( too sad<commit_after>/** * Result * ====== * * Rust's `std::result` in C++17. * * Note: Compile with -std=c++17. */ #include <iostream> #include <functional> #include <variant> #include <optional> #include <cassert> template <typename T, typename E> class result { public: result() = delete; ~result() = default; result(const result<T, E>&) = delete; result& operator=(const result<T, E>&) = delete; result(result<T, E>&&) = delete; result& operator=(result<T, E>&&) = delete; template <bool Ok = true> explicit constexpr result(const std::enable_if_t<Ok, T>& v) : v_{v} , ok_{Ok} { /* nop */ } template <bool Ok = false> explicit constexpr result(const std::enable_if_t<!Ok, E>& e, const std::nullopt_t&) : v_{e} , ok_{Ok} { /* nop */ } auto& unwrap() const { if (ok_) { return std::get<0>(v_); } throw err_(); } auto& unwrap_err() const { if (!ok_) { return err_(); } throw std::get<0>(v_); } auto& operator*() const { return unwrap(); } template <typename F> result<T, E> and_then(F f) const { try { auto v = std::get<0>(v_); return f(v); } catch (...) { auto e = err_(); return f(e); } } operator bool() const noexcept { return ok_; } private: constexpr auto& err_() const noexcept { if constexpr (same_type_()) { return std::get<0>(v_); } else { return std::get<1>(v_); } } using same_type_ = std::is_same<T, E>; typename std::conditional< std::is_same_v<T, E>, std::variant<T>, std::variant<T, E> >::type v_; const bool ok_; }; template <typename T, typename E> constexpr auto ok(const T& v) noexcept { return result<T, E>(v); } template <typename T, typename E> constexpr auto err(const E& e) noexcept { return result<T, E>(e, std::nullopt); } template <typename T, typename E> constexpr auto match(const result<T, E>& res) noexcept { return [&] (std::function<void(T)> f, std::function<void(E)> g) { if (res) { f(res.unwrap()); } else { g(res.unwrap_err()); } }; } result<int, std::string> foo(bool c) { if (c) { return ok<int, std::string>(42); } else { return err<int, std::string>("failed"); } } result<std::string, std::string> bar(bool c) { if (c) { return ok<std::string, std::string>("good"); } else { return err<std::string, std::string>("bad"); } } int main() { auto a = foo(1 + 1 == 2); assert(a); assert(a.unwrap() == 42); auto b = foo(2 + 2 == 5); assert(!b); assert(b.unwrap_err() == "failed"); auto c = bar(1); assert(c); assert(c.unwrap() == "good"); auto d = bar(0); assert(!d); assert(d.unwrap_err() == "bad"); std::cout << "sizeof a: " << sizeof a << std::endl; std::cout << "sizeof b: " << sizeof b << std::endl; auto e = ok<int, int>(42); auto f0 = [] (int v) { return ok<int, int>(v + 1); }; auto f1 = [] (int v) { return err<int, int>(v - 1); }; auto ea = e.and_then(f0).and_then(f0); auto eb = e.and_then(f1).and_then(f1); assert(ea.unwrap() == 44); assert(eb.unwrap_err() == 40); match(e)( [] (int v) { std::cout << v + v << std::endl; }, [] (int v) { std::cout << v - v << std::endl; } ); return 0; } <|endoftext|>
<commit_before>// // Copyright (c) 2012, University of Erlangen-Nuremberg // Copyright (c) 2012, Siemens AG // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // #ifndef __MASK_HPP__ #define __MASK_HPP__ #include "iterationspace.hpp" #include "types.hpp" namespace hipacc { class MaskBase { protected: const int size_x, size_y; const int offset_x, offset_y; uchar *domain_space; IterationSpaceBase iteration_space; public: MaskBase(int size_x, int size_y) : size_x(size_x), size_y(size_y), offset_x(size_x/2), offset_y(size_y/2), domain_space(new uchar[size_x*size_y]), iteration_space(size_x, size_y) { assert(size_x>0 && size_y>0 && "Size for Domain must be positive!"); // initialize full domain for (int i = 0; i < size_x*size_y; ++i) { domain_space[i] = 1; } } MaskBase(const MaskBase &mask) : size_x(mask.size_x), size_y(mask.size_y), offset_x(mask.size_x/2), offset_y(mask.size_y/2), domain_space(new uchar[mask.size_x*mask.size_y]), iteration_space(mask.size_x, mask.size_y) { for (int y=0; y<size_y; ++y) { for (int x=0; x<size_x; ++x) { domain_space[y * size_x + x] = mask.domain_space[y * size_x + x]; } } } ~MaskBase() { if (domain_space != nullptr) { delete[] domain_space; domain_space = nullptr; } } int getSizeX() const { return size_x; } int getSizeY() const { return size_y; } virtual int getX() = 0; virtual int getY() = 0; friend class Domain; template<typename> friend class Mask; }; class Domain : public MaskBase { public: class DomainIterator : public ElementIterator { private: uchar *domain_space; public: DomainIterator(int width=0, int height=0, int offsetx=0, int offsety=0, const IterationSpaceBase *iterspace=nullptr, uchar *domain_space=nullptr) : ElementIterator(width, height, offsetx, offsety, iterspace), domain_space(domain_space) { if (domain_space != nullptr) { // set current coordinate before domain coord.x = min_x-1; coord.y = min_y; // use increment to search first non-zero value ++(*this); } } ~DomainIterator() {} // increment so we iterate over elements in a block DomainIterator &operator++() { do { if (iteration_space) { coord.x++; if (coord.x >= max_x) { coord.x = min_x; coord.y++; if (coord.y >= max_y) { iteration_space = nullptr; } } } } while (nullptr != iteration_space && (nullptr == domain_space || 0 == domain_space[(coord.y-min_y) * (max_x-min_x) + (coord.x-min_x)])); return *this; } }; // Helper class: Force Domain assignment // D(1, 1) = 0; // to be an CXXOperatorCallExpr, which is easier to track. class DomainSetter { friend class Domain; private: uchar *domain_space; unsigned int pos; DomainSetter(uchar *domain_space, unsigned int pos) : domain_space(domain_space), pos(pos) { } public: DomainSetter &operator=(const uchar val) { domain_space[pos] = val; return *this; } }; protected: DomainIterator *DI; public: Domain(int size_x, int size_y) : MaskBase(size_x, size_y), DI(nullptr) {} template <int size_y, int size_x> Domain(const uchar (&domain)[size_y][size_x]) : MaskBase(size_x, size_y), DI(nullptr) {} Domain(const MaskBase &mask) : MaskBase(mask), DI(nullptr) {} Domain(const Domain &domain) : MaskBase(domain), DI(domain.DI) {} ~Domain() {} int getX() { assert(DI && "DomainIterator for Domain not set!"); return DI->getX(); } int getY() { assert(DI && "DomainIterator for Domain not set!"); return DI->getY(); } DomainSetter operator()(const int xf, const int yf) { assert(xf+offset_x < size_x && yf+offset_y < size_y && "out of bounds Domain access."); return DomainSetter(domain_space, (yf+offset_y)*size_x + xf+offset_x); } Domain &operator=(const uchar *other) { for (int y=0; y<size_y; ++y) { for (int x=0; x<size_x; ++x) { domain_space[y * size_x + x] = other[y * size_x + x]; } } return *this; } void operator=(const Domain &dom) { assert(size_x==dom.getSizeX() && size_y==dom.getSizeY() && "Domain sizes must be equal."); for (int y=0; y<size_y; ++y) { for (int x=0; x<size_x; ++x) { domain_space[y * size_x + x] = dom.domain_space[y * size_x + x]; } } } void operator=(const MaskBase &mask) { assert(size_x==mask.getSizeX() && size_y==mask.getSizeY() && "Domain and Mask size must be equal."); for (int y=0; y<size_y; ++y) { for (int x=0; x<size_x; ++x) { domain_space[y * size_x + x] = mask.domain_space[y * size_x + x]; } } } void setDI(DomainIterator *di) { DI = di; } DomainIterator begin() const { return DomainIterator(size_x, size_y, offset_x, offset_y, &iteration_space, domain_space); } DomainIterator end() const { return DomainIterator(); } }; template<typename data_t> class Mask : public MaskBase { private: ElementIterator *EI; data_t *array; template <int size_y, int size_x> void init(const data_t (&mask)[size_y][size_x]) { for (int y=0; y<size_y; ++y) { for (int x=0; x<size_x; ++x) { array[y*size_x + x] = mask[y][x]; // set holes in underlying domain_space if (mask[y][x] == 0) { domain_space[y*size_x + x] = 0; } else { domain_space[y*size_x + x] = 1; } } } } public: template <int size_y, int size_x> Mask(const data_t (&mask)[size_y][size_x]) : MaskBase(size_x, size_y), EI(nullptr), array(new data_t[size_x*size_y]) { init(mask); } Mask(const Mask &mask) : MaskBase(mask.size_x, mask.size_y), array(new data_t[mask.size_x*mask.size_y]) { init(mask.array); } ~Mask() { if (array != nullptr) { delete[] array; array = nullptr; } } int getX() { assert(EI && "ElementIterator for Mask not set!"); return EI->getX(); } int getY() { assert(EI && "ElementIterator for Mask not set!"); return EI->getY(); } data_t &operator()(void) { assert(EI && "ElementIterator for Mask not set!"); return array[(EI->getY()+offset_y)*size_x + EI->getX()+offset_x]; } data_t &operator()(const int xf, const int yf) { assert(xf+offset_x < size_x && yf+offset_y < size_y && "out of bounds Mask access."); return array[(yf+offset_y)*size_x + xf+offset_x]; } data_t &operator()(Domain &D) { assert(D.getSizeX()==size_x && D.getSizeY()==size_y && "Domain and Mask size must be equal."); return array[(D.getY()+offset_y)*size_x + D.getX()+offset_x]; } void setEI(ElementIterator *ei) { EI = ei; } ElementIterator begin() const { return ElementIterator(size_x, size_y, offset_x, offset_y, &iteration_space); } ElementIterator end() const { return ElementIterator(); } }; } // end namespace hipacc #endif // __MASK_HPP__ <commit_msg>Fix iteration space of Masks & Domains.<commit_after>// // Copyright (c) 2012, University of Erlangen-Nuremberg // Copyright (c) 2012, Siemens AG // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // #ifndef __MASK_HPP__ #define __MASK_HPP__ #include "iterationspace.hpp" #include "types.hpp" namespace hipacc { class MaskBase { protected: const int size_x, size_y; uchar *domain_space; IterationSpaceBase iteration_space; public: MaskBase(int size_x, int size_y) : size_x(size_x), size_y(size_y), domain_space(new uchar[size_x*size_y]), iteration_space(size_x, size_y) { assert(size_x>0 && size_y>0 && "Size for Domain must be positive!"); // initialize full domain for (int i = 0; i < size_x*size_y; ++i) { domain_space[i] = 1; } } MaskBase(const MaskBase &mask) : size_x(mask.size_x), size_y(mask.size_y), domain_space(new uchar[mask.size_x*mask.size_y]), iteration_space(mask.size_x, mask.size_y) { for (int y=0; y<size_y; ++y) { for (int x=0; x<size_x; ++x) { domain_space[y * size_x + x] = mask.domain_space[y * size_x + x]; } } } ~MaskBase() { if (domain_space != nullptr) { delete[] domain_space; domain_space = nullptr; } } int getSizeX() const { return size_x; } int getSizeY() const { return size_y; } virtual int getX() = 0; virtual int getY() = 0; friend class Domain; template<typename> friend class Mask; }; class Domain : public MaskBase { public: class DomainIterator : public ElementIterator { private: uchar *domain_space; public: DomainIterator(int width=0, int height=0, const IterationSpaceBase *iterspace=nullptr, uchar *domain_space=nullptr) : ElementIterator(width, height, 0, 0, iterspace), domain_space(domain_space) { if (domain_space != nullptr) { // set current coordinate before domain coord.x = min_x-1; coord.y = min_y; // use increment to search first non-zero value ++(*this); } } ~DomainIterator() {} // increment so we iterate over elements in a block DomainIterator &operator++() { do { if (iteration_space) { coord.x++; if (coord.x >= max_x) { coord.x = min_x; coord.y++; if (coord.y >= max_y) { iteration_space = nullptr; } } } } while (nullptr != iteration_space && (nullptr == domain_space || 0 == domain_space[(coord.y-min_y) * (max_x-min_x) + (coord.x-min_x)])); return *this; } }; // Helper class: Force Domain assignment // D(1, 1) = 0; // to be an CXXOperatorCallExpr, which is easier to track. class DomainSetter { friend class Domain; private: uchar *domain_space; unsigned int pos; DomainSetter(uchar *domain_space, unsigned int pos) : domain_space(domain_space), pos(pos) { } public: DomainSetter &operator=(const uchar val) { domain_space[pos] = val; return *this; } }; protected: DomainIterator *DI; public: Domain(int size_x, int size_y) : MaskBase(size_x, size_y), DI(nullptr) {} template <int size_y, int size_x> Domain(const uchar (&domain)[size_y][size_x]) : MaskBase(size_x, size_y), DI(nullptr) {} Domain(const MaskBase &mask) : MaskBase(mask), DI(nullptr) {} Domain(const Domain &domain) : MaskBase(domain), DI(domain.DI) {} ~Domain() {} int getX() { assert(DI && "DomainIterator for Domain not set!"); return DI->getX() - size_x/2; } int getY() { assert(DI && "DomainIterator for Domain not set!"); return DI->getY() - size_y/2; } DomainSetter operator()(const int xf, const int yf) { assert(xf < size_x/2 && yf < size_y && "out of bounds Domain access."); return DomainSetter(domain_space, (yf+size_x/2)*size_x + xf+size_x/2); } Domain &operator=(const uchar *other) { for (int y=0; y<size_y; ++y) { for (int x=0; x<size_x; ++x) { domain_space[y * size_x + x] = other[y * size_x + x]; } } return *this; } void operator=(const Domain &dom) { assert(size_x==dom.getSizeX() && size_y==dom.getSizeY() && "Domain sizes must be equal."); for (int y=0; y<size_y; ++y) { for (int x=0; x<size_x; ++x) { domain_space[y * size_x + x] = dom.domain_space[y * size_x + x]; } } } void operator=(const MaskBase &mask) { assert(size_x==mask.getSizeX() && size_y==mask.getSizeY() && "Domain and Mask size must be equal."); for (int y=0; y<size_y; ++y) { for (int x=0; x<size_x; ++x) { domain_space[y * size_x + x] = mask.domain_space[y * size_x + x]; } } } void setDI(DomainIterator *di) { DI = di; } DomainIterator begin() const { return DomainIterator(size_x, size_y, &iteration_space, domain_space); } DomainIterator end() const { return DomainIterator(); } }; template<typename data_t> class Mask : public MaskBase { private: ElementIterator *EI; data_t *array; template <int size_y, int size_x> void init(const data_t (&mask)[size_y][size_x]) { for (int y=0; y<size_y; ++y) { for (int x=0; x<size_x; ++x) { array[y*size_x + x] = mask[y][x]; // set holes in underlying domain_space if (mask[y][x] == 0) { domain_space[y*size_x + x] = 0; } else { domain_space[y*size_x + x] = 1; } } } } public: template <int size_y, int size_x> Mask(const data_t (&mask)[size_y][size_x]) : MaskBase(size_x, size_y), EI(nullptr), array(new data_t[size_x*size_y]) { init(mask); } Mask(const Mask &mask) : MaskBase(mask.size_x, mask.size_y), array(new data_t[mask.size_x*mask.size_y]) { init(mask.array); } ~Mask() { if (array != nullptr) { delete[] array; array = nullptr; } } int getX() { assert(EI && "ElementIterator for Mask not set!"); return EI->getX() - size_x/2; } int getY() { assert(EI && "ElementIterator for Mask not set!"); return EI->getY() - size_y/2; } data_t &operator()(void) { assert(EI && "ElementIterator for Mask not set!"); return array[EI->getY()*size_x + EI->getX()]; } data_t &operator()(const int xf, const int yf) { assert(xf < size_x/2 && yf < size_y/2 && "out of bounds Mask access."); return array[(yf+size_y/2)*size_x + xf+size_x/2]; } data_t &operator()(Domain &D) { assert(D.getSizeX()==size_x && D.getSizeY()==size_y && "Domain and Mask size must be equal."); return array[D.getY()*size_x + D.getX()]; } void setEI(ElementIterator *ei) { EI = ei; } ElementIterator begin() const { return ElementIterator(size_x, size_y, 0, 0, &iteration_space); } ElementIterator end() const { return ElementIterator(); } }; } // end namespace hipacc #endif // __MASK_HPP__ <|endoftext|>
<commit_before>#include "AppController.hpp" #include <future> #include <chrono> #include <sstream> #include <cstdarg> #include <thread> #include <unordered_map> #include <slic3r/GUI/GUI.hpp> #include <ModelArrange.hpp> #include <slic3r/GUI/PresetBundle.hpp> #include <PrintConfig.hpp> #include <Print.hpp> #include <PrintExport.hpp> #include <Geometry.hpp> #include <Model.hpp> #include <Utils.hpp> namespace Slic3r { class AppControllerBoilerplate::PriData { public: std::mutex m; std::thread::id ui_thread; inline explicit PriData(std::thread::id uit): ui_thread(uit) {} }; AppControllerBoilerplate::AppControllerBoilerplate() :pri_data_(new PriData(std::this_thread::get_id())) {} AppControllerBoilerplate::~AppControllerBoilerplate() { pri_data_.reset(); } bool AppControllerBoilerplate::is_main_thread() const { return pri_data_->ui_thread == std::this_thread::get_id(); } namespace GUI { PresetBundle* get_preset_bundle(); } static const PrintObjectStep STEP_SLICE = posSlice; static const PrintObjectStep STEP_PERIMETERS = posPerimeters; static const PrintObjectStep STEP_PREPARE_INFILL = posPrepareInfill; static const PrintObjectStep STEP_INFILL = posInfill; static const PrintObjectStep STEP_SUPPORTMATERIAL = posSupportMaterial; static const PrintStep STEP_SKIRT = psSkirt; static const PrintStep STEP_BRIM = psBrim; static const PrintStep STEP_WIPE_TOWER = psWipeTower; AppControllerBoilerplate::ProgresIndicatorPtr AppControllerBoilerplate::global_progress_indicator() { ProgresIndicatorPtr ret; pri_data_->m.lock(); ret = global_progressind_; pri_data_->m.unlock(); return ret; } void AppControllerBoilerplate::global_progress_indicator( AppControllerBoilerplate::ProgresIndicatorPtr gpri) { pri_data_->m.lock(); global_progressind_ = gpri; pri_data_->m.unlock(); } //void PrintController::make_skirt() //{ // assert(print_ != nullptr); // // prerequisites // for(auto obj : print_->objects) make_perimeters(obj); // for(auto obj : print_->objects) infill(obj); // for(auto obj : print_->objects) gen_support_material(obj); // if(!print_->state.is_done(STEP_SKIRT)) { // print_->state.set_started(STEP_SKIRT); // print_->skirt.clear(); // if(print_->has_skirt()) print_->_make_skirt(); // print_->state.set_done(STEP_SKIRT); // } //} //void PrintController::make_brim() //{ // assert(print_ != nullptr); // // prerequisites // for(auto obj : print_->objects) make_perimeters(obj); // for(auto obj : print_->objects) infill(obj); // for(auto obj : print_->objects) gen_support_material(obj); // make_skirt(); // if(!print_->state.is_done(STEP_BRIM)) { // print_->state.set_started(STEP_BRIM); // // since this method must be idempotent, we clear brim paths *before* // // checking whether we need to generate them // print_->brim.clear(); // if(print_->config.brim_width > 0) print_->_make_brim(); // print_->state.set_done(STEP_BRIM); // } //} //void PrintController::make_wipe_tower() //{ // assert(print_ != nullptr); // // prerequisites // for(auto obj : print_->objects) make_perimeters(obj); // for(auto obj : print_->objects) infill(obj); // for(auto obj : print_->objects) gen_support_material(obj); // make_skirt(); // make_brim(); // if(!print_->state.is_done(STEP_WIPE_TOWER)) { // print_->state.set_started(STEP_WIPE_TOWER); // // since this method must be idempotent, we clear brim paths *before* // // checking whether we need to generate them // print_->brim.clear(); // if(print_->has_wipe_tower()) print_->_make_wipe_tower(); // print_->state.set_done(STEP_WIPE_TOWER); // } //} //void PrintController::slice(PrintObject *pobj) //{ // assert(pobj != nullptr && print_ != nullptr); // if(pobj->state.is_done(STEP_SLICE)) return; // pobj->state.set_started(STEP_SLICE); // pobj->_slice(); // auto msg = pobj->_fix_slicing_errors(); // if(!msg.empty()) report_issue(IssueType::WARN, msg); // // simplify slices if required // if (print_->config.resolution) // pobj->_simplify_slices(scale_(print_->config.resolution)); // if(pobj->layers.empty()) // report_issue(IssueType::ERR, // L("No layers were detected. You might want to repair your " // "STL file(s) or check their size or thickness and retry") // ); // pobj->state.set_done(STEP_SLICE); //} //void PrintController::make_perimeters(PrintObject *pobj) //{ // assert(pobj != nullptr); // slice(pobj); // if (!pobj->state.is_done(STEP_PERIMETERS)) { // pobj->_make_perimeters(); // } //} //void PrintController::infill(PrintObject *pobj) //{ // assert(pobj != nullptr); // make_perimeters(pobj); // if (!pobj->state.is_done(STEP_PREPARE_INFILL)) { // pobj->state.set_started(STEP_PREPARE_INFILL); // pobj->_prepare_infill(); // pobj->state.set_done(STEP_PREPARE_INFILL); // } // pobj->_infill(); //} //void PrintController::gen_support_material(PrintObject *pobj) //{ // assert(pobj != nullptr); // // prerequisites // slice(pobj); // if(!pobj->state.is_done(STEP_SUPPORTMATERIAL)) { // pobj->state.set_started(STEP_SUPPORTMATERIAL); // pobj->clear_support_layers(); // if((pobj->config.support_material || pobj->config.raft_layers > 0) // && pobj->layers.size() > 1) { // pobj->_generate_support_material(); // } // pobj->state.set_done(STEP_SUPPORTMATERIAL); // } //} PrintController::PngExportData PrintController::query_png_export_data(const DynamicPrintConfig& conf) { PngExportData ret; auto zippath = query_destination_path("Output zip file", "*.zip", "out"); ret.zippath = zippath; ret.width_mm = conf.opt_float("display_width"); ret.height_mm = conf.opt_float("display_height"); ret.width_px = conf.opt_int("display_pixels_x"); ret.height_px = conf.opt_int("display_pixels_y"); auto opt_corr = conf.opt<ConfigOptionFloats>("printer_correction"); if(opt_corr) { ret.corr_x = opt_corr->values[0]; ret.corr_y = opt_corr->values[1]; ret.corr_z = opt_corr->values[2]; } ret.exp_time_first_s = conf.opt_float("initial_exposure_time"); ret.exp_time_s = conf.opt_float("exposure_time"); return ret; } void PrintController::slice(AppControllerBoilerplate::ProgresIndicatorPtr pri) { auto st = pri->state(); Slic3r::trace(3, "Starting the slicing process."); pri->update(st+20, L("Generating perimeters")); // for(auto obj : print_->objects) make_perimeters(obj); pri->update(st+60, L("Infilling layers")); // for(auto obj : print_->objects) infill(obj); pri->update(st+70, L("Generating support material")); // for(auto obj : print_->objects) gen_support_material(obj); // pri->message_fmt(L("Weight: %.1fg, Cost: %.1f"), // print_->total_weight, print_->total_cost); pri->state(st+85); pri->update(st+88, L("Generating skirt")); make_skirt(); pri->update(st+90, L("Generating brim")); make_brim(); pri->update(st+95, L("Generating wipe tower")); make_wipe_tower(); pri->update(st+100, L("Done")); // time to make some statistics.. Slic3r::trace(3, L("Slicing process finished.")); } void PrintController::slice() { auto pri = global_progress_indicator(); if(!pri) pri = create_progress_indicator(100, L("Slicing")); slice(pri); } template<> class LayerWriter<Zipper> { Zipper m_zip; public: inline LayerWriter(const std::string& zipfile_path): m_zip(zipfile_path) {} inline void next_entry(const std::string& fname) { m_zip.next_entry(fname); } inline std::string get_name() const { return m_zip.get_name(); } template<class T> inline LayerWriter& operator<<(const T& arg) { m_zip.stream() << arg; return *this; } inline void close() { m_zip.close(); } }; void PrintController::slice_to_png() { using Pointf3 = Vec3d; auto presetbundle = GUI::get_preset_bundle(); assert(presetbundle); auto pt = presetbundle->printers.get_selected_preset().printer_technology(); if(pt != ptSLA) { report_issue(IssueType::ERR, L("Printer technology is not SLA!"), L("Error")); return; } auto conf = presetbundle->full_config(); conf.validate(); auto exd = query_png_export_data(conf); if(exd.zippath.empty()) return; Print *print = print_; try { print->apply_config(conf); print->validate(); } catch(std::exception& e) { report_issue(IssueType::ERR, e.what(), "Error"); return; } // TODO: copy the model and work with the copy only bool correction = false; if(exd.corr_x != 1.0 || exd.corr_y != 1.0 || exd.corr_z != 1.0) { correction = true; // print->invalidate_all_steps(); // for(auto po : print->objects) { // po->model_object()->scale( // Pointf3(exd.corr_x, exd.corr_y, exd.corr_z) // ); // po->model_object()->invalidate_bounding_box(); // po->reload_model_instances(); // po->invalidate_all_steps(); // } } // Turn back the correction scaling on the model. auto scale_back = [this, print, correction, exd]() { if(correction) { // scale the model back // print->invalidate_all_steps(); // for(auto po : print->objects) { // po->model_object()->scale( // Pointf3(1.0/exd.corr_x, 1.0/exd.corr_y, 1.0/exd.corr_z) // ); // po->model_object()->invalidate_bounding_box(); // po->reload_model_instances(); // po->invalidate_all_steps(); // } } }; auto print_bb = print->bounding_box(); Vec2d punsc = unscale(print_bb.size()); // If the print does not fit into the print area we should cry about it. if(px(punsc) > exd.width_mm || py(punsc) > exd.height_mm) { std::stringstream ss; ss << L("Print will not fit and will be truncated!") << "\n" << L("Width needed: ") << px(punsc) << " mm\n" << L("Height needed: ") << py(punsc) << " mm\n"; if(!report_issue(IssueType::WARN_Q, ss.str(), L("Warning"))) { scale_back(); return; } } auto pri = create_progress_indicator( 200, L("Slicing to zipped png files...")); pri->on_cancel([&print](){ print->cancel(); }); try { pri->update(0, L("Slicing...")); slice(pri); } catch (std::exception& e) { report_issue(IssueType::ERR, e.what(), L("Exception occurred")); scale_back(); if(print->canceled()) print->restart(); return; } auto initstate = unsigned(pri->state()); print->set_status_callback([pri, initstate](int st, const std::string& msg) { pri->update(initstate + unsigned(st), msg); }); try { print_to<FilePrinterFormat::PNG, Zipper>( *print, exd.zippath, exd.width_mm, exd.height_mm, exd.width_px, exd.height_px, exd.exp_time_s, exd.exp_time_first_s); } catch (std::exception& e) { report_issue(IssueType::ERR, e.what(), L("Exception occurred")); } scale_back(); if(print->canceled()) print->restart(); print->set_status_default(); } const PrintConfig &PrintController::config() const { return print_->config(); } void ProgressIndicator::message_fmt( const std::string &fmtstr, ...) { std::stringstream ss; va_list args; va_start(args, fmtstr); auto fmt = fmtstr.begin(); while (*fmt != '\0') { if (*fmt == 'd') { int i = va_arg(args, int); ss << i << '\n'; } else if (*fmt == 'c') { // note automatic conversion to integral type int c = va_arg(args, int); ss << static_cast<char>(c) << '\n'; } else if (*fmt == 'f') { double d = va_arg(args, double); ss << d << '\n'; } ++fmt; } va_end(args); message(ss.str()); } void AppController::arrange_model() { using Coord = libnest2d::TCoord<libnest2d::PointImpl>; if(arranging_.load()) return; // to prevent UI reentrancies arranging_.store(true); unsigned count = 0; for(auto obj : model_->objects) count += obj->instances.size(); auto pind = global_progress_indicator(); float pmax = 1.0; if(pind) { pmax = pind->max(); // Set the range of the progress to the object count pind->max(count); pind->on_cancel([this](){ arranging_.store(false); }); } auto dist = print_ctl()->config().min_object_distance(); // Create the arranger config auto min_obj_distance = static_cast<Coord>(dist/SCALING_FACTOR); auto& bedpoints = print_ctl()->config().bed_shape.values; Polyline bed; bed.points.reserve(bedpoints.size()); for(auto& v : bedpoints) bed.append(Point::new_scale(v(0), v(1))); if(pind) pind->update(0, L("Arranging objects...")); try { arr::BedShapeHint hint; // TODO: from Sasha from GUI hint.type = arr::BedShapeType::WHO_KNOWS; arr::arrange(*model_, min_obj_distance, bed, hint, false, // create many piles not just one pile [this, pind, count](unsigned rem) { if(pind) pind->update(count - rem, L("Arranging objects...")); process_events(); }, [this] () { return !arranging_.load(); }); } catch(std::exception& e) { std::cerr << e.what() << std::endl; report_issue(IssueType::ERR, L("Could not arrange model objects! " "Some geometries may be invalid."), L("Exception occurred")); } // Restore previous max value if(pind) { pind->max(pmax); pind->update(0, arranging_.load() ? L("Arranging done.") : L("Arranging canceled.")); pind->on_cancel(/*remove cancel function*/); } arranging_.store(false); } } <commit_msg>png export recovered with the new print object interface.<commit_after>#include "AppController.hpp" #include <future> #include <chrono> #include <sstream> #include <cstdarg> #include <thread> #include <unordered_map> #include <slic3r/GUI/GUI.hpp> #include <ModelArrange.hpp> #include <slic3r/GUI/PresetBundle.hpp> #include <PrintConfig.hpp> #include <Print.hpp> #include <PrintExport.hpp> #include <Geometry.hpp> #include <Model.hpp> #include <Utils.hpp> namespace Slic3r { class AppControllerBoilerplate::PriData { public: std::mutex m; std::thread::id ui_thread; inline explicit PriData(std::thread::id uit): ui_thread(uit) {} }; AppControllerBoilerplate::AppControllerBoilerplate() :pri_data_(new PriData(std::this_thread::get_id())) {} AppControllerBoilerplate::~AppControllerBoilerplate() { pri_data_.reset(); } bool AppControllerBoilerplate::is_main_thread() const { return pri_data_->ui_thread == std::this_thread::get_id(); } namespace GUI { PresetBundle* get_preset_bundle(); } static const PrintObjectStep STEP_SLICE = posSlice; static const PrintObjectStep STEP_PERIMETERS = posPerimeters; static const PrintObjectStep STEP_PREPARE_INFILL = posPrepareInfill; static const PrintObjectStep STEP_INFILL = posInfill; static const PrintObjectStep STEP_SUPPORTMATERIAL = posSupportMaterial; static const PrintStep STEP_SKIRT = psSkirt; static const PrintStep STEP_BRIM = psBrim; static const PrintStep STEP_WIPE_TOWER = psWipeTower; AppControllerBoilerplate::ProgresIndicatorPtr AppControllerBoilerplate::global_progress_indicator() { ProgresIndicatorPtr ret; pri_data_->m.lock(); ret = global_progressind_; pri_data_->m.unlock(); return ret; } void AppControllerBoilerplate::global_progress_indicator( AppControllerBoilerplate::ProgresIndicatorPtr gpri) { pri_data_->m.lock(); global_progressind_ = gpri; pri_data_->m.unlock(); } PrintController::PngExportData PrintController::query_png_export_data(const DynamicPrintConfig& conf) { PngExportData ret; auto zippath = query_destination_path("Output zip file", "*.zip", "out"); ret.zippath = zippath; ret.width_mm = conf.opt_float("display_width"); ret.height_mm = conf.opt_float("display_height"); ret.width_px = conf.opt_int("display_pixels_x"); ret.height_px = conf.opt_int("display_pixels_y"); auto opt_corr = conf.opt<ConfigOptionFloats>("printer_correction"); if(opt_corr) { ret.corr_x = opt_corr->values[0]; ret.corr_y = opt_corr->values[1]; ret.corr_z = opt_corr->values[2]; } ret.exp_time_first_s = conf.opt_float("initial_exposure_time"); ret.exp_time_s = conf.opt_float("exposure_time"); return ret; } void PrintController::slice(AppControllerBoilerplate::ProgresIndicatorPtr pri) { print_->set_status_callback([pri](int st, const std::string& msg){ pri->update(unsigned(st), msg); }); print_->process(); } void PrintController::slice() { auto pri = global_progress_indicator(); if(!pri) pri = create_progress_indicator(100, L("Slicing")); slice(pri); } template<> class LayerWriter<Zipper> { Zipper m_zip; public: inline LayerWriter(const std::string& zipfile_path): m_zip(zipfile_path) {} inline void next_entry(const std::string& fname) { m_zip.next_entry(fname); } inline std::string get_name() const { return m_zip.get_name(); } template<class T> inline LayerWriter& operator<<(const T& arg) { m_zip.stream() << arg; return *this; } inline void close() { m_zip.close(); } }; void PrintController::slice_to_png() { using Pointf3 = Vec3d; auto presetbundle = GUI::get_preset_bundle(); assert(presetbundle); auto pt = presetbundle->printers.get_selected_preset().printer_technology(); if(pt != ptSLA) { report_issue(IssueType::ERR, L("Printer technology is not SLA!"), L("Error")); return; } auto conf = presetbundle->full_config(); conf.validate(); auto exd = query_png_export_data(conf); if(exd.zippath.empty()) return; Print *print = print_; try { print->apply_config(conf); print->validate(); } catch(std::exception& e) { report_issue(IssueType::ERR, e.what(), "Error"); return; } // TODO: copy the model and work with the copy only bool correction = false; if(exd.corr_x != 1.0 || exd.corr_y != 1.0 || exd.corr_z != 1.0) { correction = true; // print->invalidate_all_steps(); // for(auto po : print->objects) { // po->model_object()->scale( // Pointf3(exd.corr_x, exd.corr_y, exd.corr_z) // ); // po->model_object()->invalidate_bounding_box(); // po->reload_model_instances(); // po->invalidate_all_steps(); // } } // Turn back the correction scaling on the model. auto scale_back = [this, print, correction, exd]() { if(correction) { // scale the model back // print->invalidate_all_steps(); // for(auto po : print->objects) { // po->model_object()->scale( // Pointf3(1.0/exd.corr_x, 1.0/exd.corr_y, 1.0/exd.corr_z) // ); // po->model_object()->invalidate_bounding_box(); // po->reload_model_instances(); // po->invalidate_all_steps(); // } } }; auto print_bb = print->bounding_box(); Vec2d punsc = unscale(print_bb.size()); // If the print does not fit into the print area we should cry about it. if(px(punsc) > exd.width_mm || py(punsc) > exd.height_mm) { std::stringstream ss; ss << L("Print will not fit and will be truncated!") << "\n" << L("Width needed: ") << px(punsc) << " mm\n" << L("Height needed: ") << py(punsc) << " mm\n"; if(!report_issue(IssueType::WARN_Q, ss.str(), L("Warning"))) { scale_back(); return; } } auto pri = create_progress_indicator( 200, L("Slicing to zipped png files...")); pri->on_cancel([&print](){ print->cancel(); }); try { pri->update(0, L("Slicing...")); slice(pri); } catch (std::exception& e) { report_issue(IssueType::ERR, e.what(), L("Exception occurred")); scale_back(); if(print->canceled()) print->restart(); return; } auto initstate = unsigned(pri->state()); print->set_status_callback([pri, initstate](int st, const std::string& msg) { pri->update(initstate + unsigned(st), msg); }); try { print_to<FilePrinterFormat::PNG, Zipper>( *print, exd.zippath, exd.width_mm, exd.height_mm, exd.width_px, exd.height_px, exd.exp_time_s, exd.exp_time_first_s); } catch (std::exception& e) { report_issue(IssueType::ERR, e.what(), L("Exception occurred")); } scale_back(); if(print->canceled()) print->restart(); print->set_status_default(); } const PrintConfig &PrintController::config() const { return print_->config(); } void ProgressIndicator::message_fmt( const std::string &fmtstr, ...) { std::stringstream ss; va_list args; va_start(args, fmtstr); auto fmt = fmtstr.begin(); while (*fmt != '\0') { if (*fmt == 'd') { int i = va_arg(args, int); ss << i << '\n'; } else if (*fmt == 'c') { // note automatic conversion to integral type int c = va_arg(args, int); ss << static_cast<char>(c) << '\n'; } else if (*fmt == 'f') { double d = va_arg(args, double); ss << d << '\n'; } ++fmt; } va_end(args); message(ss.str()); } void AppController::arrange_model() { using Coord = libnest2d::TCoord<libnest2d::PointImpl>; if(arranging_.load()) return; // to prevent UI reentrancies arranging_.store(true); unsigned count = 0; for(auto obj : model_->objects) count += obj->instances.size(); auto pind = global_progress_indicator(); float pmax = 1.0; if(pind) { pmax = pind->max(); // Set the range of the progress to the object count pind->max(count); pind->on_cancel([this](){ arranging_.store(false); }); } auto dist = print_ctl()->config().min_object_distance(); // Create the arranger config auto min_obj_distance = static_cast<Coord>(dist/SCALING_FACTOR); auto& bedpoints = print_ctl()->config().bed_shape.values; Polyline bed; bed.points.reserve(bedpoints.size()); for(auto& v : bedpoints) bed.append(Point::new_scale(v(0), v(1))); if(pind) pind->update(0, L("Arranging objects...")); try { arr::BedShapeHint hint; // TODO: from Sasha from GUI hint.type = arr::BedShapeType::WHO_KNOWS; arr::arrange(*model_, min_obj_distance, bed, hint, false, // create many piles not just one pile [this, pind, count](unsigned rem) { if(pind) pind->update(count - rem, L("Arranging objects...")); process_events(); }, [this] () { return !arranging_.load(); }); } catch(std::exception& e) { std::cerr << e.what() << std::endl; report_issue(IssueType::ERR, L("Could not arrange model objects! " "Some geometries may be invalid."), L("Exception occurred")); } // Restore previous max value if(pind) { pind->max(pmax); pind->update(0, arranging_.load() ? L("Arranging done.") : L("Arranging canceled.")); pind->on_cancel(/*remove cancel function*/); } arranging_.store(false); } } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: edws.cxx,v $ * * $Revision: 1.10 $ * * last change: $Author: hr $ $Date: 2007-09-27 08:47: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 * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sw.hxx" #ifndef _WINDOW_HXX //autogen #include <vcl/window.hxx> #endif #ifndef _EDITSH_HXX #include <editsh.hxx> #endif #ifndef _DOC_HXX #include <doc.hxx> #endif #ifndef _PAM_HXX #include <pam.hxx> #endif #ifndef _DOCARY_HXX #include <docary.hxx> #endif #ifndef _ACORRECT_HXX #include <acorrect.hxx> #endif #ifndef _SWTABLE_HXX #include <swtable.hxx> #endif #ifndef _NDTXT_HXX #include <ndtxt.hxx> #endif #ifndef _SWUNDO_HXX #include <swundo.hxx> #endif #ifndef _SW_REWRITER_HXX #include <SwRewriter.hxx> #endif /******************************************************** * Ctor/Dtor ********************************************************/ // verkleideter Copy-Constructor SwEditShell::SwEditShell( SwEditShell& rEdSH, Window *pWindow ) : SwCrsrShell( rEdSH, pWindow ) { } // ctor/dtor SwEditShell::SwEditShell( SwDoc& rDoc, Window *pWindow, const SwViewOption *pOptions ) : SwCrsrShell( rDoc, pWindow, pOptions ) { GetDoc()->DoUndo(true); } SwEditShell::~SwEditShell() // USED { } /****************************************************************************** * sal_Bool SwEditShell::IsModified() const ******************************************************************************/ sal_Bool SwEditShell::IsModified() const { return GetDoc()->IsModified(); } /****************************************************************************** * void SwEditShell::SetModified() ******************************************************************************/ void SwEditShell::SetModified() { GetDoc()->SetModified(); } /****************************************************************************** * void SwEditShell::ResetModified() ******************************************************************************/ void SwEditShell::ResetModified() { GetDoc()->ResetModified(); } void SwEditShell::SetUndoNoResetModified() { GetDoc()->SetModified(); GetDoc()->SetUndoNoResetModified(); } /****************************************************************************** * void SwEditShell::StartAllAction() ******************************************************************************/ void SwEditShell::StartAllAction() { ViewShell *pSh = this; do { if( pSh->IsA( TYPE( SwEditShell ) ) ) ((SwEditShell*)pSh)->StartAction(); else pSh->StartAction(); pSh = (ViewShell *)pSh->GetNext(); } while(pSh != this); } /****************************************************************************** * void SwEditShell::EndAllAction() ******************************************************************************/ void SwEditShell::EndAllAction() { ViewShell *pSh = this; do { if( pSh->IsA( TYPE( SwEditShell ) ) ) ((SwEditShell*)pSh)->EndAction(); else pSh->EndAction(); pSh = (ViewShell *)pSh->GetNext(); } while(pSh != this); } /****************************************************************************** * void SwEditShell::CalcLayout() ******************************************************************************/ void SwEditShell::CalcLayout() { StartAllAction(); ViewShell::CalcLayout(); ViewShell *pSh = this; do { if ( pSh->GetWin() ) pSh->GetWin()->Invalidate(); pSh = (ViewShell*)pSh->GetNext(); } while ( pSh != this ); EndAllAction(); } /****************************************************************************** * Inhaltsform bestimmen, holen ******************************************************************************/ // OPT: wird fuer jedes Attribut gerufen? sal_uInt16 SwEditShell::GetCntType() const { // nur noch am SPoint ist der Inhalt interessant sal_uInt16 nRet = 0; if( IsTableMode() ) nRet = CNT_TXT; else switch( GetCrsr()->GetNode()->GetNodeType() ) { case ND_TEXTNODE: nRet = CNT_TXT; break; case ND_GRFNODE: nRet = CNT_GRF; break; case ND_OLENODE: nRet = CNT_OLE; break; } ASSERT( nRet, ERR_OUTOFSCOPE ); return nRet; } //------------------------------------------------------------------------------ sal_Bool SwEditShell::HasOtherCnt() const { const SwNodes &rNds = GetDoc()->GetNodes(); const SwNode *pNd; return GetDoc()->GetSpzFrmFmts()->Count() || 1 != (( pNd = &rNds.GetEndOfInserts() )->GetIndex() - pNd->StartOfSectionIndex() ) || 1 != (( pNd = &rNds.GetEndOfAutotext() )->GetIndex() - pNd->StartOfSectionIndex() ); } /****************************************************************************** * Zugriffsfunktionen fuer Filename-Behandlung ******************************************************************************/ SwActKontext::SwActKontext(SwEditShell *pShell) : pSh(pShell) { pSh->StartAction(); } SwActKontext::~SwActKontext() { pSh->EndAction(); } /****************************************************************************** * Klasse fuer den automatisierten Aufruf von Start- und * EndCrsrMove(); ******************************************************************************/ SwMvKontext::SwMvKontext(SwEditShell *pShell ) : pSh(pShell) { pSh->SttCrsrMove(); } SwMvKontext::~SwMvKontext() { pSh->EndCrsrMove(); } SwFrmFmt *SwEditShell::GetTableFmt() // OPT: schnellster Test auf Tabelle? { const SwTableNode* pTblNd = IsCrsrInTbl(); return pTblNd ? (SwFrmFmt*)pTblNd->GetTable().GetFrmFmt() : 0; } // OPT: wieso 3x beim neuen Dokument sal_uInt16 SwEditShell::GetTOXTypeCount(TOXTypes eTyp) const { return pDoc->GetTOXTypeCount(eTyp); } void SwEditShell::InsertTOXType(const SwTOXType& rTyp) { pDoc->InsertTOXType(rTyp); } void SwEditShell::DoUndo( sal_Bool bOn ) { GetDoc()->DoUndo( bOn ); } sal_Bool SwEditShell::DoesUndo() const { return GetDoc()->DoesUndo(); } void SwEditShell::DoGroupUndo( sal_Bool bOn ) { GetDoc()->DoGroupUndo( bOn ); } sal_Bool SwEditShell::DoesGroupUndo() const { return GetDoc()->DoesGroupUndo(); } void SwEditShell::DelAllUndoObj() { GetDoc()->DelAllUndoObj(); } // Zusammenfassen von Kontinuierlichen Insert/Delete/Overwrite von // Charaktern. Default ist sdbcx::Group-Undo. // setzt Undoklammerung auf, liefert nUndoId der Klammerung SwUndoId SwEditShell::StartUndo( SwUndoId eUndoId, const SwRewriter *pRewriter ) { return GetDoc()->StartUndo( eUndoId, pRewriter ); } // schliesst Klammerung der nUndoId, nicht vom UI benutzt SwUndoId SwEditShell::EndUndo(SwUndoId eUndoId, const SwRewriter *pRewriter) { return GetDoc()->EndUndo(eUndoId, pRewriter); } // liefert die Id der letzten undofaehigen Aktion zurueck // fuellt ggf. VARARR mit sdbcx::User-UndoIds SwUndoId SwEditShell::GetUndoIds(String* pStr,SwUndoIds *pUndoIds) const { return GetDoc()->GetUndoIds(pStr,pUndoIds); } String SwEditShell::GetUndoIdsStr(String* pStr,SwUndoIds *pUndoIds) const { return GetDoc()->GetUndoIdsStr(pStr,pUndoIds); } // liefert die Id der letzten Redofaehigen Aktion zurueck // fuellt ggf. VARARR mit RedoIds SwUndoId SwEditShell::GetRedoIds(String* pStr,SwUndoIds *pRedoIds) const { return GetDoc()->GetRedoIds(pStr,pRedoIds); } String SwEditShell::GetRedoIdsStr(String* pStr,SwUndoIds *pRedoIds) const { return GetDoc()->GetRedoIdsStr(pStr,pRedoIds); } // liefert die Id der letzten Repeatfaehigen Aktion zurueck // fuellt ggf. VARARR mit RedoIds SwUndoId SwEditShell::GetRepeatIds(String* pStr, SwUndoIds *pRedoIds) const { return GetDoc()->GetRepeatIds(pStr,pRedoIds); } String SwEditShell::GetRepeatIdsStr(String* pStr, SwUndoIds *pRedoIds) const { return GetDoc()->GetRepeatIdsStr(pStr,pRedoIds); } // AutoKorrektur - JP 27.01.94 void SwEditShell::AutoCorrect( SvxAutoCorrect& rACorr, sal_Bool bInsert, sal_Unicode cChar ) { SET_CURR_SHELL( this ); StartAllAction(); SwPaM* pCrsr = GetCrsr(); SwTxtNode* pTNd = pCrsr->GetNode()->GetTxtNode(); SwAutoCorrDoc aSwAutoCorrDoc( *this, *pCrsr, cChar ); rACorr.AutoCorrect( aSwAutoCorrDoc, pTNd->GetTxt(), pCrsr->GetPoint()->nContent.GetIndex(), cChar, bInsert ); if( cChar ) SaveTblBoxCntnt( pCrsr->GetPoint() ); EndAllAction(); } void SwEditShell::SetNewDoc(sal_Bool bNew) { GetDoc()->SetNewDoc(bNew); } sal_Bool SwEditShell::GetPrevAutoCorrWord( SvxAutoCorrect& rACorr, String& rWord ) { SET_CURR_SHELL( this ); sal_Bool bRet; SwPaM* pCrsr = GetCrsr(); xub_StrLen nPos = pCrsr->GetPoint()->nContent.GetIndex(); SwTxtNode* pTNd = pCrsr->GetNode()->GetTxtNode(); if( pTNd && nPos ) { SwAutoCorrDoc aSwAutoCorrDoc( *this, *pCrsr, 0 ); bRet = rACorr.GetPrevAutoCorrWord( aSwAutoCorrDoc, pTNd->GetTxt(), nPos, rWord ); } else bRet = sal_False; return bRet; } SwAutoCompleteWord& SwEditShell::GetAutoCompleteWords() { return SwDoc::GetAutoCompleteWords(); } <commit_msg>INTEGRATION: CWS swcolsel (1.10.34); FILE MERGED 2007/11/08 15:41:49 ama 1.10.34.1: Fix #i83343#: Travel functionality with BlockCursor<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: edws.cxx,v $ * * $Revision: 1.11 $ * * last change: $Author: ihi $ $Date: 2007-11-22 15:34:01 $ * * 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_sw.hxx" #ifndef _WINDOW_HXX //autogen #include <vcl/window.hxx> #endif #ifndef _EDITSH_HXX #include <editsh.hxx> #endif #ifndef _DOC_HXX #include <doc.hxx> #endif #ifndef _PAM_HXX #include <pam.hxx> #endif #ifndef _DOCARY_HXX #include <docary.hxx> #endif #ifndef _ACORRECT_HXX #include <acorrect.hxx> #endif #ifndef _SWTABLE_HXX #include <swtable.hxx> #endif #ifndef _NDTXT_HXX #include <ndtxt.hxx> #endif #ifndef _SWUNDO_HXX #include <swundo.hxx> #endif #ifndef _SW_REWRITER_HXX #include <SwRewriter.hxx> #endif /******************************************************** * Ctor/Dtor ********************************************************/ // verkleideter Copy-Constructor SwEditShell::SwEditShell( SwEditShell& rEdSH, Window *pWindow ) : SwCrsrShell( rEdSH, pWindow ) { } // ctor/dtor SwEditShell::SwEditShell( SwDoc& rDoc, Window *pWindow, const SwViewOption *pOptions ) : SwCrsrShell( rDoc, pWindow, pOptions ) { GetDoc()->DoUndo(true); } SwEditShell::~SwEditShell() // USED { } /****************************************************************************** * sal_Bool SwEditShell::IsModified() const ******************************************************************************/ sal_Bool SwEditShell::IsModified() const { return GetDoc()->IsModified(); } /****************************************************************************** * void SwEditShell::SetModified() ******************************************************************************/ void SwEditShell::SetModified() { GetDoc()->SetModified(); } /****************************************************************************** * void SwEditShell::ResetModified() ******************************************************************************/ void SwEditShell::ResetModified() { GetDoc()->ResetModified(); } void SwEditShell::SetUndoNoResetModified() { GetDoc()->SetModified(); GetDoc()->SetUndoNoResetModified(); } /****************************************************************************** * void SwEditShell::StartAllAction() ******************************************************************************/ void SwEditShell::StartAllAction() { ViewShell *pSh = this; do { if( pSh->IsA( TYPE( SwEditShell ) ) ) ((SwEditShell*)pSh)->StartAction(); else pSh->StartAction(); pSh = (ViewShell *)pSh->GetNext(); } while(pSh != this); } /****************************************************************************** * void SwEditShell::EndAllAction() ******************************************************************************/ void SwEditShell::EndAllAction() { ViewShell *pSh = this; do { if( pSh->IsA( TYPE( SwEditShell ) ) ) ((SwEditShell*)pSh)->EndAction(); else pSh->EndAction(); pSh = (ViewShell *)pSh->GetNext(); } while(pSh != this); } /****************************************************************************** * void SwEditShell::CalcLayout() ******************************************************************************/ void SwEditShell::CalcLayout() { StartAllAction(); ViewShell::CalcLayout(); ViewShell *pSh = this; do { if ( pSh->GetWin() ) pSh->GetWin()->Invalidate(); pSh = (ViewShell*)pSh->GetNext(); } while ( pSh != this ); EndAllAction(); } /****************************************************************************** * Inhaltsform bestimmen, holen ******************************************************************************/ // OPT: wird fuer jedes Attribut gerufen? sal_uInt16 SwEditShell::GetCntType() const { // nur noch am SPoint ist der Inhalt interessant sal_uInt16 nRet = 0; if( IsTableMode() ) nRet = CNT_TXT; else switch( GetCrsr()->GetNode()->GetNodeType() ) { case ND_TEXTNODE: nRet = CNT_TXT; break; case ND_GRFNODE: nRet = CNT_GRF; break; case ND_OLENODE: nRet = CNT_OLE; break; } ASSERT( nRet, ERR_OUTOFSCOPE ); return nRet; } //------------------------------------------------------------------------------ sal_Bool SwEditShell::HasOtherCnt() const { const SwNodes &rNds = GetDoc()->GetNodes(); const SwNode *pNd; return GetDoc()->GetSpzFrmFmts()->Count() || 1 != (( pNd = &rNds.GetEndOfInserts() )->GetIndex() - pNd->StartOfSectionIndex() ) || 1 != (( pNd = &rNds.GetEndOfAutotext() )->GetIndex() - pNd->StartOfSectionIndex() ); } /****************************************************************************** * Zugriffsfunktionen fuer Filename-Behandlung ******************************************************************************/ SwActKontext::SwActKontext(SwEditShell *pShell) : pSh(pShell) { pSh->StartAction(); } SwActKontext::~SwActKontext() { pSh->EndAction(); } /****************************************************************************** * Klasse fuer den automatisierten Aufruf von Start- und * EndCrsrMove(); ******************************************************************************/ SwMvKontext::SwMvKontext(SwEditShell *pShell ) : pSh(pShell) { pSh->SttCrsrMove(); } SwMvKontext::~SwMvKontext() { pSh->EndCrsrMove(); } SwFrmFmt *SwEditShell::GetTableFmt() // OPT: schnellster Test auf Tabelle? { const SwTableNode* pTblNd = IsCrsrInTbl(); return pTblNd ? (SwFrmFmt*)pTblNd->GetTable().GetFrmFmt() : 0; } // OPT: wieso 3x beim neuen Dokument sal_uInt16 SwEditShell::GetTOXTypeCount(TOXTypes eTyp) const { return pDoc->GetTOXTypeCount(eTyp); } void SwEditShell::InsertTOXType(const SwTOXType& rTyp) { pDoc->InsertTOXType(rTyp); } void SwEditShell::DoUndo( sal_Bool bOn ) { GetDoc()->DoUndo( bOn ); } sal_Bool SwEditShell::DoesUndo() const { return GetDoc()->DoesUndo(); } void SwEditShell::DoGroupUndo( sal_Bool bOn ) { GetDoc()->DoGroupUndo( bOn ); } sal_Bool SwEditShell::DoesGroupUndo() const { return GetDoc()->DoesGroupUndo(); } void SwEditShell::DelAllUndoObj() { GetDoc()->DelAllUndoObj(); } // Zusammenfassen von Kontinuierlichen Insert/Delete/Overwrite von // Charaktern. Default ist sdbcx::Group-Undo. // setzt Undoklammerung auf, liefert nUndoId der Klammerung SwUndoId SwEditShell::StartUndo( SwUndoId eUndoId, const SwRewriter *pRewriter ) { return GetDoc()->StartUndo( eUndoId, pRewriter ); } // schliesst Klammerung der nUndoId, nicht vom UI benutzt SwUndoId SwEditShell::EndUndo(SwUndoId eUndoId, const SwRewriter *pRewriter) { return GetDoc()->EndUndo(eUndoId, pRewriter); } // liefert die Id der letzten undofaehigen Aktion zurueck // fuellt ggf. VARARR mit sdbcx::User-UndoIds SwUndoId SwEditShell::GetUndoIds(String* pStr,SwUndoIds *pUndoIds) const { return GetDoc()->GetUndoIds(pStr,pUndoIds); } String SwEditShell::GetUndoIdsStr(String* pStr,SwUndoIds *pUndoIds) const { return GetDoc()->GetUndoIdsStr(pStr,pUndoIds); } // liefert die Id der letzten Redofaehigen Aktion zurueck // fuellt ggf. VARARR mit RedoIds SwUndoId SwEditShell::GetRedoIds(String* pStr,SwUndoIds *pRedoIds) const { return GetDoc()->GetRedoIds(pStr,pRedoIds); } String SwEditShell::GetRedoIdsStr(String* pStr,SwUndoIds *pRedoIds) const { return GetDoc()->GetRedoIdsStr(pStr,pRedoIds); } // liefert die Id der letzten Repeatfaehigen Aktion zurueck // fuellt ggf. VARARR mit RedoIds SwUndoId SwEditShell::GetRepeatIds(String* pStr, SwUndoIds *pRedoIds) const { return GetDoc()->GetRepeatIds(pStr,pRedoIds); } String SwEditShell::GetRepeatIdsStr(String* pStr, SwUndoIds *pRedoIds) const { return GetDoc()->GetRepeatIdsStr(pStr,pRedoIds); } // AutoKorrektur - JP 27.01.94 void SwEditShell::AutoCorrect( SvxAutoCorrect& rACorr, sal_Bool bInsert, sal_Unicode cChar ) { SET_CURR_SHELL( this ); StartAllAction(); SwPaM* pCrsr = getShellCrsr( true ); SwTxtNode* pTNd = pCrsr->GetNode()->GetTxtNode(); SwAutoCorrDoc aSwAutoCorrDoc( *this, *pCrsr, cChar ); rACorr.AutoCorrect( aSwAutoCorrDoc, pTNd->GetTxt(), pCrsr->GetPoint()->nContent.GetIndex(), cChar, bInsert ); if( cChar ) SaveTblBoxCntnt( pCrsr->GetPoint() ); EndAllAction(); } void SwEditShell::SetNewDoc(sal_Bool bNew) { GetDoc()->SetNewDoc(bNew); } sal_Bool SwEditShell::GetPrevAutoCorrWord( SvxAutoCorrect& rACorr, String& rWord ) { SET_CURR_SHELL( this ); sal_Bool bRet; SwPaM* pCrsr = getShellCrsr( true ); xub_StrLen nPos = pCrsr->GetPoint()->nContent.GetIndex(); SwTxtNode* pTNd = pCrsr->GetNode()->GetTxtNode(); if( pTNd && nPos ) { SwAutoCorrDoc aSwAutoCorrDoc( *this, *pCrsr, 0 ); bRet = rACorr.GetPrevAutoCorrWord( aSwAutoCorrDoc, pTNd->GetTxt(), nPos, rWord ); } else bRet = sal_False; return bRet; } SwAutoCompleteWord& SwEditShell::GetAutoCompleteWords() { return SwDoc::GetAutoCompleteWords(); } <|endoftext|>
<commit_before>/************************************************************************* * * 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: annotsh.hxx,v $ * $Revision: 1.3 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef _SWANNOTSH_HXX #define _SWANNOTSH_HXX #include <sfx2/shell.hxx> #include "shellid.hxx" #include "swmodule.hxx" class SwView; class SwAnnotationShell: public SfxShell { SwView& rView; public: SFX_DECL_INTERFACE(SW_ANNOTATIONSHELL) TYPEINFO(); SwAnnotationShell(SwView&); virtual ~SwAnnotationShell(); void StateDisableItems(SfxItemSet &); void Exec(SfxRequest &); void GetState(SfxItemSet &); void StateInsert(SfxItemSet &rSet); void NoteExec(SfxRequest &); void GetNoteState(SfxItemSet &); void ExecLingu(SfxRequest &rReq); void GetLinguState(SfxItemSet &); void ExecClpbrd(SfxRequest &rReq); void StateClpbrd(SfxItemSet &rSet); void ExecTransliteration(SfxRequest &); void ExecUndo(SfxRequest &rReq); void StateUndo(SfxItemSet &rSet); void InsertSymbol(SfxRequest& rReq); virtual SfxUndoManager* GetUndoManager(); }; #endif <commit_msg>INTEGRATION: CWS notes5 (1.3.30); FILE MERGED 2008/05/14 17:02:59 mod 1.3.30.1: #i86595# #i89474#<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: annotsh.hxx,v $ * $Revision: 1.4 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef _SWANNOTSH_HXX #define _SWANNOTSH_HXX #include <sfx2/shell.hxx> #include "shellid.hxx" #include "swmodule.hxx" class SwView; class SwAnnotationShell: public SfxShell { SwView& rView; public: SFX_DECL_INTERFACE(SW_ANNOTATIONSHELL) TYPEINFO(); SwAnnotationShell(SwView&); virtual ~SwAnnotationShell(); void StateDisableItems(SfxItemSet &); void Exec(SfxRequest &); void GetState(SfxItemSet &); void StateInsert(SfxItemSet &rSet); void NoteExec(SfxRequest &); void GetNoteState(SfxItemSet &); void ExecLingu(SfxRequest &rReq); void GetLinguState(SfxItemSet &); void ExecClpbrd(SfxRequest &rReq); void StateClpbrd(SfxItemSet &rSet); void ExecTransliteration(SfxRequest &); void ExecUndo(SfxRequest &rReq); void StateUndo(SfxItemSet &rSet); void StateStatusLine(SfxItemSet &rSet); void InsertSymbol(SfxRequest& rReq); virtual SfxUndoManager* GetUndoManager(); }; #endif <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: frmpage.hxx,v $ * * $Revision: 1.14 $ * * last change: $Author: hr $ $Date: 2004-03-08 14:08:21 $ * * 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 _FRMPAGE_HXX #define _FRMPAGE_HXX #ifndef _FIXED_HXX //autogen #include <vcl/fixed.hxx> #endif #ifndef _BUTTON_HXX //autogen #include <vcl/button.hxx> #endif #ifndef _LSTBOX_HXX //autogen #include <vcl/lstbox.hxx> #endif #ifndef _FIELD_HXX //autogen #include <vcl/field.hxx> #endif #ifndef _SFXTABDLG_HXX //autogen #include <sfx2/tabdlg.hxx> #endif #ifndef _SWTYPES_HXX #include <swtypes.hxx> #endif #ifndef _BMPWIN_HXX #include <bmpwin.hxx> #endif #ifndef _FRMEX_HXX #include <frmex.hxx> #endif #ifndef _PRCNTFLD_HXX #include <prcntfld.hxx> #endif namespace sfx2{class FileDialogHelper;} class SwWrtShell; struct FrmMap; // OD 12.11.2003 #i22341# struct SwPosition; /*-------------------------------------------------------------------- Beschreibung: Rahmendialog --------------------------------------------------------------------*/ class SwFrmPage: public SfxTabPage { // Size FixedText aWidthFT; PercentField aWidthED; CheckBox aRelWidthCB; FixedText aHeightFT; PercentField aHeightED; CheckBox aRelHeightCB; CheckBox aFixedRatioCB; CheckBox aAutoHeightCB; PushButton aRealSizeBT; FixedLine aSizeFL; BOOL bWidthLastChanged; // Anker FixedLine aTypeFL; FixedLine aTypeSepFL; RadioButton aAnchorAtPageRB; RadioButton aAnchorAtParaRB; RadioButton aAnchorAtCharRB; RadioButton aAnchorAsCharRB; RadioButton aAnchorAtFrameRB; // Position FixedText aHorizontalFT; ListBox aHorizontalDLB; FixedText aAtHorzPosFT; MetricField aAtHorzPosED; FixedText aHoriRelationFT; ListBox aHoriRelationLB; CheckBox aMirrorPagesCB; FixedText aVerticalFT; ListBox aVerticalDLB; FixedText aAtVertPosFT; MetricField aAtVertPosED; FixedText aVertRelationFT; ListBox aVertRelationLB; // OD 02.10.2003 #i18732# - check box for new option 'FollowTextFlow' CheckBox aFollowTextFlowCB; FixedLine aPositionFL; BOOL bAtHorzPosModified; BOOL bAtVertPosModified; // Example SwFrmPagePreview aExampleWN; BOOL bFormat; BOOL bNew; BOOL bHtmlMode; BOOL bNoModifyHdl; BOOL bVerticalChanged; //check done whether frame is in vertical environment BOOL bIsVerticalFrame; //current frame is in vertical environment - strings are exchanged BOOL bIsInRightToLeft; // current frame is in right-to-left environment - strings are exchanged USHORT nHtmlMode; USHORT nDlgType; Size aGrfSize; Size aWrap; SwTwips nUpperBorder; SwTwips nLowerBorder; double fWidthHeightRatio; //width-to-height ratio to support the KeepRatio button // OD 12.11.2003 #i22341# - keep content position of character for // to character anchored objects. const SwPosition* mpToCharCntntPos; // Die alten Ausrichtungen USHORT nOldH; USHORT nOldHRel; USHORT nOldV; USHORT nOldVRel; virtual void ActivatePage(const SfxItemSet& rSet); virtual int DeactivatePage(SfxItemSet *pSet); DECL_LINK( RangeModifyHdl, Edit * ); DECL_LINK( AnchorTypeHdl, RadioButton * ); DECL_LINK( PosHdl, ListBox * ); DECL_LINK( RelHdl, ListBox * ); void InitPos(USHORT nId, USHORT nH, USHORT nHRel, USHORT nV, USHORT nVRel, long nX, long nY); DECL_LINK( EditModifyHdl, Edit * ); DECL_LINK( RealSizeHdl, Button * ); DECL_LINK( RelSizeClickHdl, CheckBox * ); DECL_LINK( MirrorHdl, CheckBox * ); DECL_LINK( ManualHdl, Button * ); // Beispiel aktualisieren void UpdateExample(); DECL_LINK( ModifyHdl, Edit * ); void Init(const SfxItemSet& rSet, BOOL bReset = FALSE); // OD 12.11.2003 #i22341# - adjustment to handle maps, that are ambigous // in the alignment. USHORT FillPosLB( const FrmMap* _pMap, const USHORT _nAlign, const USHORT _nRel, ListBox& _rLB ); // OD 14.11.2003 #i22341# - adjustment to handle maps, that are ambigous // in their string entries. ULONG FillRelLB( const FrmMap* _pMap, const USHORT _nLBSelPos, const USHORT _nAlign, USHORT _nRel, ListBox& _rLB, FixedText& _rFT ); USHORT GetMapPos( const FrmMap *pMap, ListBox &rAlignLB ); USHORT GetAlignment(FrmMap *pMap, USHORT nMapPos, ListBox &rAlignLB, ListBox &rRelationLB); USHORT GetRelation(FrmMap *pMap, ListBox &rRelationLB); USHORT GetAnchor(); SwFrmPage(Window *pParent, const SfxItemSet &rSet); ~SwFrmPage(); public: static SfxTabPage *Create(Window *pParent, const SfxItemSet &rSet); static USHORT* GetRanges(); virtual BOOL FillItemSet(SfxItemSet &rSet); virtual void Reset(const SfxItemSet &rSet); void SetNewFrame(BOOL bNewFrame) { bNew = bNewFrame; } void SetFormatUsed(BOOL bFmt); void SetFrmType(USHORT nType) { nDlgType = nType; } }; class SwGrfExtPage: public SfxTabPage { // Spiegeln FixedLine aMirrorFL; CheckBox aMirrorVertBox; CheckBox aMirrorHorzBox; RadioButton aAllPagesRB; RadioButton aLeftPagesRB; RadioButton aRightPagesRB; BmpWindow aBmpWin; FixedLine aConnectFL; FixedText aConnectFT; Edit aConnectED; PushButton aBrowseBT; String aFilterName; String aGrfName, aNewGrfName; ::sfx2::FileDialogHelper* pGrfDlg; BOOL bHtmlMode; // Handler fuer Spiegeln DECL_LINK( MirrorHdl, CheckBox * ); DECL_LINK( BrowseHdl, Button * ); virtual void ActivatePage(const SfxItemSet& rSet); SwGrfExtPage(Window *pParent, const SfxItemSet &rSet); ~SwGrfExtPage(); public: static SfxTabPage *Create(Window *pParent, const SfxItemSet &rSet); virtual BOOL FillItemSet(SfxItemSet &rSet); virtual void Reset(const SfxItemSet &rSet); virtual int DeactivatePage(SfxItemSet *pSet); }; class SwFrmURLPage : public SfxTabPage { //Hyperlink FixedLine aHyperLinkFL; FixedText aURLFT; Edit aURLED; PushButton aSearchPB; FixedText aNameFT; Edit aNameED; FixedText aFrameFT; ComboBox aFrameCB; //Image map FixedLine aImageFL; CheckBox aServerCB; CheckBox aClientCB; DECL_LINK( InsertFileHdl, PushButton * ); SwFrmURLPage(Window *pParent, const SfxItemSet &rSet); ~SwFrmURLPage(); public: static SfxTabPage *Create(Window *pParent, const SfxItemSet &rSet); virtual BOOL FillItemSet(SfxItemSet &rSet); virtual void Reset(const SfxItemSet &rSet); }; /*-----------------13.11.96 12.59------------------- --------------------------------------------------*/ class SwFrmAddPage : public SfxTabPage { FixedText aNameFT; Edit aNameED; FixedText aAltNameFT; Edit aAltNameED; FixedText aPrevFT; ListBox aPrevLB; FixedText aNextFT; ListBox aNextLB; FixedLine aNamesFL; CheckBox aProtectContentCB; CheckBox aProtectFrameCB; CheckBox aProtectSizeCB; FixedLine aProtectFL; CheckBox aEditInReadonlyCB; CheckBox aPrintFrameCB; FixedText aTextFlowFT; ListBox aTextFlowLB; FixedLine aExtFL; SwWrtShell* pWrtSh; USHORT nDlgType; BOOL bHtmlMode; BOOL bFormat; BOOL bNew; DECL_LINK(EditModifyHdl, Edit*); DECL_LINK(ChainModifyHdl, ListBox*); SwFrmAddPage(Window *pParent, const SfxItemSet &rSet); ~SwFrmAddPage(); public: static SfxTabPage* Create(Window *pParent, const SfxItemSet &rSet); static USHORT* GetRanges(); virtual BOOL FillItemSet(SfxItemSet &rSet); virtual void Reset(const SfxItemSet &rSet); void SetFormatUsed(BOOL bFmt); void SetFrmType(USHORT nType) { nDlgType = nType; } void SetNewFrame(BOOL bNewFrame) { bNew = bNewFrame; } void SetShell(SwWrtShell* pSh) { pWrtSh = pSh; } }; #endif // _FRMPAGE_HXX <commit_msg>INTEGRATION: CWS swautowidth (1.14.52); FILE MERGED 2004/04/16 07:44:27 gt 1.14.52.1: #i27202# autowidth for textframes UI<commit_after>/************************************************************************* * * $RCSfile: frmpage.hxx,v $ * * $Revision: 1.15 $ * * last change: $Author: kz $ $Date: 2004-05-18 15:00: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 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 _FRMPAGE_HXX #define _FRMPAGE_HXX #ifndef _FIXED_HXX //autogen #include <vcl/fixed.hxx> #endif #ifndef _BUTTON_HXX //autogen #include <vcl/button.hxx> #endif #ifndef _LSTBOX_HXX //autogen #include <vcl/lstbox.hxx> #endif #ifndef _FIELD_HXX //autogen #include <vcl/field.hxx> #endif #ifndef _SFXTABDLG_HXX //autogen #include <sfx2/tabdlg.hxx> #endif #ifndef _SWTYPES_HXX #include <swtypes.hxx> #endif #ifndef _BMPWIN_HXX #include <bmpwin.hxx> #endif #ifndef _FRMEX_HXX #include <frmex.hxx> #endif #ifndef _PRCNTFLD_HXX #include <prcntfld.hxx> #endif #ifndef _GLOBALS_HRC #include <globals.hrc> #endif namespace sfx2{class FileDialogHelper;} class SwWrtShell; struct FrmMap; // OD 12.11.2003 #i22341# struct SwPosition; /*-------------------------------------------------------------------- Beschreibung: Rahmendialog --------------------------------------------------------------------*/ class SwFrmPage: public SfxTabPage { // Size FixedText aWidthFT; FixedText aWidthAutoFT; PercentField aWidthED; CheckBox aRelWidthCB; CheckBox aAutoWidthCB; FixedText aHeightFT; FixedText aHeightAutoFT; PercentField aHeightED; CheckBox aRelHeightCB; CheckBox aAutoHeightCB; CheckBox aFixedRatioCB; PushButton aRealSizeBT; FixedLine aSizeFL; BOOL bWidthLastChanged; // Anker FixedLine aTypeFL; FixedLine aTypeSepFL; RadioButton aAnchorAtPageRB; RadioButton aAnchorAtParaRB; RadioButton aAnchorAtCharRB; RadioButton aAnchorAsCharRB; RadioButton aAnchorAtFrameRB; // Position FixedText aHorizontalFT; ListBox aHorizontalDLB; FixedText aAtHorzPosFT; MetricField aAtHorzPosED; FixedText aHoriRelationFT; ListBox aHoriRelationLB; CheckBox aMirrorPagesCB; FixedText aVerticalFT; ListBox aVerticalDLB; FixedText aAtVertPosFT; MetricField aAtVertPosED; FixedText aVertRelationFT; ListBox aVertRelationLB; // OD 02.10.2003 #i18732# - check box for new option 'FollowTextFlow' CheckBox aFollowTextFlowCB; FixedLine aPositionFL; BOOL bAtHorzPosModified; BOOL bAtVertPosModified; // Example SwFrmPagePreview aExampleWN; BOOL bFormat; BOOL bNew; BOOL bHtmlMode; BOOL bNoModifyHdl; BOOL bVerticalChanged; //check done whether frame is in vertical environment BOOL bIsVerticalFrame; //current frame is in vertical environment - strings are exchanged BOOL bIsInRightToLeft; // current frame is in right-to-left environment - strings are exchanged USHORT nHtmlMode; USHORT nDlgType; Size aGrfSize; Size aWrap; SwTwips nUpperBorder; SwTwips nLowerBorder; double fWidthHeightRatio; //width-to-height ratio to support the KeepRatio button // OD 12.11.2003 #i22341# - keep content position of character for // to character anchored objects. const SwPosition* mpToCharCntntPos; // Die alten Ausrichtungen USHORT nOldH; USHORT nOldHRel; USHORT nOldV; USHORT nOldVRel; virtual void ActivatePage(const SfxItemSet& rSet); virtual int DeactivatePage(SfxItemSet *pSet); DECL_LINK( RangeModifyHdl, Edit * ); DECL_LINK( AnchorTypeHdl, RadioButton * ); DECL_LINK( PosHdl, ListBox * ); DECL_LINK( RelHdl, ListBox * ); void InitPos(USHORT nId, USHORT nH, USHORT nHRel, USHORT nV, USHORT nVRel, long nX, long nY); DECL_LINK( EditModifyHdl, Edit * ); DECL_LINK( RealSizeHdl, Button * ); DECL_LINK( RelSizeClickHdl, CheckBox * ); DECL_LINK( MirrorHdl, CheckBox * ); DECL_LINK( ManualHdl, Button * ); DECL_LINK( AutoWidthClickHdl, void* ); DECL_LINK( AutoHeightClickHdl, void* ); // Beispiel aktualisieren void UpdateExample(); DECL_LINK( ModifyHdl, Edit * ); void Init(const SfxItemSet& rSet, BOOL bReset = FALSE); // OD 12.11.2003 #i22341# - adjustment to handle maps, that are ambigous // in the alignment. USHORT FillPosLB( const FrmMap* _pMap, const USHORT _nAlign, const USHORT _nRel, ListBox& _rLB ); // OD 14.11.2003 #i22341# - adjustment to handle maps, that are ambigous // in their string entries. ULONG FillRelLB( const FrmMap* _pMap, const USHORT _nLBSelPos, const USHORT _nAlign, USHORT _nRel, ListBox& _rLB, FixedText& _rFT ); USHORT GetMapPos( const FrmMap *pMap, ListBox &rAlignLB ); USHORT GetAlignment(FrmMap *pMap, USHORT nMapPos, ListBox &rAlignLB, ListBox &rRelationLB); USHORT GetRelation(FrmMap *pMap, ListBox &rRelationLB); USHORT GetAnchor(); void EnableGraficMode( void ); // hides auto check boxes and re-org controls for "Real Size" button SwFrmPage(Window *pParent, const SfxItemSet &rSet); ~SwFrmPage(); public: static SfxTabPage *Create(Window *pParent, const SfxItemSet &rSet); static USHORT* GetRanges(); virtual BOOL FillItemSet(SfxItemSet &rSet); virtual void Reset(const SfxItemSet &rSet); void SetNewFrame(BOOL bNewFrame) { bNew = bNewFrame; } void SetFormatUsed(BOOL bFmt); void SetFrmType(USHORT nType) { nDlgType = nType; } inline BOOL IsInGraficMode( void ) { return nDlgType == DLG_FRM_GRF || nDlgType == DLG_FRM_OLE; } }; class SwGrfExtPage: public SfxTabPage { // Spiegeln FixedLine aMirrorFL; CheckBox aMirrorVertBox; CheckBox aMirrorHorzBox; RadioButton aAllPagesRB; RadioButton aLeftPagesRB; RadioButton aRightPagesRB; BmpWindow aBmpWin; FixedLine aConnectFL; FixedText aConnectFT; Edit aConnectED; PushButton aBrowseBT; String aFilterName; String aGrfName, aNewGrfName; ::sfx2::FileDialogHelper* pGrfDlg; BOOL bHtmlMode; // Handler fuer Spiegeln DECL_LINK( MirrorHdl, CheckBox * ); DECL_LINK( BrowseHdl, Button * ); virtual void ActivatePage(const SfxItemSet& rSet); SwGrfExtPage(Window *pParent, const SfxItemSet &rSet); ~SwGrfExtPage(); public: static SfxTabPage *Create(Window *pParent, const SfxItemSet &rSet); virtual BOOL FillItemSet(SfxItemSet &rSet); virtual void Reset(const SfxItemSet &rSet); virtual int DeactivatePage(SfxItemSet *pSet); }; class SwFrmURLPage : public SfxTabPage { //Hyperlink FixedLine aHyperLinkFL; FixedText aURLFT; Edit aURLED; PushButton aSearchPB; FixedText aNameFT; Edit aNameED; FixedText aFrameFT; ComboBox aFrameCB; //Image map FixedLine aImageFL; CheckBox aServerCB; CheckBox aClientCB; DECL_LINK( InsertFileHdl, PushButton * ); SwFrmURLPage(Window *pParent, const SfxItemSet &rSet); ~SwFrmURLPage(); public: static SfxTabPage *Create(Window *pParent, const SfxItemSet &rSet); virtual BOOL FillItemSet(SfxItemSet &rSet); virtual void Reset(const SfxItemSet &rSet); }; /*-----------------13.11.96 12.59------------------- --------------------------------------------------*/ class SwFrmAddPage : public SfxTabPage { FixedText aNameFT; Edit aNameED; FixedText aAltNameFT; Edit aAltNameED; FixedText aPrevFT; ListBox aPrevLB; FixedText aNextFT; ListBox aNextLB; FixedLine aNamesFL; CheckBox aProtectContentCB; CheckBox aProtectFrameCB; CheckBox aProtectSizeCB; FixedLine aProtectFL; CheckBox aEditInReadonlyCB; CheckBox aPrintFrameCB; FixedText aTextFlowFT; ListBox aTextFlowLB; FixedLine aExtFL; SwWrtShell* pWrtSh; USHORT nDlgType; BOOL bHtmlMode; BOOL bFormat; BOOL bNew; DECL_LINK(EditModifyHdl, Edit*); DECL_LINK(ChainModifyHdl, ListBox*); SwFrmAddPage(Window *pParent, const SfxItemSet &rSet); ~SwFrmAddPage(); public: static SfxTabPage* Create(Window *pParent, const SfxItemSet &rSet); static USHORT* GetRanges(); virtual BOOL FillItemSet(SfxItemSet &rSet); virtual void Reset(const SfxItemSet &rSet); void SetFormatUsed(BOOL bFmt); void SetFrmType(USHORT nType) { nDlgType = nType; } void SetNewFrame(BOOL bNewFrame) { bNew = bNewFrame; } void SetShell(SwWrtShell* pSh) { pWrtSh = pSh; } }; #endif // _FRMPAGE_HXX <|endoftext|>
<commit_before> #ifndef _enum_gen__enum_gen_hpp #define _enum_gen__enum_gen_hpp #include <boost/preprocessor.hpp> #include <cstdint> #include <cstring> #include <cassert> /****************************************************************************/ #define ENUM_GEN_WRAP_SEQUENCE_X(...) \ ((__VA_ARGS__)) ENUM_GEN_WRAP_SEQUENCE_Y #define ENUM_GEN_WRAP_SEQUENCE_Y(...) \ ((__VA_ARGS__)) ENUM_GEN_WRAP_SEQUENCE_X #define ENUM_GEN_WRAP_SEQUENCE_X0 #define ENUM_GEN_WRAP_SEQUENCE_Y0 /****************************************************************************/ #define ENUM_GEN_DECLARE_ENUM_MEMBERS(unused, data, idx, elem) \ BOOST_PP_COMMA_IF(idx) BOOST_PP_IF( \ BOOST_PP_EQUAL(2, BOOST_PP_TUPLE_SIZE(elem)) \ ,BOOST_PP_TUPLE_ELEM(0, elem)=BOOST_PP_TUPLE_ELEM(1, elem) /* member = value */ \ ,BOOST_PP_TUPLE_ELEM(0, elem) /* member */ \ ) #define ENUM_GEN_DECLARE_ENUM_WRITE_CASES(unused, data, idx, elem) \ case BOOST_PP_TUPLE_ELEM(0, data)::BOOST_PP_TUPLE_ELEM(0, elem): \ return BOOST_PP_STRINGIZE(BOOST_PP_TUPLE_ELEM(0, data)::BOOST_PP_TUPLE_ELEM(0, elem)) \ ; #define ENUM_GEN_DECLARE_ENUM_WRITE_CASES2(unused, data, idx, elem) \ case idx: if ( 0 == std::strcmp(names[idx], str) ) return data::BOOST_PP_TUPLE_ELEM(0, elem); /****************************************************************************/ #define ENUM_GEN_DECLARE_ENUM_MEMBERS_NAMES_AUX(unused, data, idx, elem) \ BOOST_PP_STRINGIZE(data::BOOST_PP_TUPLE_ELEM(0, elem)), #define ENUM_GEN_DECLARE_ENUM_MEMBERS_NAMES_AUX2(unused, data, idx, elem) \ with_pref[idx]+preflen, #define ENUM_GEN_DECLARE_ENUM_MEMBERS_NAMES(name, seq) \ static const char *with_pref[] = { \ BOOST_PP_SEQ_FOR_EACH_I( \ ENUM_GEN_DECLARE_ENUM_MEMBERS_NAMES_AUX \ ,name \ ,seq \ ) \ 0 \ }; \ static const char *without_pref[] = { \ BOOST_PP_SEQ_FOR_EACH_I( \ ENUM_GEN_DECLARE_ENUM_MEMBERS_NAMES_AUX2 \ ,name\ ,seq \ ) \ 0 \ }; /****************************************************************************/ #define ENUM_GEN_DECLARE_ENUM_OPERATORS_IMPL(unused, data, elem) \ inline constexpr BOOST_PP_TUPLE_ELEM(0, data) operator elem ( \ const BOOST_PP_TUPLE_ELEM(0, data) &l \ ,const BOOST_PP_TUPLE_ELEM(0, data) &r \ ) { \ return static_cast<BOOST_PP_TUPLE_ELEM(0, data)> \ ( \ static_cast<BOOST_PP_TUPLE_ELEM(1, data)>(l) \ elem \ static_cast<BOOST_PP_TUPLE_ELEM(1, data)>(r) \ ); \ } #define ENUM_GEN_DECLARE_ENUM_OPERATORS(name, type, seq) \ BOOST_PP_SEQ_FOR_EACH( \ ENUM_GEN_DECLARE_ENUM_OPERATORS_IMPL \ ,(name, type) \ ,seq \ ) /****************************************************************************/ #define ENUM_GEN_DECLARE_ENUM_IMPL(name, type, seq) \ enum class name : type { \ BOOST_PP_SEQ_FOR_EACH_I( \ ENUM_GEN_DECLARE_ENUM_MEMBERS \ ,~ \ ,seq \ ) \ }; \ \ inline const char *enum_cast(const name &e) { \ switch ( e ) { \ BOOST_PP_SEQ_FOR_EACH_I( \ ENUM_GEN_DECLARE_ENUM_WRITE_CASES \ ,(name, seq) \ ,seq \ ) \ } \ assert("bad enum value #1" == 0); \ } \ \ template<typename E> \ E enum_cast(const char *); \ \ template<> \ name enum_cast<name>(const char *str) { \ static const std::size_t preflen = sizeof(BOOST_PP_STRINGIZE(name::))-1; \ ENUM_GEN_DECLARE_ENUM_MEMBERS_NAMES(name, seq) \ \ const char **names = (std::strchr(str, ':') != 0 ? with_pref : without_pref); \ for ( std::size_t idx = 0; idx < BOOST_PP_SEQ_SIZE(seq); ++idx ) { \ switch ( idx ) { \ BOOST_PP_SEQ_FOR_EACH_I( \ ENUM_GEN_DECLARE_ENUM_WRITE_CASES2 \ ,name\ ,seq \ ) \ } \ } \ assert("bad enum value #2" == 0); \ } \ \ std::ostream& operator<< (std::ostream &os, const name &e) { \ return (os << enum_cast(e)); \ } \ \ ENUM_GEN_DECLARE_ENUM_OPERATORS(name, type, (&)(|)(^)) #define ENUM_GEN_DECLARE_ENUM(name, type, seq) \ ENUM_GEN_DECLARE_ENUM_IMPL( \ name \ ,type \ ,BOOST_PP_CAT(ENUM_GEN_WRAP_SEQUENCE_X seq, 0) \ ) #define ENUM_GEN_DECLARE_ENUM_NS(ns, name, type, seq) \ namespace ns { \ ENUM_GEN_DECLARE_ENUM(name, type, seq) \ } /****************************************************************************/ #endif // _enum_gen__enum_gen_hpp <commit_msg>fix for previous commit<commit_after> #ifndef _enum_gen__enum_gen_hpp #define _enum_gen__enum_gen_hpp #include <boost/preprocessor.hpp> #include <cstdint> #include <cstring> #include <cassert> /****************************************************************************/ #define ENUM_GEN_WRAP_SEQUENCE_X(...) \ ((__VA_ARGS__)) ENUM_GEN_WRAP_SEQUENCE_Y #define ENUM_GEN_WRAP_SEQUENCE_Y(...) \ ((__VA_ARGS__)) ENUM_GEN_WRAP_SEQUENCE_X #define ENUM_GEN_WRAP_SEQUENCE_X0 #define ENUM_GEN_WRAP_SEQUENCE_Y0 /****************************************************************************/ #define ENUM_GEN_DECLARE_ENUM_MEMBERS(unused, data, idx, elem) \ BOOST_PP_COMMA_IF(idx) BOOST_PP_IF( \ BOOST_PP_EQUAL(2, BOOST_PP_TUPLE_SIZE(elem)) \ ,BOOST_PP_TUPLE_ELEM(0, elem)=BOOST_PP_TUPLE_ELEM(1, elem) /* member = value */ \ ,BOOST_PP_TUPLE_ELEM(0, elem) /* member */ \ ) #define ENUM_GEN_DECLARE_ENUM_WRITE_CASES(unused, data, idx, elem) \ case data::BOOST_PP_TUPLE_ELEM(0, elem): \ return BOOST_PP_STRINGIZE(data::BOOST_PP_TUPLE_ELEM(0, elem)) \ ; #define ENUM_GEN_DECLARE_ENUM_WRITE_CASES2(unused, data, idx, elem) \ case idx: if ( 0 == std::strcmp(names[idx], str) ) return data::BOOST_PP_TUPLE_ELEM(0, elem); /****************************************************************************/ #define ENUM_GEN_DECLARE_ENUM_MEMBERS_NAMES_AUX(unused, data, idx, elem) \ BOOST_PP_STRINGIZE(data::BOOST_PP_TUPLE_ELEM(0, elem)), #define ENUM_GEN_DECLARE_ENUM_MEMBERS_NAMES_AUX2(unused, data, idx, elem) \ with_pref[idx]+preflen, #define ENUM_GEN_DECLARE_ENUM_MEMBERS_NAMES(name, seq) \ static const char *with_pref[] = { \ BOOST_PP_SEQ_FOR_EACH_I( \ ENUM_GEN_DECLARE_ENUM_MEMBERS_NAMES_AUX \ ,name \ ,seq \ ) \ 0 \ }; \ static const char *without_pref[] = { \ BOOST_PP_SEQ_FOR_EACH_I( \ ENUM_GEN_DECLARE_ENUM_MEMBERS_NAMES_AUX2 \ ,name\ ,seq \ ) \ 0 \ }; /****************************************************************************/ #define ENUM_GEN_DECLARE_ENUM_OPERATORS_IMPL(unused, data, elem) \ inline constexpr BOOST_PP_TUPLE_ELEM(0, data) operator elem ( \ const BOOST_PP_TUPLE_ELEM(0, data) &l \ ,const BOOST_PP_TUPLE_ELEM(0, data) &r \ ) { \ return static_cast<BOOST_PP_TUPLE_ELEM(0, data)> \ ( \ static_cast<BOOST_PP_TUPLE_ELEM(1, data)>(l) \ elem \ static_cast<BOOST_PP_TUPLE_ELEM(1, data)>(r) \ ); \ } #define ENUM_GEN_DECLARE_ENUM_OPERATORS(name, type, seq) \ BOOST_PP_SEQ_FOR_EACH( \ ENUM_GEN_DECLARE_ENUM_OPERATORS_IMPL \ ,(name, type) \ ,seq \ ) /****************************************************************************/ #define ENUM_GEN_DECLARE_ENUM_IMPL(name, type, seq) \ enum class name : type { \ BOOST_PP_SEQ_FOR_EACH_I( \ ENUM_GEN_DECLARE_ENUM_MEMBERS \ ,~ \ ,seq \ ) \ }; \ \ inline const char *enum_cast(const name &e) { \ switch ( e ) { \ BOOST_PP_SEQ_FOR_EACH_I( \ ENUM_GEN_DECLARE_ENUM_WRITE_CASES \ ,name\ ,seq \ ) \ } \ assert("bad enum value #1" == 0); \ } \ \ template<typename E> \ E enum_cast(const char *); \ \ template<> \ name enum_cast<name>(const char *str) { \ static const std::size_t preflen = sizeof(BOOST_PP_STRINGIZE(name::))-1; \ ENUM_GEN_DECLARE_ENUM_MEMBERS_NAMES(name, seq) \ \ const char **names = (std::strchr(str, ':') != 0 ? with_pref : without_pref); \ for ( std::size_t idx = 0; idx < BOOST_PP_SEQ_SIZE(seq); ++idx ) { \ switch ( idx ) { \ BOOST_PP_SEQ_FOR_EACH_I( \ ENUM_GEN_DECLARE_ENUM_WRITE_CASES2 \ ,name\ ,seq \ ) \ } \ } \ assert("bad enum value #2" == 0); \ } \ \ std::ostream& operator<< (std::ostream &os, const name &e) { \ return (os << enum_cast(e)); \ } \ \ ENUM_GEN_DECLARE_ENUM_OPERATORS(name, type, (&)(|)(^)) #define ENUM_GEN_DECLARE_ENUM(name, type, seq) \ ENUM_GEN_DECLARE_ENUM_IMPL( \ name \ ,type \ ,BOOST_PP_CAT(ENUM_GEN_WRAP_SEQUENCE_X seq, 0) \ ) #define ENUM_GEN_DECLARE_ENUM_NS(ns, name, type, seq) \ namespace ns { \ ENUM_GEN_DECLARE_ENUM(name, type, seq) \ } /****************************************************************************/ #endif // _enum_gen__enum_gen_hpp <|endoftext|>
<commit_before>#include <iostream> #include <boost/program_options.hpp> #include "common.h" #include "scope_guard.h" #include "context.h" #include "agenda.h" #include "commands.h" #include "errors.h" #include <sys/ioctl.h> #include <boost/bind.hpp> #include <curl/curl.h> #include "mimes.h" using namespace es3; namespace po = boost::program_options; int es3::term_width = 80; std::vector<po::option> subcommands_parser(stringvec& args, const stringvec& subcommands) { std::vector<po::option> result; if (args.empty()) return result; stringvec::const_iterator i(args.begin()); stringvec::const_iterator cmd_idx=std::find(subcommands.begin(), subcommands.end(),*i); if (cmd_idx!=subcommands.end()) { po::option opt; opt.string_key = "subcommand"; opt.value.push_back(*i); opt.original_tokens.push_back(*i); result.push_back(opt); for (++i; i != args.end(); ++i) { po::option opt; opt.string_key = "subcommand_params"; opt.value.push_back(*i); opt.original_tokens.push_back(*i); result.push_back(opt); } args.clear(); } return result; } static std::string get_at(const std::map<std::string, std::string> &map, const std::string &key) { return try_get(map, key); } int main(int argc, char **argv) { int verbosity = 0; //Get terminal size (to pretty-print help text) struct winsize w={0}; ioctl(0, TIOCGWINSZ, &w); term_width=(w.ws_col==0)? 80 : w.ws_col; init_mimes(); context_ptr cd(new conn_context()); po::options_description generic("Generic options", term_width); generic.add_options() ("help", "Display this message") ("config,c", po::value<std::string>(), "Path to a file that contains configuration settings") ("verbosity,v", po::value<int>(&verbosity)->default_value(1), "Verbosity level [0 - the lowest, 9 - the highest]") ("no-progress,q", "Quiet mode (no progress indicator)") ("no-stats,t", "Quiet mode (no final stats)") ("scratch-dir,i", po::value<bf::path>(&cd->scratch_dir_) ->default_value(bf::temp_directory_path())->required(), "Path to the scratch directory") ; po::options_description access("Access settings", term_width); access.add_options() ("access-key,a", po::value<std::string>( &cd->api_key_)->required(), "Amazon S3 API key. If not set then AWS_ACCESS_KEY_ID " "environment variable is used.") ("secret-key,s", po::value<std::string>( &cd->secret_key)->required(), "Amazon S3 secret key. If not set then AWS_SECRET_ACCESS_KEY " "environment variable is used.") ("use-ssl,l", po::value<bool>( &cd->use_ssl_)->default_value(false), "Use SSL for communications with the Amazon S3 servers") ("compression,m", po::value<bool>( &cd->do_compression_)->default_value(true)->required(), "Use GZIP compression") ; generic.add(access); int thread_num=0, io_threads=0, cpu_threads=0, segment_size=0, segments=0; po::options_description tuning("Tuning", term_width); tuning.add_options() ("thread-num,n", po::value<int>(&thread_num)->default_value(0), "Number of download/upload threads used [0 - autodetect]") ("reader-threads,r", po::value<int>( &io_threads)->default_value(0), "Number of filesystem reader/writer threads [0 - autodetect]") ("compressor-threads,o", po::value<int>( &cpu_threads)->default_value(0), "Number of compressor threads [0 - autodetect]") ("segment-size,g", po::value<int>( &segment_size)->default_value(0), "Segment size in bytes [0 - autodetect, 6291456 - minimum]") ("segments-in-flight,f", po::value<int>( &segments)->default_value(0), "Number of segments in-flight [0 - autodetect]") ; generic.add(tuning); po::options_description sub_data("Subcommands"); sub_data.add_options() ("subcommand", po::value<std::string>()) ("subcommand_params", po::value<stringvec>()->multitoken()); std::map< std::string, std::function<int(context_ptr, const stringvec&, agenda_ptr, bool)> > subcommands_map; subcommands_map["sync"] = boost::bind(&do_rsync, _1, _2, _3, _4); subcommands_map["test"] = boost::bind(&do_test, _1, _2, _3, _4); subcommands_map["touch"] = boost::bind(&do_touch, _1, _2, _3, _4); subcommands_map["rm"] = boost::bind(&do_rm, _1, _2, _3, _4); subcommands_map["du"] = boost::bind(&do_du, _1, _2, _3, _4); subcommands_map["ls"] = boost::bind(&do_ls, _1, _2, _3, _4); subcommands_map["cat"] = boost::bind(&do_cat, _1, _2, _3, _4); subcommands_map["publish"] = boost::bind(&do_publish, _1, _2, _3, _4); stringvec subcommands; for(auto iter=subcommands_map.begin();iter!=subcommands_map.end();++iter) subcommands.push_back(iter->first); std::string cur_subcommand; stringvec cur_sub_params; po::variables_map vm; try { sub_data.add(generic); po::parsed_options parsed = po::command_line_parser(argc, argv) .options(sub_data) .extra_style_parser(boost::bind(&subcommands_parser, _1, subcommands)) .run(); po::store(parsed, vm); cur_subcommand=vm.count("subcommand")==0? "" : vm["subcommand"].as<std::string>(); cur_sub_params=vm.count("subcommand_params")==0? stringvec() : vm["subcommand_params"].as<stringvec>(); if (argc < 2 || vm.count("help")) { if (cur_subcommand.empty()) { std::cout << "Extreme S3 - fast S3 client\n" << generic << "\nThe following commands are supported:\n\t"; for(auto iter=subcommands.begin();iter!=subcommands.end();++iter) std::cout<< *iter <<" "; std::cout << "\nUse --help <command_name> to get more info\n"; } else { std::cout << "Extreme S3 - fast S3 client\n"; subcommands_map[cur_subcommand](cd, cur_sub_params, agenda_ptr(), true); } return 1; } if (cur_subcommand.empty()) { std::cout << "No command specified. Use --help for help\n"; return 2; } } catch(const boost::program_options::error &err) { std::cerr << "Failed to parse command line. Error: " << err.what() << std::endl; return 2; } try { bool found=false; if (vm.count("config")) { // Parse the file and store the options std::string config_file = vm["config"].as<std::string>(); po::store(po::parse_config_file<char>(config_file.c_str(),generic), vm); found = true; } if (!found && getenv("ES3_CONFIG")) { po::store(po::parse_config_file<char>( getenv("ES3_CONFIG"),generic), vm); found = true; } if (!found) { const char *home=getenv("HOME"); if (home) { bf::path cfg=bf::path(home) / ".es3cfg"; if (bf::exists(cfg)) { po::store(po::parse_config_file<char>( cfg.c_str(),generic), vm); found=true; } } } /* if (!found) { bf::path cfg=bf::path("/conf") / "es3cfg"; if (bf::exists(cfg)) { po::store(po::parse_config_file<char>(cfg.c_str(),generic), vm); found=true; } } */ //Try to parse the environment std::map<std::string, std::string> env_name_map; env_name_map["AWS_ACCESS_KEY_ID"]="access-key"; env_name_map["AWS_SECRET_ACCESS_KEY"]="secret-key"; po::store(po::parse_environment(generic, boost::bind( &get_at, env_name_map, _1)), vm); } catch(const boost::program_options::error &err) { std::cerr << "Failed to parse the configuration file. Error: " << err.what() << std::endl; return 2; } bool no_progress = vm.count("no-progress"); bool no_stats = vm.count("no-stats"); try { po::notify(vm); } catch(const boost::program_options::required_option &option) { std::cerr << "Required option " << option.get_option_name() << " is not present." << std::endl; return 1; } logger::set_verbosity(verbosity); curl_global_init(CURL_GLOBAL_ALL); ON_BLOCK_EXIT(&curl_global_cleanup); if (segments>MAX_IN_FLIGHT) segments=MAX_IN_FLIGHT; else if (segments<=0) segments=40; if (segment_size<MIN_SEGMENT_SIZE) segment_size=MIN_SEGMENT_SIZE; if (cpu_threads<=0) cpu_threads=sysconf(_SC_NPROCESSORS_ONLN)+2; if (io_threads<=0) io_threads=sysconf(_SC_NPROCESSORS_ONLN)*2+2; if (thread_num<=0) thread_num=sysconf(_SC_NPROCESSORS_ONLN)*6+40; if (cur_subcommand=="cat") { no_progress=no_stats=true; //A special hack } agenda_ptr ag(new agenda(thread_num, cpu_threads, io_threads, no_progress, no_stats, segment_size, segments)); try { return subcommands_map[cur_subcommand](cd, cur_sub_params, ag, false); } catch(const es3_exception &ex) { VLOG(0) << "" << ex.what() << std::endl; return 8; } catch(const std::exception &ex) { VLOG(0) << "Unexpected error: " << ex.what() << std::endl; return 8; } } <commit_msg>No verbosity by default<commit_after>#include <iostream> #include <boost/program_options.hpp> #include "common.h" #include "scope_guard.h" #include "context.h" #include "agenda.h" #include "commands.h" #include "errors.h" #include <sys/ioctl.h> #include <boost/bind.hpp> #include <curl/curl.h> #include "mimes.h" using namespace es3; namespace po = boost::program_options; int es3::term_width = 80; std::vector<po::option> subcommands_parser(stringvec& args, const stringvec& subcommands) { std::vector<po::option> result; if (args.empty()) return result; stringvec::const_iterator i(args.begin()); stringvec::const_iterator cmd_idx=std::find(subcommands.begin(), subcommands.end(),*i); if (cmd_idx!=subcommands.end()) { po::option opt; opt.string_key = "subcommand"; opt.value.push_back(*i); opt.original_tokens.push_back(*i); result.push_back(opt); for (++i; i != args.end(); ++i) { po::option opt; opt.string_key = "subcommand_params"; opt.value.push_back(*i); opt.original_tokens.push_back(*i); result.push_back(opt); } args.clear(); } return result; } static std::string get_at(const std::map<std::string, std::string> &map, const std::string &key) { return try_get(map, key); } int main(int argc, char **argv) { int verbosity = 0; //Be verbose by default if controlling terminal is present int def_verbose = isatty(2); //Get terminal size (to pretty-print help text) struct winsize w={0}; ioctl(0, TIOCGWINSZ, &w); term_width=(w.ws_col==0)? 80 : w.ws_col; init_mimes(); context_ptr cd(new conn_context()); po::options_description generic("Generic options", term_width); generic.add_options() ("help", "Display this message") ("config,c", po::value<std::string>(), "Path to a file that contains configuration settings") ("verbosity,v", po::value<int>(&verbosity)->default_value(1), "Verbosity level [0 - the lowest, 9 - the highest]") ("no-progress,q", "Quiet mode (no progress indicator)") ("no-stats,t", "Quiet mode (no final stats)") ("scratch-dir,i", po::value<bf::path>(&cd->scratch_dir_) ->default_value(bf::temp_directory_path())->required(), "Path to the scratch directory") ; po::options_description access("Access settings", term_width); access.add_options() ("access-key,a", po::value<std::string>( &cd->api_key_)->required(), "Amazon S3 API key. If not set then AWS_ACCESS_KEY_ID " "environment variable is used.") ("secret-key,s", po::value<std::string>( &cd->secret_key)->required(), "Amazon S3 secret key. If not set then AWS_SECRET_ACCESS_KEY " "environment variable is used.") ("use-ssl,l", po::value<bool>( &cd->use_ssl_)->default_value(false), "Use SSL for communications with the Amazon S3 servers") ("compression,m", po::value<bool>( &cd->do_compression_)->default_value(true)->required(), "Use GZIP compression") ; generic.add(access); int thread_num=0, io_threads=0, cpu_threads=0, segment_size=0, segments=0; po::options_description tuning("Tuning", term_width); tuning.add_options() ("thread-num,n", po::value<int>(&thread_num)->default_value(0), "Number of download/upload threads used [0 - autodetect]") ("reader-threads,r", po::value<int>( &io_threads)->default_value(0), "Number of filesystem reader/writer threads [0 - autodetect]") ("compressor-threads,o", po::value<int>( &cpu_threads)->default_value(0), "Number of compressor threads [0 - autodetect]") ("segment-size,g", po::value<int>( &segment_size)->default_value(0), "Segment size in bytes [0 - autodetect, 6291456 - minimum]") ("segments-in-flight,f", po::value<int>( &segments)->default_value(0), "Number of segments in-flight [0 - autodetect]") ; generic.add(tuning); po::options_description sub_data("Subcommands"); sub_data.add_options() ("subcommand", po::value<std::string>()) ("subcommand_params", po::value<stringvec>()->multitoken()); std::map< std::string, std::function<int(context_ptr, const stringvec&, agenda_ptr, bool)> > subcommands_map; subcommands_map["sync"] = boost::bind(&do_rsync, _1, _2, _3, _4); subcommands_map["test"] = boost::bind(&do_test, _1, _2, _3, _4); subcommands_map["touch"] = boost::bind(&do_touch, _1, _2, _3, _4); subcommands_map["rm"] = boost::bind(&do_rm, _1, _2, _3, _4); subcommands_map["du"] = boost::bind(&do_du, _1, _2, _3, _4); subcommands_map["ls"] = boost::bind(&do_ls, _1, _2, _3, _4); subcommands_map["cat"] = boost::bind(&do_cat, _1, _2, _3, _4); subcommands_map["publish"] = boost::bind(&do_publish, _1, _2, _3, _4); stringvec subcommands; for(auto iter=subcommands_map.begin();iter!=subcommands_map.end();++iter) subcommands.push_back(iter->first); std::string cur_subcommand; stringvec cur_sub_params; po::variables_map vm; try { sub_data.add(generic); po::parsed_options parsed = po::command_line_parser(argc, argv) .options(sub_data) .extra_style_parser(boost::bind(&subcommands_parser, _1, subcommands)) .run(); po::store(parsed, vm); cur_subcommand=vm.count("subcommand")==0? "" : vm["subcommand"].as<std::string>(); cur_sub_params=vm.count("subcommand_params")==0? stringvec() : vm["subcommand_params"].as<stringvec>(); if (argc < 2 || vm.count("help")) { if (cur_subcommand.empty()) { std::cout << "Extreme S3 - fast S3 client\n" << generic << "\nThe following commands are supported:\n\t"; for(auto iter=subcommands.begin();iter!=subcommands.end();++iter) std::cout<< *iter <<" "; std::cout << "\nUse --help <command_name> to get more info\n"; } else { std::cout << "Extreme S3 - fast S3 client\n"; subcommands_map[cur_subcommand](cd, cur_sub_params, agenda_ptr(), true); } return 1; } if (cur_subcommand.empty()) { std::cout << "No command specified. Use --help for help\n"; return 2; } } catch(const boost::program_options::error &err) { std::cerr << "Failed to parse command line. Error: " << err.what() << std::endl; return 2; } try { bool found=false; if (vm.count("config")) { // Parse the file and store the options std::string config_file = vm["config"].as<std::string>(); po::store(po::parse_config_file<char>(config_file.c_str(),generic), vm); found = true; } if (!found && getenv("ES3_CONFIG")) { po::store(po::parse_config_file<char>( getenv("ES3_CONFIG"),generic), vm); found = true; } if (!found) { const char *home=getenv("HOME"); if (home) { bf::path cfg=bf::path(home) / ".es3cfg"; if (bf::exists(cfg)) { po::store(po::parse_config_file<char>( cfg.c_str(),generic), vm); found=true; } } } /* if (!found) { bf::path cfg=bf::path("/conf") / "es3cfg"; if (bf::exists(cfg)) { po::store(po::parse_config_file<char>(cfg.c_str(),generic), vm); found=true; } } */ //Try to parse the environment std::map<std::string, std::string> env_name_map; env_name_map["AWS_ACCESS_KEY_ID"]="access-key"; env_name_map["AWS_SECRET_ACCESS_KEY"]="secret-key"; po::store(po::parse_environment(generic, boost::bind( &get_at, env_name_map, _1)), vm); } catch(const boost::program_options::error &err) { std::cerr << "Failed to parse the configuration file. Error: " << err.what() << std::endl; return 2; } bool no_progress = vm.count("no-progress") || !def_verbose; bool no_stats = vm.count("no-stats"); try { po::notify(vm); } catch(const boost::program_options::required_option &option) { std::cerr << "Required option " << option.get_option_name() << " is not present." << std::endl; return 1; } logger::set_verbosity(verbosity); curl_global_init(CURL_GLOBAL_ALL); ON_BLOCK_EXIT(&curl_global_cleanup); if (segments>MAX_IN_FLIGHT) segments=MAX_IN_FLIGHT; else if (segments<=0) segments=40; if (segment_size<MIN_SEGMENT_SIZE) segment_size=MIN_SEGMENT_SIZE; if (cpu_threads<=0) cpu_threads=sysconf(_SC_NPROCESSORS_ONLN)+2; if (io_threads<=0) io_threads=sysconf(_SC_NPROCESSORS_ONLN)*2+2; if (thread_num<=0) thread_num=sysconf(_SC_NPROCESSORS_ONLN)*6+40; if (cur_subcommand=="cat") { no_progress=no_stats=true; //A special hack } agenda_ptr ag(new agenda(thread_num, cpu_threads, io_threads, no_progress, no_stats, segment_size, segments)); try { return subcommands_map[cur_subcommand](cd, cur_sub_params, ag, false); } catch(const es3_exception &ex) { VLOG(0) << "" << ex.what() << std::endl; return 8; } catch(const std::exception &ex) { VLOG(0) << "Unexpected error: " << ex.what() << std::endl; return 8; } } <|endoftext|>
<commit_before>#include <iostream> #include <boost/program_options.hpp> #include "common.h" #include "scope_guard.h" #include "context.h" #include "agenda.h" #include "commands.h" #include "errors.h" #include <sys/ioctl.h> #include <boost/bind.hpp> #include <curl/curl.h> #include "mimes.h" using namespace es3; namespace po = boost::program_options; int es3::term_width = 80; std::vector<po::option> subcommands_parser(stringvec& args, const stringvec& subcommands) { std::vector<po::option> result; if (args.empty()) return result; stringvec::const_iterator i(args.begin()); stringvec::const_iterator cmd_idx=std::find(subcommands.begin(), subcommands.end(),*i); if (cmd_idx!=subcommands.end()) { po::option opt; opt.string_key = "subcommand"; opt.value.push_back(*i); opt.original_tokens.push_back(*i); result.push_back(opt); for (++i; i != args.end(); ++i) { po::option opt; opt.string_key = "subcommand_params"; opt.value.push_back(*i); opt.original_tokens.push_back(*i); result.push_back(opt); } args.clear(); } return result; } static std::string get_at(const std::map<std::string, std::string> &map, const std::string &key) { return try_get(map, key); } int main(int argc, char **argv) { int verbosity = 0; //Get terminal size (to pretty-print help text) struct winsize w={0}; ioctl(0, TIOCGWINSZ, &w); term_width=(w.ws_col==0)? 80 : w.ws_col; init_mimes(); context_ptr cd(new conn_context()); po::options_description generic("Generic options", term_width); generic.add_options() ("help", "Display this message") ("config,c", po::value<std::string>(), "Path to a file that contains configuration settings") ("verbosity,v", po::value<int>(&verbosity)->default_value(1), "Verbosity level [0 - the lowest, 9 - the highest]") ("no-progress,q", "Quiet mode (no progress indicator)") ("no-stats,t", "Quiet mode (no final stats)") ("scratch-dir,i", po::value<bf::path>(&cd->scratch_dir_) ->default_value(bf::temp_directory_path())->required(), "Path to the scratch directory") ; po::options_description access("Access settings", term_width); access.add_options() ("access-key,a", po::value<std::string>( &cd->api_key_)->required(), "Amazon S3 API key. If not set then AWS_ACCESS_KEY_ID " "environment variable is used.") ("secret-key,s", po::value<std::string>( &cd->secret_key)->required(), "Amazon S3 secret key. If not set then AWS_SECRET_ACCESS_KEY " "environment variable is used.") ("use-ssl,l", po::value<bool>( &cd->use_ssl_)->default_value(false), "Use SSL for communications with the Amazon S3 servers") ("compression,m", po::value<bool>( &cd->do_compression_)->default_value(true)->required(), "Use GZIP compression") ; generic.add(access); int thread_num=0, io_threads=0, cpu_threads=0, segment_size=0, segments=0; po::options_description tuning("Tuning", term_width); tuning.add_options() ("thread-num,n", po::value<int>(&thread_num)->default_value(0), "Number of download/upload threads used [0 - autodetect]") ("reader-threads,r", po::value<int>( &io_threads)->default_value(0), "Number of filesystem reader/writer threads [0 - autodetect]") ("compressor-threads,o", po::value<int>( &cpu_threads)->default_value(0), "Number of compressor threads [0 - autodetect]") ("segment-size,g", po::value<int>( &segment_size)->default_value(0), "Segment size in bytes [0 - autodetect, 6291456 - minimum]") ("segments-in-flight,f", po::value<int>( &segments)->default_value(0), "Number of segments in-flight [0 - autodetect]") ; generic.add(tuning); po::options_description sub_data("Subcommands"); sub_data.add_options() ("subcommand", po::value<std::string>()) ("subcommand_params", po::value<stringvec>()->multitoken()); std::map< std::string, std::function<int(context_ptr, const stringvec&, agenda_ptr, bool)> > subcommands_map; subcommands_map["sync"] = boost::bind(&do_rsync, _1, _2, _3, _4); subcommands_map["test"] = boost::bind(&do_test, _1, _2, _3, _4); subcommands_map["touch"] = boost::bind(&do_touch, _1, _2, _3, _4); subcommands_map["rm"] = boost::bind(&do_rm, _1, _2, _3, _4); subcommands_map["du"] = boost::bind(&do_du, _1, _2, _3, _4); subcommands_map["ls"] = boost::bind(&do_ls, _1, _2, _3, _4); subcommands_map["cat"] = boost::bind(&do_cat, _1, _2, _3, _4); subcommands_map["publish"] = boost::bind(&do_publish, _1, _2, _3, _4); stringvec subcommands; for(auto iter=subcommands_map.begin();iter!=subcommands_map.end();++iter) subcommands.push_back(iter->first); std::string cur_subcommand; stringvec cur_sub_params; po::variables_map vm; try { sub_data.add(generic); po::parsed_options parsed = po::command_line_parser(argc, argv) .options(sub_data) .extra_style_parser(boost::bind(&subcommands_parser, _1, subcommands)) .run(); po::store(parsed, vm); cur_subcommand=vm.count("subcommand")==0? "" : vm["subcommand"].as<std::string>(); cur_sub_params=vm.count("subcommand_params")==0? stringvec() : vm["subcommand_params"].as<stringvec>(); if (argc < 2 || vm.count("help")) { if (cur_subcommand.empty()) { std::cout << "Extreme S3 - fast S3 client\n" << generic << "\nThe following commands are supported:\n\t"; for(auto iter=subcommands.begin();iter!=subcommands.end();++iter) std::cout<< *iter <<" "; std::cout << "\nUse --help <command_name> to get more info\n"; } else { std::cout << "Extreme S3 - fast S3 client\n"; subcommands_map[cur_subcommand](cd, cur_sub_params, agenda_ptr(), true); } return 1; } if (cur_subcommand.empty()) { std::cout << "No command specified. Use --help for help\n"; return 2; } } catch(const boost::program_options::error &err) { std::cerr << "Failed to parse command line. Error: " << err.what() << std::endl; return 2; } try { bool found=false; if (vm.count("config")) { // Parse the file and store the options std::string config_file = vm["config"].as<std::string>(); po::store(po::parse_config_file<char>(config_file.c_str(),generic), vm); found = true; } if (!found && getenv("ES3_CONFIG")) { po::store(po::parse_config_file<char>( getenv("ES3_CONFIG"),generic), vm); found = true; } if (!found) { const char *home=getenv("HOME"); if (home) { bf::path cfg=bf::path(home) / ".es3cfg"; if (bf::exists(cfg)) po::store(po::parse_config_file<char>( cfg.c_str(),generic), vm); found=true; } } if (!found) { bf::path cfg=bf::path("/conf") / "es3cfg"; if (bf::exists(cfg)) po::store(po::parse_config_file<char>(cfg.c_str(),generic), vm); found=true; } //Try to parse the environment std::map<std::string, std::string> env_name_map; env_name_map["AWS_ACCESS_KEY_ID"]="access-key"; env_name_map["AWS_SECRET_ACCESS_KEY"]="secret-key"; po::store(po::parse_environment(generic, boost::bind( &get_at, env_name_map, _1)), vm); } catch(const boost::program_options::error &err) { std::cerr << "Failed to parse the configuration file. Error: " << err.what() << std::endl; return 2; } bool no_progress = vm.count("no-progress"); bool no_stats = vm.count("no-stats"); try { po::notify(vm); } catch(const boost::program_options::required_option &option) { std::cerr << "Required option " << option.get_option_name() << " is not present." << std::endl; return 1; } logger::set_verbosity(verbosity); curl_global_init(CURL_GLOBAL_ALL); ON_BLOCK_EXIT(&curl_global_cleanup); if (segments>MAX_IN_FLIGHT) segments=MAX_IN_FLIGHT; else if (segments<=0) segments=40; if (segment_size<MIN_SEGMENT_SIZE) segment_size=MIN_SEGMENT_SIZE; if (cpu_threads<=0) cpu_threads=sysconf(_SC_NPROCESSORS_ONLN)+2; if (io_threads<=0) io_threads=sysconf(_SC_NPROCESSORS_ONLN)*2+2; if (thread_num<=0) thread_num=sysconf(_SC_NPROCESSORS_ONLN)*6+40; if (cur_subcommand=="cat") { no_progress=no_stats=true; //A special hack } agenda_ptr ag(new agenda(thread_num, cpu_threads, io_threads, no_progress, no_stats, segment_size, segments)); try { return subcommands_map[cur_subcommand](cd, cur_sub_params, ag, false); } catch(const es3_exception &ex) { VLOG(0) << "" << ex.what() << std::endl; return 8; } catch(const std::exception &ex) { VLOG(0) << "Unexpected error: " << ex.what() << std::endl; return 8; } } <commit_msg>Also read /conf/es3cfg<commit_after>#include <iostream> #include <boost/program_options.hpp> #include "common.h" #include "scope_guard.h" #include "context.h" #include "agenda.h" #include "commands.h" #include "errors.h" #include <sys/ioctl.h> #include <boost/bind.hpp> #include <curl/curl.h> #include "mimes.h" using namespace es3; namespace po = boost::program_options; int es3::term_width = 80; std::vector<po::option> subcommands_parser(stringvec& args, const stringvec& subcommands) { std::vector<po::option> result; if (args.empty()) return result; stringvec::const_iterator i(args.begin()); stringvec::const_iterator cmd_idx=std::find(subcommands.begin(), subcommands.end(),*i); if (cmd_idx!=subcommands.end()) { po::option opt; opt.string_key = "subcommand"; opt.value.push_back(*i); opt.original_tokens.push_back(*i); result.push_back(opt); for (++i; i != args.end(); ++i) { po::option opt; opt.string_key = "subcommand_params"; opt.value.push_back(*i); opt.original_tokens.push_back(*i); result.push_back(opt); } args.clear(); } return result; } static std::string get_at(const std::map<std::string, std::string> &map, const std::string &key) { return try_get(map, key); } int main(int argc, char **argv) { int verbosity = 0; //Get terminal size (to pretty-print help text) struct winsize w={0}; ioctl(0, TIOCGWINSZ, &w); term_width=(w.ws_col==0)? 80 : w.ws_col; init_mimes(); context_ptr cd(new conn_context()); po::options_description generic("Generic options", term_width); generic.add_options() ("help", "Display this message") ("config,c", po::value<std::string>(), "Path to a file that contains configuration settings") ("verbosity,v", po::value<int>(&verbosity)->default_value(1), "Verbosity level [0 - the lowest, 9 - the highest]") ("no-progress,q", "Quiet mode (no progress indicator)") ("no-stats,t", "Quiet mode (no final stats)") ("scratch-dir,i", po::value<bf::path>(&cd->scratch_dir_) ->default_value(bf::temp_directory_path())->required(), "Path to the scratch directory") ; po::options_description access("Access settings", term_width); access.add_options() ("access-key,a", po::value<std::string>( &cd->api_key_)->required(), "Amazon S3 API key. If not set then AWS_ACCESS_KEY_ID " "environment variable is used.") ("secret-key,s", po::value<std::string>( &cd->secret_key)->required(), "Amazon S3 secret key. If not set then AWS_SECRET_ACCESS_KEY " "environment variable is used.") ("use-ssl,l", po::value<bool>( &cd->use_ssl_)->default_value(false), "Use SSL for communications with the Amazon S3 servers") ("compression,m", po::value<bool>( &cd->do_compression_)->default_value(true)->required(), "Use GZIP compression") ; generic.add(access); int thread_num=0, io_threads=0, cpu_threads=0, segment_size=0, segments=0; po::options_description tuning("Tuning", term_width); tuning.add_options() ("thread-num,n", po::value<int>(&thread_num)->default_value(0), "Number of download/upload threads used [0 - autodetect]") ("reader-threads,r", po::value<int>( &io_threads)->default_value(0), "Number of filesystem reader/writer threads [0 - autodetect]") ("compressor-threads,o", po::value<int>( &cpu_threads)->default_value(0), "Number of compressor threads [0 - autodetect]") ("segment-size,g", po::value<int>( &segment_size)->default_value(0), "Segment size in bytes [0 - autodetect, 6291456 - minimum]") ("segments-in-flight,f", po::value<int>( &segments)->default_value(0), "Number of segments in-flight [0 - autodetect]") ; generic.add(tuning); po::options_description sub_data("Subcommands"); sub_data.add_options() ("subcommand", po::value<std::string>()) ("subcommand_params", po::value<stringvec>()->multitoken()); std::map< std::string, std::function<int(context_ptr, const stringvec&, agenda_ptr, bool)> > subcommands_map; subcommands_map["sync"] = boost::bind(&do_rsync, _1, _2, _3, _4); subcommands_map["test"] = boost::bind(&do_test, _1, _2, _3, _4); subcommands_map["touch"] = boost::bind(&do_touch, _1, _2, _3, _4); subcommands_map["rm"] = boost::bind(&do_rm, _1, _2, _3, _4); subcommands_map["du"] = boost::bind(&do_du, _1, _2, _3, _4); subcommands_map["ls"] = boost::bind(&do_ls, _1, _2, _3, _4); subcommands_map["cat"] = boost::bind(&do_cat, _1, _2, _3, _4); subcommands_map["publish"] = boost::bind(&do_publish, _1, _2, _3, _4); stringvec subcommands; for(auto iter=subcommands_map.begin();iter!=subcommands_map.end();++iter) subcommands.push_back(iter->first); std::string cur_subcommand; stringvec cur_sub_params; po::variables_map vm; try { sub_data.add(generic); po::parsed_options parsed = po::command_line_parser(argc, argv) .options(sub_data) .extra_style_parser(boost::bind(&subcommands_parser, _1, subcommands)) .run(); po::store(parsed, vm); cur_subcommand=vm.count("subcommand")==0? "" : vm["subcommand"].as<std::string>(); cur_sub_params=vm.count("subcommand_params")==0? stringvec() : vm["subcommand_params"].as<stringvec>(); if (argc < 2 || vm.count("help")) { if (cur_subcommand.empty()) { std::cout << "Extreme S3 - fast S3 client\n" << generic << "\nThe following commands are supported:\n\t"; for(auto iter=subcommands.begin();iter!=subcommands.end();++iter) std::cout<< *iter <<" "; std::cout << "\nUse --help <command_name> to get more info\n"; } else { std::cout << "Extreme S3 - fast S3 client\n"; subcommands_map[cur_subcommand](cd, cur_sub_params, agenda_ptr(), true); } return 1; } if (cur_subcommand.empty()) { std::cout << "No command specified. Use --help for help\n"; return 2; } } catch(const boost::program_options::error &err) { std::cerr << "Failed to parse command line. Error: " << err.what() << std::endl; return 2; } try { bool found=false; if (vm.count("config")) { // Parse the file and store the options std::string config_file = vm["config"].as<std::string>(); po::store(po::parse_config_file<char>(config_file.c_str(),generic), vm); found = true; } if (!found && getenv("ES3_CONFIG")) { po::store(po::parse_config_file<char>( getenv("ES3_CONFIG"),generic), vm); found = true; } if (!found) { const char *home=getenv("HOME"); if (home) { bf::path cfg=bf::path(home) / ".es3cfg"; if (bf::exists(cfg)) { po::store(po::parse_config_file<char>( cfg.c_str(),generic), vm); found=true; } } } if (!found) { bf::path cfg=bf::path("/conf") / "es3cfg"; if (bf::exists(cfg)) { po::store(po::parse_config_file<char>(cfg.c_str(),generic), vm); found=true; } } //Try to parse the environment std::map<std::string, std::string> env_name_map; env_name_map["AWS_ACCESS_KEY_ID"]="access-key"; env_name_map["AWS_SECRET_ACCESS_KEY"]="secret-key"; po::store(po::parse_environment(generic, boost::bind( &get_at, env_name_map, _1)), vm); } catch(const boost::program_options::error &err) { std::cerr << "Failed to parse the configuration file. Error: " << err.what() << std::endl; return 2; } bool no_progress = vm.count("no-progress"); bool no_stats = vm.count("no-stats"); try { po::notify(vm); } catch(const boost::program_options::required_option &option) { std::cerr << "Required option " << option.get_option_name() << " is not present." << std::endl; return 1; } logger::set_verbosity(verbosity); curl_global_init(CURL_GLOBAL_ALL); ON_BLOCK_EXIT(&curl_global_cleanup); if (segments>MAX_IN_FLIGHT) segments=MAX_IN_FLIGHT; else if (segments<=0) segments=40; if (segment_size<MIN_SEGMENT_SIZE) segment_size=MIN_SEGMENT_SIZE; if (cpu_threads<=0) cpu_threads=sysconf(_SC_NPROCESSORS_ONLN)+2; if (io_threads<=0) io_threads=sysconf(_SC_NPROCESSORS_ONLN)*2+2; if (thread_num<=0) thread_num=sysconf(_SC_NPROCESSORS_ONLN)*6+40; if (cur_subcommand=="cat") { no_progress=no_stats=true; //A special hack } agenda_ptr ag(new agenda(thread_num, cpu_threads, io_threads, no_progress, no_stats, segment_size, segments)); try { return subcommands_map[cur_subcommand](cd, cur_sub_params, ag, false); } catch(const es3_exception &ex) { VLOG(0) << "" << ex.what() << std::endl; return 8; } catch(const std::exception &ex) { VLOG(0) << "Unexpected error: " << ex.what() << std::endl; return 8; } } <|endoftext|>
<commit_before>#include "wasm-binary.h" #include "wasm-s-parser.h" using namespace std; namespace { string wast2wasm(string input, bool debug = false) { wasm::Module wasm; try { if (debug) std::cerr << "s-parsing..." << std::endl; wasm::SExpressionParser parser(const_cast<char*>(input.c_str())); wasm::Element& root = *parser.root; if (debug) std::cerr << "w-parsing..." << std::endl; wasm::SExpressionWasmBuilder builder(wasm, *root[0]); } catch (wasm::ParseException& p) { p.dump(std::cerr); wasm::Fatal() << "error in parsing input"; } // FIXME: perhaps call validate() here? if (debug) std::cerr << "binarification..." << std::endl; wasm::BufferWithRandomAccess buffer(debug); wasm::WasmBinaryWriter writer(&wasm, buffer, debug); writer.write(); if (debug) std::cerr << "writing to output..." << std::endl; ostringstream output; buffer.writeTo(output); if (debug) std::cerr << "Done." << std::endl; return output.str(); } string evm2wast(string input) { // FIXME: do evm magic here } string evm2wasm(string input) { return wast2wasm(evm2wast(input)); } } int main(int argc, char **argv) { cout << wast2wasm("(module (func $test (i64.const 1)))") << endl; cout << evm2wast("600160020200") << endl; } <commit_msg>Fix C++ example code<commit_after>#include "wasm-binary.h" #include "wasm-s-parser.h" using namespace std; namespace { string wast2wasm(string input, bool debug = false) { wasm::Module wasm; try { if (debug) std::cerr << "s-parsing..." << std::endl; wasm::SExpressionParser parser(const_cast<char*>(input.c_str())); wasm::Element& root = *parser.root; if (debug) std::cerr << "w-parsing..." << std::endl; wasm::SExpressionWasmBuilder builder(wasm, *root[0]); } catch (wasm::ParseException& p) { p.dump(std::cerr); wasm::Fatal() << "error in parsing input"; } // FIXME: perhaps call validate() here? if (debug) std::cerr << "binarification..." << std::endl; wasm::BufferWithRandomAccess buffer(debug); wasm::WasmBinaryWriter writer(&wasm, buffer, debug); writer.write(); if (debug) std::cerr << "writing to output..." << std::endl; ostringstream output; buffer.writeTo(output); if (debug) std::cerr << "Done." << std::endl; return output.str(); } string evm2wast(string input) { // FIXME: do evm magic here return "(module (func $test))"; } string evm2wasm(string input) { return wast2wasm(evm2wast(input)); } } int main(int argc, char **argv) { cout << evm2wasm("600160020200") << endl; } <|endoftext|>
<commit_before>#include <cppunit/BriefTestProgressListener.h> #include <cppunit/TestResult.h> #include <cppunit/TextTestRunner.h> #include <cppunit/extensions/TestFactoryRegistry.h> #include <cppunit/CompilerOutputter.h> #include <unistd.h> namespace { void printTestTree(CppUnit::Test const* root) { std::cerr << root->getName() << "\n"; for (int i(0); i < root->getChildTestCount(); ++i) { printTestTree(root->getChildTestAt(i)); } } } int main(int argc, char *argv[]) { bool list(false); std::string testname; char opt; while ((opt = getopt(argc, argv, "lt:")) != -1) { switch (opt) { case 'l': list = true; break; case 't': testname = optarg; break; default: /* '?' */ std::cerr << "Usage:" << argv[0] << " [-t name] [-l]\n"; return EXIT_FAILURE; } } CppUnit::TestFactoryRegistry & registry( CppUnit::TestFactoryRegistry::getRegistry()); CppUnit::Test *test(registry.makeTest()); if (list) { printTestTree(test); return EXIT_SUCCESS; } CppUnit::TextTestRunner runner; runner.addTest(test); CppUnit::BriefTestProgressListener progress; runner.eventManager().addListener(&progress); runner.setOutputter(new CppUnit::CompilerOutputter( &runner.result(), std::cerr, "%p:%l:")); return runner.run(testname) ? EXIT_SUCCESS : EXIT_FAILURE; } <commit_msg>tests: add missing include<commit_after>#include <cppunit/BriefTestProgressListener.h> #include <cppunit/TestResult.h> #include <cppunit/TextTestRunner.h> #include <cppunit/extensions/TestFactoryRegistry.h> #include <cppunit/CompilerOutputter.h> #include <stdlib.h> #include <unistd.h> namespace { void printTestTree(CppUnit::Test const* root) { std::cerr << root->getName() << "\n"; for (int i(0); i < root->getChildTestCount(); ++i) { printTestTree(root->getChildTestAt(i)); } } } int main(int argc, char *argv[]) { bool list(false); std::string testname; char opt; while ((opt = getopt(argc, argv, "lt:")) != -1) { switch (opt) { case 'l': list = true; break; case 't': testname = optarg; break; default: /* '?' */ std::cerr << "Usage:" << argv[0] << " [-t name] [-l]\n"; return EXIT_FAILURE; } } CppUnit::TestFactoryRegistry & registry( CppUnit::TestFactoryRegistry::getRegistry()); CppUnit::Test *test(registry.makeTest()); if (list) { printTestTree(test); return EXIT_SUCCESS; } CppUnit::TextTestRunner runner; runner.addTest(test); CppUnit::BriefTestProgressListener progress; runner.eventManager().addListener(&progress); runner.setOutputter(new CppUnit::CompilerOutputter( &runner.result(), std::cerr, "%p:%l:")); return runner.run(testname) ? EXIT_SUCCESS : EXIT_FAILURE; } <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ //$Id$ #ifndef FEATURE_STYLE_PROCESSOR_HPP #define FEATURE_STYLE_PROCESSOR_HPP //stl #include <vector> // boost #include <boost/progress.hpp> // mapnik #include <mapnik/envelope.hpp> #include <mapnik/datasource.hpp> #include <mapnik/layer.hpp> #include <mapnik/map.hpp> #include <mapnik/attribute_collector.hpp> #include <mapnik/utils.hpp> namespace mapnik { template <typename Processor> class feature_style_processor { struct symbol_dispatch : public boost::static_visitor<> { symbol_dispatch (Processor & output,Feature const& f) : output_(output),f_(f) {} template <typename T> void operator () (T const& sym) const { output_.process(sym,f_); } Processor & output_; Feature const& f_; }; public: feature_style_processor(Map const& m) : m_(m) {} void apply() { boost::progress_timer t; Processor & p = static_cast<Processor&>(*this); p.start_map_processing(m_); std::vector<Layer>::const_iterator itr = m_.layers().begin(); while (itr != m_.layers().end()) { if (itr->isVisible(m_.scale()) && itr->envelope().intersects(m_.getCurrentExtent())) { apply_to_layer(*itr,p); } ++itr; } p.end_map_processing(m_); } private: void apply_to_layer(Layer const& lay,Processor & p) { p.start_layer_processing(lay); datasource *ds=lay.datasource().get(); if (ds) { Envelope<double> const& bbox=m_.getCurrentExtent(); double scale = m_.scale(); std::vector<std::string> const& style_names = lay.styles(); std::vector<std::string>::const_iterator stylesIter = style_names.begin(); while (stylesIter != style_names.end()) { std::set<std::string> names; attribute_collector<Feature> collector(names); std::vector<rule_type*> if_rules; std::vector<rule_type*> else_rules; bool active_rules=false; feature_type_style const& style=m_.find_style(*stylesIter++); const std::vector<rule_type>& rules=style.get_rules(); std::vector<rule_type>::const_iterator ruleIter=rules.begin(); query q(bbox); //BBOX query while (ruleIter!=rules.end()) { if (ruleIter->active(scale)) { active_rules=true; ruleIter->accept(collector); if (ruleIter->has_else_filter()) { else_rules.push_back(const_cast<rule_type*>(&(*ruleIter))); } else { if_rules.push_back(const_cast<rule_type*>(&(*ruleIter))); } } ++ruleIter; } std::set<std::string>::const_iterator namesIter=names.begin(); // push all property names while (namesIter!=names.end()) { q.add_property_name(*namesIter); ++namesIter; } if (active_rules) { featureset_ptr fs=ds->features(q); if (fs) { feature_ptr feature; while ((feature = fs->next())) { bool do_else=true; std::vector<rule_type*>::const_iterator itr=if_rules.begin(); while (itr!=if_rules.end()) { filter_ptr const& filter=(*itr)->get_filter(); if (filter->pass(*feature)) { do_else=false; const symbolizers& symbols = (*itr)->get_symbolizers(); symbolizers::const_iterator symIter=symbols.begin(); while (symIter!=symbols.end()) { boost::apply_visitor (symbol_dispatch(p,*feature),*symIter++); } } ++itr; } if (do_else) { //else filter std::vector<rule_type*>::const_iterator itr= else_rules.begin(); while (itr != else_rules.end()) { const symbolizers& symbols = (*itr)->get_symbolizers(); symbolizers::const_iterator symIter=symbols.begin(); while (symIter!=symbols.end()) { boost::apply_visitor (symbol_dispatch(p,*feature),*symIter++); } ++itr; } } } } } } } p.end_layer_processing(lay); } Map const& m_; }; } #endif //FEATURE_STYLE_PROCESSOR_HPP <commit_msg>use boost::shared_ptr<datasource> <commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ //$Id$ #ifndef FEATURE_STYLE_PROCESSOR_HPP #define FEATURE_STYLE_PROCESSOR_HPP //stl #include <vector> // boost #include <boost/progress.hpp> // mapnik #include <mapnik/envelope.hpp> #include <mapnik/datasource.hpp> #include <mapnik/layer.hpp> #include <mapnik/map.hpp> #include <mapnik/attribute_collector.hpp> #include <mapnik/utils.hpp> namespace mapnik { template <typename Processor> class feature_style_processor { struct symbol_dispatch : public boost::static_visitor<> { symbol_dispatch (Processor & output,Feature const& f) : output_(output),f_(f) {} template <typename T> void operator () (T const& sym) const { output_.process(sym,f_); } Processor & output_; Feature const& f_; }; public: feature_style_processor(Map const& m) : m_(m) {} void apply() { boost::progress_timer t; Processor & p = static_cast<Processor&>(*this); p.start_map_processing(m_); std::vector<Layer>::const_iterator itr = m_.layers().begin(); while (itr != m_.layers().end()) { if (itr->isVisible(m_.scale()) && itr->envelope().intersects(m_.getCurrentExtent())) { apply_to_layer(*itr,p); } ++itr; } p.end_map_processing(m_); } private: void apply_to_layer(Layer const& lay,Processor & p) { p.start_layer_processing(lay); boost::shared_ptr<datasource> ds=lay.datasource(); if (ds) { Envelope<double> const& bbox=m_.getCurrentExtent(); double scale = m_.scale(); std::vector<std::string> const& style_names = lay.styles(); std::vector<std::string>::const_iterator stylesIter = style_names.begin(); while (stylesIter != style_names.end()) { std::set<std::string> names; attribute_collector<Feature> collector(names); std::vector<rule_type*> if_rules; std::vector<rule_type*> else_rules; bool active_rules=false; feature_type_style const& style=m_.find_style(*stylesIter++); const std::vector<rule_type>& rules=style.get_rules(); std::vector<rule_type>::const_iterator ruleIter=rules.begin(); query q(bbox); //BBOX query while (ruleIter!=rules.end()) { if (ruleIter->active(scale)) { active_rules=true; ruleIter->accept(collector); if (ruleIter->has_else_filter()) { else_rules.push_back(const_cast<rule_type*>(&(*ruleIter))); } else { if_rules.push_back(const_cast<rule_type*>(&(*ruleIter))); } } ++ruleIter; } std::set<std::string>::const_iterator namesIter=names.begin(); // push all property names while (namesIter!=names.end()) { q.add_property_name(*namesIter); ++namesIter; } if (active_rules) { featureset_ptr fs=ds->features(q); if (fs) { feature_ptr feature; while ((feature = fs->next())) { bool do_else=true; std::vector<rule_type*>::const_iterator itr=if_rules.begin(); while (itr!=if_rules.end()) { filter_ptr const& filter=(*itr)->get_filter(); if (filter->pass(*feature)) { do_else=false; const symbolizers& symbols = (*itr)->get_symbolizers(); symbolizers::const_iterator symIter=symbols.begin(); while (symIter!=symbols.end()) { boost::apply_visitor (symbol_dispatch(p,*feature),*symIter++); } } ++itr; } if (do_else) { //else filter std::vector<rule_type*>::const_iterator itr= else_rules.begin(); while (itr != else_rules.end()) { const symbolizers& symbols = (*itr)->get_symbolizers(); symbolizers::const_iterator symIter=symbols.begin(); while (symIter!=symbols.end()) { boost::apply_visitor (symbol_dispatch(p,*feature),*symIter++); } ++itr; } } } } } } } p.end_layer_processing(lay); } Map const& m_; }; } #endif //FEATURE_STYLE_PROCESSOR_HPP <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ //$Id$ #ifndef FEATURE_STYLE_PROCESSOR_HPP #define FEATURE_STYLE_PROCESSOR_HPP // mapnik #include <mapnik/envelope.hpp> #include <mapnik/datasource.hpp> #include <mapnik/layer.hpp> #include <mapnik/map.hpp> #include <mapnik/attribute_collector.hpp> #include <mapnik/utils.hpp> #include <mapnik/projection.hpp> #include <mapnik/scale_denominator.hpp> // boost #include <boost/progress.hpp> //stl #include <vector> namespace mapnik { template <typename Processor> class feature_style_processor { struct symbol_dispatch : public boost::static_visitor<> { symbol_dispatch (Processor & output, Feature const& f, proj_transform const& prj_trans) : output_(output), f_(f), prj_trans_(prj_trans) {} template <typename T> void operator () (T const& sym) const { output_.process(sym,f_,prj_trans_); } Processor & output_; Feature const& f_; proj_transform const& prj_trans_; }; public: feature_style_processor(Map const& m) : m_(m) {} void apply() { #ifdef MAPNIK_DEBUG boost::progress_timer t(std::clog); #endif Processor & p = static_cast<Processor&>(*this); p.start_map_processing(m_); try { projection proj(m_.srs()); // map projection double scale_denom = scale_denominator(m_,proj.is_geographic()); #ifdef MAPNIK_DEBUG std::clog << "scale denominator = " << scale_denom << "\n"; #endif std::vector<Layer>::const_iterator itr = m_.layers().begin(); std::vector<Layer>::const_iterator end = m_.layers().end(); while (itr != end) { if (itr->isVisible(scale_denom)) { apply_to_layer(*itr, p, proj, scale_denom); } ++itr; } } catch (proj_init_error& ex) { std::clog << "proj_init_error:" << ex.what() << "\n"; } p.end_map_processing(m_); } private: void apply_to_layer(Layer const& lay, Processor & p, projection const& proj0,double scale_denom) { p.start_layer_processing(lay); boost::shared_ptr<datasource> ds=lay.datasource(); if (ds) { Envelope<double> const& ext=m_.getCurrentExtent(); projection proj1(lay.srs()); proj_transform prj_trans(proj0,proj1); Envelope<double> layer_ext = lay.envelope(); double lx0 = layer_ext.minx(); double ly0 = layer_ext.miny(); double lz0 = 0.0; double lx1 = layer_ext.maxx(); double ly1 = layer_ext.maxy(); double lz1 = 0.0; // back project layers extent into main map projection prj_trans.backward(lx0,ly0,lz0); prj_trans.backward(lx1,ly1,lz1); // if no intersection then nothing to do for layer if ( lx0 > ext.maxx() || lx1 < ext.minx() || ly0 > ext.maxy() || ly1 < ext.miny() ) { return; } // clip query bbox lx0 = std::max(ext.minx(),lx0); ly0 = std::max(ext.miny(),ly0); lx1 = std::min(ext.maxx(),lx1); ly1 = std::min(ext.maxy(),ly1); prj_trans.forward(lx0,ly0,lz0); prj_trans.forward(lx1,ly1,lz1); Envelope<double> bbox(lx0,ly0,lx1,ly1); double resolution = m_.getWidth()/bbox.width(); query q(bbox,resolution); //BBOX query std::vector<std::string> const& style_names = lay.styles(); std::vector<std::string>::const_iterator stylesIter = style_names.begin(); std::vector<std::string>::const_iterator stylesEnd = style_names.end(); for (;stylesIter != stylesEnd; ++stylesIter) { std::set<std::string> names; attribute_collector<Feature> collector(names); std::vector<rule_type*> if_rules; std::vector<rule_type*> else_rules; bool active_rules=false; boost::optional<feature_type_style const&> style=m_.find_style(*stylesIter); if (!style) continue; const std::vector<rule_type>& rules=(*style).get_rules(); std::vector<rule_type>::const_iterator ruleIter=rules.begin(); std::vector<rule_type>::const_iterator ruleEnd=rules.end(); for (;ruleIter!=ruleEnd;++ruleIter) { if (ruleIter->active(scale_denom)) { active_rules=true; ruleIter->accept(collector); if (ruleIter->has_else_filter()) { else_rules.push_back(const_cast<rule_type*>(&(*ruleIter))); } else { if_rules.push_back(const_cast<rule_type*>(&(*ruleIter))); } } } std::set<std::string>::const_iterator namesIter=names.begin(); std::set<std::string>::const_iterator namesEnd =names.end(); // push all property names for (;namesIter!=namesEnd;++namesIter) { q.add_property_name(*namesIter); } if (active_rules) { featureset_ptr fs=ds->features(q); if (fs) { feature_ptr feature; while ((feature = fs->next())) { bool do_else=true; std::vector<rule_type*>::const_iterator itr=if_rules.begin(); std::vector<rule_type*>::const_iterator end=if_rules.end(); for (;itr != end;++itr) { filter_ptr const& filter=(*itr)->get_filter(); if (filter->pass(*feature)) { do_else=false; const symbolizers& symbols = (*itr)->get_symbolizers(); symbolizers::const_iterator symIter=symbols.begin(); symbolizers::const_iterator symEnd =symbols.end(); for (;symIter != symEnd;++symIter) { boost::apply_visitor (symbol_dispatch(p,*feature,prj_trans),*symIter); } } } if (do_else) { //else filter std::vector<rule_type*>::const_iterator itr= else_rules.begin(); std::vector<rule_type*>::const_iterator end= else_rules.end(); for (;itr != end;++itr) { const symbolizers& symbols = (*itr)->get_symbolizers(); symbolizers::const_iterator symIter= symbols.begin(); symbolizers::const_iterator symEnd = symbols.end(); for (;symIter!=symEnd;++symIter) { boost::apply_visitor (symbol_dispatch(p,*feature,prj_trans),*symIter); } } } } } } } } p.end_layer_processing(lay); } Map const& m_; }; } #endif //FEATURE_STYLE_PROCESSOR_HPP <commit_msg>+ use 'buffered' extent in bbox query<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ //$Id$ #ifndef FEATURE_STYLE_PROCESSOR_HPP #define FEATURE_STYLE_PROCESSOR_HPP // mapnik #include <mapnik/envelope.hpp> #include <mapnik/datasource.hpp> #include <mapnik/layer.hpp> #include <mapnik/map.hpp> #include <mapnik/attribute_collector.hpp> #include <mapnik/utils.hpp> #include <mapnik/projection.hpp> #include <mapnik/scale_denominator.hpp> // boost #include <boost/progress.hpp> //stl #include <vector> namespace mapnik { template <typename Processor> class feature_style_processor { struct symbol_dispatch : public boost::static_visitor<> { symbol_dispatch (Processor & output, Feature const& f, proj_transform const& prj_trans) : output_(output), f_(f), prj_trans_(prj_trans) {} template <typename T> void operator () (T const& sym) const { output_.process(sym,f_,prj_trans_); } Processor & output_; Feature const& f_; proj_transform const& prj_trans_; }; public: feature_style_processor(Map const& m) : m_(m) {} void apply() { #ifdef MAPNIK_DEBUG boost::progress_timer t(std::clog); #endif Processor & p = static_cast<Processor&>(*this); p.start_map_processing(m_); try { projection proj(m_.srs()); // map projection double scale_denom = scale_denominator(m_,proj.is_geographic()); #ifdef MAPNIK_DEBUG std::clog << "scale denominator = " << scale_denom << "\n"; #endif std::vector<Layer>::const_iterator itr = m_.layers().begin(); std::vector<Layer>::const_iterator end = m_.layers().end(); while (itr != end) { if (itr->isVisible(scale_denom)) { apply_to_layer(*itr, p, proj, scale_denom); } ++itr; } } catch (proj_init_error& ex) { std::clog << "proj_init_error:" << ex.what() << "\n"; } p.end_map_processing(m_); } private: void apply_to_layer(Layer const& lay, Processor & p, projection const& proj0,double scale_denom) { p.start_layer_processing(lay); boost::shared_ptr<datasource> ds=lay.datasource(); if (ds) { Envelope<double> ext = m_.get_buffered_extent(); projection proj1(lay.srs()); proj_transform prj_trans(proj0,proj1); Envelope<double> layer_ext = lay.envelope(); double lx0 = layer_ext.minx(); double ly0 = layer_ext.miny(); double lz0 = 0.0; double lx1 = layer_ext.maxx(); double ly1 = layer_ext.maxy(); double lz1 = 0.0; // back project layers extent into main map projection prj_trans.backward(lx0,ly0,lz0); prj_trans.backward(lx1,ly1,lz1); // if no intersection then nothing to do for layer if ( lx0 > ext.maxx() || lx1 < ext.minx() || ly0 > ext.maxy() || ly1 < ext.miny() ) { return; } // clip query bbox lx0 = std::max(ext.minx(),lx0); ly0 = std::max(ext.miny(),ly0); lx1 = std::min(ext.maxx(),lx1); ly1 = std::min(ext.maxy(),ly1); prj_trans.forward(lx0,ly0,lz0); prj_trans.forward(lx1,ly1,lz1); Envelope<double> bbox(lx0,ly0,lx1,ly1); double resolution = m_.getWidth()/bbox.width(); query q(bbox,resolution); //BBOX query std::vector<std::string> const& style_names = lay.styles(); std::vector<std::string>::const_iterator stylesIter = style_names.begin(); std::vector<std::string>::const_iterator stylesEnd = style_names.end(); for (;stylesIter != stylesEnd; ++stylesIter) { std::set<std::string> names; attribute_collector<Feature> collector(names); std::vector<rule_type*> if_rules; std::vector<rule_type*> else_rules; bool active_rules=false; boost::optional<feature_type_style const&> style=m_.find_style(*stylesIter); if (!style) continue; const std::vector<rule_type>& rules=(*style).get_rules(); std::vector<rule_type>::const_iterator ruleIter=rules.begin(); std::vector<rule_type>::const_iterator ruleEnd=rules.end(); for (;ruleIter!=ruleEnd;++ruleIter) { if (ruleIter->active(scale_denom)) { active_rules=true; ruleIter->accept(collector); if (ruleIter->has_else_filter()) { else_rules.push_back(const_cast<rule_type*>(&(*ruleIter))); } else { if_rules.push_back(const_cast<rule_type*>(&(*ruleIter))); } } } std::set<std::string>::const_iterator namesIter=names.begin(); std::set<std::string>::const_iterator namesEnd =names.end(); // push all property names for (;namesIter!=namesEnd;++namesIter) { q.add_property_name(*namesIter); } if (active_rules) { featureset_ptr fs=ds->features(q); if (fs) { feature_ptr feature; while ((feature = fs->next())) { bool do_else=true; std::vector<rule_type*>::const_iterator itr=if_rules.begin(); std::vector<rule_type*>::const_iterator end=if_rules.end(); for (;itr != end;++itr) { filter_ptr const& filter=(*itr)->get_filter(); if (filter->pass(*feature)) { do_else=false; const symbolizers& symbols = (*itr)->get_symbolizers(); symbolizers::const_iterator symIter=symbols.begin(); symbolizers::const_iterator symEnd =symbols.end(); for (;symIter != symEnd;++symIter) { boost::apply_visitor (symbol_dispatch(p,*feature,prj_trans),*symIter); } } } if (do_else) { //else filter std::vector<rule_type*>::const_iterator itr= else_rules.begin(); std::vector<rule_type*>::const_iterator end= else_rules.end(); for (;itr != end;++itr) { const symbolizers& symbols = (*itr)->get_symbolizers(); symbolizers::const_iterator symIter= symbols.begin(); symbolizers::const_iterator symEnd = symbols.end(); for (;symIter!=symEnd;++symIter) { boost::apply_visitor (symbol_dispatch(p,*feature,prj_trans),*symIter); } } } } } } } } p.end_layer_processing(lay); } Map const& m_; }; } #endif //FEATURE_STYLE_PROCESSOR_HPP <|endoftext|>
<commit_before>#include "ssnes_dsp.h" #include <string.h> #include <stdio.h> #include <stdlib.h> #include "wahwah.h" #include "inireader.h" #include "abstract_plugin.hpp" struct PlugWah : public AbstractPlugin { WahWah wah_l; WahWah wah_r; float buf[4096]; PlugWah(float freq, float startphase, float res, float depth, float freqofs) { PluginOption opt = {0}; opt.type = PluginOption::Type::Double; opt.id = FREQ; opt.description = "LFO frequency"; opt.d.min = 0.1; opt.d.max = 10.0; opt.d.current = freq; dsp_options.push_back(opt); opt.id = STARTPHASE; opt.description = "LFO start phase"; opt.d.min = 0.0; opt.d.max = 360.0; opt.d.current = startphase; dsp_options.push_back(opt); opt.id = RES; opt.description = "LFO resonance"; opt.d.min = 0.0; opt.d.max = 10.0; opt.d.current = res; dsp_options.push_back(opt); opt.id = DEPTH; opt.description = "LFO depth"; opt.d.min = 0.0; opt.d.max = 10.0; opt.d.current = depth; dsp_options.push_back(opt); opt.id = FREQOFS; opt.description = "LFO frequency offset"; opt.d.min = 0.1; opt.d.max = 10.0; opt.d.current = freqofs; dsp_options.push_back(opt); } void set_option(PluginOption::ID id, double val) { switch (id) { case FREQ: wah_l.SetLFOFreq(val); wah_r.SetLFOFreq(val); break; case STARTPHASE: wah_l.SetLFOStartPhase(val); wah_r.SetLFOStartPhase(val); break; case RES: wah_l.SetResonance(val); wah_r.SetResonance(val); break; case DEPTH: wah_l.SetDepth(val); wah_r.SetDepth(val); break; case FREQOFS: wah_l.SetFreqOffset(val); wah_r.SetFreqOffset(val); break; } } enum IDs : PluginOption::ID { FREQ, STARTPHASE, RES, DEPTH, FREQOFS }; }; static void* dsp_init(const ssnes_dsp_info_t *info) { CIniReader iniReader("ssnes_effect.cfg"); float freq = iniReader.ReadFloat("wah", "lfo_frequency",1.5); float startphase = iniReader.ReadFloat("wah","lfo_start_phase",0.0); float res = iniReader.ReadFloat("wah","lfo_resonance",2.5); float depth = iniReader.ReadInteger("wah","lfo_depth",0.70); float freqofs = iniReader.ReadInteger("wah","lfo_frequency_offset",0.30); PlugWah *wah = new PlugWah(freq, startphase, res, depth, freqofs); wah->wah_l.SetDepth(depth); wah->wah_l.SetFreqOffset(freqofs); wah->wah_l.SetLFOFreq(freq); wah->wah_l.SetLFOStartPhase(startphase); wah->wah_l.SetResonance(res); wah->wah_l.init(info->input_rate); wah->wah_r.SetDepth(depth); wah->wah_r.SetFreqOffset(freqofs); wah->wah_r.SetLFOFreq(freq); wah->wah_r.SetLFOStartPhase(startphase); wah->wah_r.SetResonance(res); wah->wah_r.init(info->input_rate); return wah; } static void dsp_process(void *data, ssnes_dsp_output_t *output, const ssnes_dsp_input_t *input) { PlugWah *wah = reinterpret_cast<PlugWah*>(data); output->samples = wah->buf; int num_samples = input->frames * 2; for (int i = 0; i<num_samples;) { wah->buf[i] = wah->wah_l.Process(input->samples[i]); i++; wah->buf[i] = wah->wah_r.Process(input->samples[i]); i++; } output->frames = input->frames; output->should_resample = SSNES_TRUE; } static void dsp_free(void *data) { delete reinterpret_cast<PlugWah*>(data); } static void dsp_config(void*) {} const ssnes_dsp_plugin_t dsp_plug = { dsp_init, dsp_process, dsp_free, SSNES_DSP_API_VERSION, dsp_config, "Wah plugin" }; SSNES_API_EXPORT const ssnes_dsp_plugin_t* SSNES_API_CALLTYPE ssnes_dsp_plugin_init(void) { return &dsp_plug; } <commit_msg>Fix up Wah.<commit_after>#include "ssnes_dsp.h" #include <string.h> #include <stdio.h> #include <stdlib.h> #include "wahwah.h" #include "inireader.h" #include "abstract_plugin.hpp" struct PlugWah : public AbstractPlugin { WahWah wah_l; WahWah wah_r; float buf[4096]; PlugWah(float freq, float startphase, float res, float depth, float freqofs) { PluginOption opt = {0}; opt.type = PluginOption::Type::Double; opt.id = FREQ; opt.description = "LFO frequency"; opt.d.min = 0.1; opt.d.max = 10.0; opt.d.current = freq; dsp_options.push_back(opt); opt.id = STARTPHASE; opt.description = "LFO start phase"; opt.d.min = 0.0; opt.d.max = 360.0; opt.d.current = startphase; dsp_options.push_back(opt); opt.id = RES; opt.description = "LFO resonance"; opt.d.min = 0.0; opt.d.max = 10.0; opt.d.current = res; dsp_options.push_back(opt); opt.id = DEPTH; opt.description = "LFO depth"; opt.d.min = 0.0; opt.d.max = 1.0; opt.d.current = depth; dsp_options.push_back(opt); opt.id = FREQOFS; opt.description = "LFO frequency offset"; opt.d.min = 0.0; opt.d.max = 0.95; opt.d.current = freqofs; dsp_options.push_back(opt); } void set_option_double(PluginOption::ID id, double val) { switch (id) { case FREQ: wah_l.SetLFOFreq(val); wah_r.SetLFOFreq(val); break; case STARTPHASE: wah_l.SetLFOStartPhase(val); wah_r.SetLFOStartPhase(val); break; case RES: wah_l.SetResonance(val); wah_r.SetResonance(val); break; case DEPTH: wah_l.SetDepth(val); wah_r.SetDepth(val); break; case FREQOFS: wah_l.SetFreqOffset(val); wah_r.SetFreqOffset(val); break; } } enum IDs : PluginOption::ID { FREQ, STARTPHASE, RES, DEPTH, FREQOFS }; }; static void* dsp_init(const ssnes_dsp_info_t *info) { CIniReader iniReader("ssnes_effect.cfg"); float freq = iniReader.ReadFloat("wah", "lfo_frequency",1.5); float startphase = iniReader.ReadFloat("wah","lfo_start_phase",0.0); float res = iniReader.ReadFloat("wah","lfo_resonance",2.5); float depth = iniReader.ReadFloat("wah","lfo_depth",0.70); float freqofs = iniReader.ReadFloat("wah","lfo_frequency_offset",0.30); PlugWah *wah = new PlugWah(freq, startphase, res, depth, freqofs); wah->wah_l.SetDepth(depth); wah->wah_l.SetFreqOffset(freqofs); wah->wah_l.SetLFOFreq(freq); wah->wah_l.SetLFOStartPhase(startphase); wah->wah_l.SetResonance(res); wah->wah_l.init(info->input_rate); wah->wah_r.SetDepth(depth); wah->wah_r.SetFreqOffset(freqofs); wah->wah_r.SetLFOFreq(freq); wah->wah_r.SetLFOStartPhase(startphase); wah->wah_r.SetResonance(res); wah->wah_r.init(info->input_rate); return wah; } static void dsp_process(void *data, ssnes_dsp_output_t *output, const ssnes_dsp_input_t *input) { PlugWah *wah = reinterpret_cast<PlugWah*>(data); output->samples = wah->buf; int num_samples = input->frames * 2; for (int i = 0; i<num_samples;) { wah->buf[i] = wah->wah_l.Process(input->samples[i]); i++; wah->buf[i] = wah->wah_r.Process(input->samples[i]); i++; } output->frames = input->frames; output->should_resample = SSNES_TRUE; } static void dsp_free(void *data) { delete reinterpret_cast<PlugWah*>(data); } static void dsp_config(void*) {} const ssnes_dsp_plugin_t dsp_plug = { dsp_init, dsp_process, dsp_free, SSNES_DSP_API_VERSION, dsp_config, "Wah plugin" }; SSNES_API_EXPORT const ssnes_dsp_plugin_t* SSNES_API_CALLTYPE ssnes_dsp_plugin_init(void) { return &dsp_plug; } <|endoftext|>
<commit_before>/** * @file llfloaterdeleteenvpreset.cpp * @brief Floater to delete a water / sky / day cycle preset. * * $LicenseInfo:firstyear=2011&license=viewerlgpl$ * Second Life Viewer Source Code * Copyright (C) 2011, Linden Research, Inc. * * 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; * version 2.1 of the License only. * * 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 * * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA * $/LicenseInfo$ */ #include "llviewerprecompiledheaders.h" #include "llfloaterdeleteenvpreset.h" // libs #include "llbutton.h" #include "llcombobox.h" #include "llnotificationsutil.h" // newview #include "lldaycyclemanager.h" #include "llwaterparammanager.h" static bool confirmation_callback(const LLSD& notification, const LLSD& response, boost::function<void()> cb) { S32 option = LLNotificationsUtil::getSelectedOption(notification, response); if (option == 0) { cb(); } return false; } LLFloaterDeleteEnvPreset::LLFloaterDeleteEnvPreset(const LLSD &key) : LLFloater(key) , mPresetCombo(NULL) { } // virtual BOOL LLFloaterDeleteEnvPreset::postBuild() { mPresetCombo = getChild<LLComboBox>("preset_combo"); getChild<LLButton>("delete")->setCommitCallback(boost::bind(&LLFloaterDeleteEnvPreset::onBtnDelete, this)); getChild<LLButton>("cancel")->setCommitCallback(boost::bind(&LLFloaterDeleteEnvPreset::onBtnCancel, this)); // Listen to presets addition/removal. LLDayCycleManager::instance().setModifyCallback(boost::bind(&LLFloaterDeleteEnvPreset::populateDayCyclesList, this)); LLWLParamManager::instance().setPresetListChangeCallback(boost::bind(&LLFloaterDeleteEnvPreset::populateSkyPresetsList, this)); return TRUE; } // virtual void LLFloaterDeleteEnvPreset::onOpen(const LLSD& key) { std::string param = key.asString(); std::string floater_title = getString(std::string("title_") + param); std::string combo_label = getString(std::string("label_" + param)); // Update floater title. setTitle(floater_title); // Update the combobox label. getChild<LLUICtrl>("label")->setValue(combo_label); // Populate the combobox. if (param == "water") { populateWaterPresetsList(); getChild<LLButton>("delete")->setEnabled(FALSE); // not implemented yet } else if (param == "sky") { populateSkyPresetsList(); } else if (param == "day_cycle") { populateDayCyclesList(); } else { llwarns << "Unrecognized key" << llendl; } } void LLFloaterDeleteEnvPreset::onBtnDelete() { std::string param = mKey.asString(); std::string preset_name = mPresetCombo->getValue().asString(); boost::function<void()> confirm_cb; if (param == "water") { llwarns << "Deleting water presets not implemented" << llendl; return; } else if (param == "sky") { // Don't allow deleting presets referenced by local day cycles. if (LLDayCycleManager::instance().isSkyPresetReferenced(preset_name)) { LLNotificationsUtil::add("GenericAlert", LLSD().with("MESSAGE", getString("msg_sky_is_referenced"))); return; } LLWLParamManager& wl_mgr = LLWLParamManager::instance(); // Don't allow deleting system presets. if (wl_mgr.isSystemPreset(preset_name)) { LLNotificationsUtil::add("WLNoEditDefault"); return; } confirm_cb = boost::bind(&LLFloaterDeleteEnvPreset::onDeleteSkyPresetConfirmation, this); } else if (param == "day_cycle") { LLDayCycleManager& day_mgr = LLDayCycleManager::instance(); // Don't allow deleting system presets. if (day_mgr.isSystemPreset(preset_name)) { LLNotificationsUtil::add("WLNoEditDefault"); return; } confirm_cb = boost::bind(&LLFloaterDeleteEnvPreset::onDeleteDayCycleConfirmation, this); } else { llwarns << "Unrecognized key" << llendl; } LLSD args; args["MESSAGE"] = getString("msg_confirm_deletion"); LLNotificationsUtil::add("GenericAlertYesCancel", args, LLSD(), boost::bind(&confirmation_callback, _1, _2, confirm_cb)); } void LLFloaterDeleteEnvPreset::onBtnCancel() { closeFloater(); } void LLFloaterDeleteEnvPreset::populateWaterPresetsList() { if (mKey.asString() != "water") return; mPresetCombo->removeall(); // *TODO: Reload the list when user preferences change. LLWaterParamManager& water_mgr = LLWaterParamManager::instance(); LL_DEBUGS("Windlight") << "Current water preset: " << water_mgr.mCurParams.mName << LL_ENDL; const std::map<std::string, LLWaterParamSet> &water_params_map = water_mgr.mParamList; for (std::map<std::string, LLWaterParamSet>::const_iterator it = water_params_map.begin(); it != water_params_map.end(); it++) { std::string name = it->first; bool enabled = (name != water_mgr.mCurParams.mName); // don't allow deleting current preset mPresetCombo->add(name, ADD_BOTTOM, enabled); } postPopulate(); } void LLFloaterDeleteEnvPreset::populateSkyPresetsList() { if (mKey.asString() != "sky") return; mPresetCombo->removeall(); std::string cur_preset; LLEnvManagerNew& env_mgr = LLEnvManagerNew::instance(); if (!env_mgr.getUseRegionSettings() && env_mgr.getUseFixedSky()) { cur_preset = env_mgr.getSkyPresetName(); } // *TODO: Reload the list when user preferences change. LLWLParamManager& sky_mgr = LLWLParamManager::instance(); const std::map<LLWLParamKey, LLWLParamSet> &sky_params_map = sky_mgr.mParamList; for (std::map<LLWLParamKey, LLWLParamSet>::const_iterator it = sky_params_map.begin(); it != sky_params_map.end(); it++) { const LLWLParamKey& key = it->first; // list only local user presets if (key.scope == LLEnvKey::SCOPE_REGION || sky_mgr.isSystemPreset(key.name)) { continue; } bool enabled = (key.name != cur_preset); mPresetCombo->add(key.name, ADD_BOTTOM, enabled); } postPopulate(); } void LLFloaterDeleteEnvPreset::populateDayCyclesList() { if (mKey.asString() != "day_cycle") return; mPresetCombo->removeall(); // *TODO: Disable current day cycle. const LLDayCycleManager::dc_map_t& map = LLDayCycleManager::instance().getPresets(); for (LLDayCycleManager::dc_map_t::const_iterator it = map.begin(); it != map.end(); ++it) { mPresetCombo->add(it->first); } postPopulate(); } void LLFloaterDeleteEnvPreset::postPopulate() { // Handle empty list. S32 n_items = mPresetCombo->getItemCount(); if (n_items == 0) { mPresetCombo->setLabel(getString("combo_label")); } getChild<LLButton>("delete")->setEnabled(n_items > 0); } void LLFloaterDeleteEnvPreset::onDeleteDayCycleConfirmation() { LLDayCycleManager::instance().deletePreset(mPresetCombo->getValue().asString()); } void LLFloaterDeleteEnvPreset::onDeleteSkyPresetConfirmation() { LLWLParamKey key(mPresetCombo->getValue().asString(), LLEnvKey::SCOPE_LOCAL); LLWLParamManager::instance().removeParamSet(key, true); } <commit_msg>STORM-1253 WIP Disable removing current day cycle.<commit_after>/** * @file llfloaterdeleteenvpreset.cpp * @brief Floater to delete a water / sky / day cycle preset. * * $LicenseInfo:firstyear=2011&license=viewerlgpl$ * Second Life Viewer Source Code * Copyright (C) 2011, Linden Research, Inc. * * 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; * version 2.1 of the License only. * * 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 * * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA * $/LicenseInfo$ */ #include "llviewerprecompiledheaders.h" #include "llfloaterdeleteenvpreset.h" // libs #include "llbutton.h" #include "llcombobox.h" #include "llnotificationsutil.h" // newview #include "lldaycyclemanager.h" #include "llwaterparammanager.h" static bool confirmation_callback(const LLSD& notification, const LLSD& response, boost::function<void()> cb) { S32 option = LLNotificationsUtil::getSelectedOption(notification, response); if (option == 0) { cb(); } return false; } LLFloaterDeleteEnvPreset::LLFloaterDeleteEnvPreset(const LLSD &key) : LLFloater(key) , mPresetCombo(NULL) { } // virtual BOOL LLFloaterDeleteEnvPreset::postBuild() { mPresetCombo = getChild<LLComboBox>("preset_combo"); getChild<LLButton>("delete")->setCommitCallback(boost::bind(&LLFloaterDeleteEnvPreset::onBtnDelete, this)); getChild<LLButton>("cancel")->setCommitCallback(boost::bind(&LLFloaterDeleteEnvPreset::onBtnCancel, this)); // Listen to presets addition/removal. LLDayCycleManager::instance().setModifyCallback(boost::bind(&LLFloaterDeleteEnvPreset::populateDayCyclesList, this)); LLWLParamManager::instance().setPresetListChangeCallback(boost::bind(&LLFloaterDeleteEnvPreset::populateSkyPresetsList, this)); return TRUE; } // virtual void LLFloaterDeleteEnvPreset::onOpen(const LLSD& key) { std::string param = key.asString(); std::string floater_title = getString(std::string("title_") + param); std::string combo_label = getString(std::string("label_" + param)); // Update floater title. setTitle(floater_title); // Update the combobox label. getChild<LLUICtrl>("label")->setValue(combo_label); // Populate the combobox. if (param == "water") { populateWaterPresetsList(); getChild<LLButton>("delete")->setEnabled(FALSE); // not implemented yet } else if (param == "sky") { populateSkyPresetsList(); } else if (param == "day_cycle") { populateDayCyclesList(); } else { llwarns << "Unrecognized key" << llendl; } } void LLFloaterDeleteEnvPreset::onBtnDelete() { std::string param = mKey.asString(); std::string preset_name = mPresetCombo->getValue().asString(); boost::function<void()> confirm_cb; if (param == "water") { llwarns << "Deleting water presets not implemented" << llendl; return; } else if (param == "sky") { // Don't allow deleting presets referenced by local day cycles. if (LLDayCycleManager::instance().isSkyPresetReferenced(preset_name)) { LLNotificationsUtil::add("GenericAlert", LLSD().with("MESSAGE", getString("msg_sky_is_referenced"))); return; } LLWLParamManager& wl_mgr = LLWLParamManager::instance(); // Don't allow deleting system presets. if (wl_mgr.isSystemPreset(preset_name)) { LLNotificationsUtil::add("WLNoEditDefault"); return; } confirm_cb = boost::bind(&LLFloaterDeleteEnvPreset::onDeleteSkyPresetConfirmation, this); } else if (param == "day_cycle") { LLDayCycleManager& day_mgr = LLDayCycleManager::instance(); // Don't allow deleting system presets. if (day_mgr.isSystemPreset(preset_name)) { LLNotificationsUtil::add("WLNoEditDefault"); return; } confirm_cb = boost::bind(&LLFloaterDeleteEnvPreset::onDeleteDayCycleConfirmation, this); } else { llwarns << "Unrecognized key" << llendl; } LLSD args; args["MESSAGE"] = getString("msg_confirm_deletion"); LLNotificationsUtil::add("GenericAlertYesCancel", args, LLSD(), boost::bind(&confirmation_callback, _1, _2, confirm_cb)); } void LLFloaterDeleteEnvPreset::onBtnCancel() { closeFloater(); } void LLFloaterDeleteEnvPreset::populateWaterPresetsList() { if (mKey.asString() != "water") return; mPresetCombo->removeall(); // *TODO: Reload the list when user preferences change. LLWaterParamManager& water_mgr = LLWaterParamManager::instance(); LL_DEBUGS("Windlight") << "Current water preset: " << water_mgr.mCurParams.mName << LL_ENDL; const std::map<std::string, LLWaterParamSet> &water_params_map = water_mgr.mParamList; for (std::map<std::string, LLWaterParamSet>::const_iterator it = water_params_map.begin(); it != water_params_map.end(); it++) { std::string name = it->first; bool enabled = (name != water_mgr.mCurParams.mName); // don't allow deleting current preset mPresetCombo->add(name, ADD_BOTTOM, enabled); } postPopulate(); } void LLFloaterDeleteEnvPreset::populateSkyPresetsList() { if (mKey.asString() != "sky") return; mPresetCombo->removeall(); std::string cur_preset; LLEnvManagerNew& env_mgr = LLEnvManagerNew::instance(); if (!env_mgr.getUseRegionSettings() && env_mgr.getUseFixedSky()) { cur_preset = env_mgr.getSkyPresetName(); } // *TODO: Reload the list when user preferences change. LLWLParamManager& sky_mgr = LLWLParamManager::instance(); const std::map<LLWLParamKey, LLWLParamSet> &sky_params_map = sky_mgr.mParamList; for (std::map<LLWLParamKey, LLWLParamSet>::const_iterator it = sky_params_map.begin(); it != sky_params_map.end(); it++) { const LLWLParamKey& key = it->first; // list only local user presets if (key.scope == LLEnvKey::SCOPE_REGION || sky_mgr.isSystemPreset(key.name)) { continue; } bool enabled = (key.name != cur_preset); mPresetCombo->add(key.name, ADD_BOTTOM, enabled); } postPopulate(); } void LLFloaterDeleteEnvPreset::populateDayCyclesList() { if (mKey.asString() != "day_cycle") return; mPresetCombo->removeall(); std::string cur_day; LLEnvManagerNew& env_mgr = LLEnvManagerNew::instance(); if (!env_mgr.getUseRegionSettings() && env_mgr.getUseDayCycle()) { cur_day = env_mgr.getDayCycleName(); } const LLDayCycleManager::dc_map_t& map = LLDayCycleManager::instance().getPresets(); for (LLDayCycleManager::dc_map_t::const_iterator it = map.begin(); it != map.end(); ++it) { mPresetCombo->add(it->first, ADD_BOTTOM, it->first != cur_day); } postPopulate(); } void LLFloaterDeleteEnvPreset::postPopulate() { // Handle empty list. S32 n_items = mPresetCombo->getItemCount(); if (n_items == 0) { mPresetCombo->setLabel(getString("combo_label")); } getChild<LLButton>("delete")->setEnabled(n_items > 0); } void LLFloaterDeleteEnvPreset::onDeleteDayCycleConfirmation() { LLDayCycleManager::instance().deletePreset(mPresetCombo->getValue().asString()); } void LLFloaterDeleteEnvPreset::onDeleteSkyPresetConfirmation() { LLWLParamKey key(mPresetCombo->getValue().asString(), LLEnvKey::SCOPE_LOCAL); LLWLParamManager::instance().removeParamSet(key, true); } <|endoftext|>
<commit_before>#include "Board.h" Board::Board(){ init(); } void Board::init(){ RawBoard.resize(BOARD_SIZE + 2, vC(BOARD_SIZE + 2)); MovableDir.resize(MAX_TURNS + 1, vvu(BOARD_SIZE + 2, vu(BOARD_SIZE + 2))); Liberty.resize(BOARD_SIZE + 2, vi(BOARD_SIZE + 2)); rep1(x, BOARD_SIZE) rep1(y, BOARD_SIZE){ RawBoard[x][y] = EMPTY; } rep(y, BOARD_SIZE + 2){ RawBoard[0][y] = WALL; RawBoard[BOARD_SIZE + 1][y] = WALL; } rep(x, BOARD_SIZE + 2){ RawBoard[x][0] = WALL; RawBoard[x][BOARD_SIZE + 1] = WALL; } // 初期配置 constexpr int MID = BOARD_SIZE / 2; RawBoard[MID ][MID ] = WHITE; RawBoard[MID + 1][MID + 1] = WHITE; RawBoard[MID ][MID + 1] = BLACK; RawBoard[MID + 1][MID ] = BLACK; Discs[BLACK] = 2; Discs[WHITE] = 2; Discs[EMPTY] = BOARD_SIZE * BOARD_SIZE - 4; Turns = 0; CurrentColor = BLACK; UpdateLog.clear(); initMovable(); } bool Board::move(const Point& point){ if(point.x < 1 || BOARD_SIZE < point.x) return false; if(point.y < 1 || BOARD_SIZE < point.y) return false; if(MovableDir[Turns][point.x][point.y] == Direction::NONE) return false; flipDiscs(point); Turns++; CurrentColor = (Color) -CurrentColor; initMovable(); return true; } bool Board::pass(){ if(MovablePos[Turns].size() != 0) return false; if(isGameOver()) return false; CurrentColor = (Color) -CurrentColor; // 空のupdateを挿入しておく UpdateLog.emplace_back(vD()); // パスで手数は増えないが、色が反転したので // MovableDirとMovablePosを調べ直す initMovable(); return true; } bool Board::undo(){ if(Turns == 0) return false; CurrentColor = (Color) -CurrentColor; const vD& update = UpdateLog.back(); // 前回がパスかどうかで場合分け if(update.empty()){ MovablePos[Turns].clear(); rep1(x, BOARD_SIZE){ rep1(y, BOARD_SIZE){ MovableDir[Turns][x][y] = Direction::NONE; } } } else{ Turns--; // 石を元に戻す int S = update.size(); rep(i, S){ RawBoard[update[i].x][update[i].y] = i == 0 ? EMPTY : (Color) -CurrentColor; } // 開放度を元に戻す rep(k, 8) Liberty[update[0].x + dx[k]][update[0].y + dy[k]]++; // 石数の更新 unsigned discdiff = S; Discs[CurrentColor] -= discdiff; Discs[(Color) -CurrentColor] += discdiff - 1; Discs[Color::EMPTY]--; } UpdateLog.pop_back(); return true; } bool Board::isGameOver() const { if(Turns == MAX_TURNS) return true; if(MovablePos[Turns].size() != 0) return false; // 現在の手番と逆の色が打てるかどうか調べる Disc disc; disc.color = (Color) -CurrentColor; rep1(x, BOARD_SIZE){ disc.x = x; rep1(y, BOARD_SIZE){ disc.y = y; if(checkMobility(disc) != Direction::NONE) return false; } } return true; } unsigned Board::countDisc(Color color) const { return Discs[color]; } vP Board::getHistory() const { vP history; for(const auto& update : UpdateLog){ if(!update.empty()) history.emplace_back(update[0]); } return history; } Color Board::getColor(const Point& p) const { return RawBoard[p.x][p.y]; } const vP& Board::getMovablePos() const { return MovablePos[Turns]; } vD Board::getUpdate() const { if(UpdateLog.empty()) return vD(); else return UpdateLog.back(); } Color Board::getCurrentColor() const { return CurrentColor; } unsigned Board::getTurns() const { return Turns; } int Board::getLiberty(const Point& p) const { return Liberty[p.x][p.y]; } array<int, 8> Board::dx = {0, -1, -1, -1, 0, 1, 1, 1}; array<int, 8> Board::dy = {-1, -1, 0, 1, 1, 1, 0, -1}; void Board::flipDiscs(const Point& point){ // 行った操作を表す石 Disc operation(point.x, point.y, CurrentColor); // 打った石の周囲8マスの開放度を1ずつ減らす rep(k, 8) Liberty[point.x + dx[k]][point.y + dy[k]]--; unsigned dir = MovableDir[Turns][point.x][point.y]; vD update; RawBoard[point.x][point.y] = CurrentColor; update.emplace_back(operation); rep(k, 8){ if(dir & (1 << k)){ int x = point.x; int y = point.y; while(RawBoard[x + dx[k]][y + dy[k]] != CurrentColor){ x += dx[k]; y += dy[k]; RawBoard[x][y] = CurrentColor; operation.x = x; operation.y = y; update.emplace_back(operation); } } } // 石の数を更新 int discdiff = update.size(); Discs[CurrentColor] += discdiff; Discs[(Color) -CurrentColor] -= discdiff - 1; Discs[Color::EMPTY]--; UpdateLog.emplace_back(update); } unsigned Board::checkMobility(const Disc& disc) const { if(RawBoard[disc.x][disc.y] != Color::EMPTY){ return Direction::NONE; } unsigned dir = Direction::NONE; rep(k, 8){ if(RawBoard[disc.x + dx[k]][disc.y + dy[k]] == -disc.color){ int x = disc.x + 2 * dx[k]; int y = disc.y + 2 * dy[k]; while(RawBoard[x][y] == -disc.color){ x += dx[k]; y += dy[k]; } if(RawBoard[x][y] == disc.color) dir |= (1 << k); } } return dir; } void Board::initMovable(){ Disc disc(0, 0, CurrentColor); MovablePos[Turns].clear(); rep1(x, BOARD_SIZE){ disc.x = x; rep1(y, BOARD_SIZE){ disc.y = y; unsigned dir = checkMobility(disc); if(dir != Direction::NONE){ MovablePos[Turns].emplace_back(disc); } MovableDir[Turns][x][y] = dir; } } } <commit_msg>explicitly indicate Color::<commit_after>#include "Board.h" Board::Board(){ init(); } void Board::init(){ RawBoard.resize(BOARD_SIZE + 2, vC(BOARD_SIZE + 2)); MovableDir.resize(MAX_TURNS + 1, vvu(BOARD_SIZE + 2, vu(BOARD_SIZE + 2))); Liberty.resize(BOARD_SIZE + 2, vi(BOARD_SIZE + 2)); rep1(x, BOARD_SIZE) rep1(y, BOARD_SIZE){ RawBoard[x][y] = Color::EMPTY; } rep(y, BOARD_SIZE + 2){ RawBoard[0][y] = WALL; RawBoard[BOARD_SIZE + 1][y] = WALL; } rep(x, BOARD_SIZE + 2){ RawBoard[x][0] = WALL; RawBoard[x][BOARD_SIZE + 1] = WALL; } // 初期配置 constexpr int MID = BOARD_SIZE / 2; RawBoard[MID ][MID ] = Color::WHITE; RawBoard[MID + 1][MID + 1] = Color::WHITE; RawBoard[MID ][MID + 1] = Color::BLACK; RawBoard[MID + 1][MID ] = Color::BLACK; Discs[Color::BLACK] = 2; Discs[Color::WHITE] = 2; Discs[Color::EMPTY] = BOARD_SIZE * BOARD_SIZE - 4; Turns = 0; CurrentColor = Color::BLACK; UpdateLog.clear(); initMovable(); } bool Board::move(const Point& point){ if(point.x < 1 || BOARD_SIZE < point.x) return false; if(point.y < 1 || BOARD_SIZE < point.y) return false; if(MovableDir[Turns][point.x][point.y] == Direction::NONE) return false; flipDiscs(point); Turns++; CurrentColor = (Color) -CurrentColor; initMovable(); return true; } bool Board::pass(){ if(MovablePos[Turns].size() != 0) return false; if(isGameOver()) return false; CurrentColor = (Color) -CurrentColor; // 空のupdateを挿入しておく UpdateLog.emplace_back(vD()); // パスで手数は増えないが、色が反転したので // MovableDirとMovablePosを調べ直す initMovable(); return true; } bool Board::undo(){ if(Turns == 0) return false; CurrentColor = (Color) -CurrentColor; const vD& update = UpdateLog.back(); // 前回がパスかどうかで場合分け if(update.empty()){ MovablePos[Turns].clear(); rep1(x, BOARD_SIZE){ rep1(y, BOARD_SIZE){ MovableDir[Turns][x][y] = Direction::NONE; } } } else{ Turns--; // 石を元に戻す int S = update.size(); rep(i, S){ RawBoard[update[i].x][update[i].y] = i == 0 ? EMPTY : (Color) -CurrentColor; } // 開放度を元に戻す rep(k, 8) Liberty[update[0].x + dx[k]][update[0].y + dy[k]]++; // 石数の更新 unsigned discdiff = S; Discs[CurrentColor] -= discdiff; Discs[(Color) -CurrentColor] += discdiff - 1; Discs[Color::EMPTY]++; } UpdateLog.pop_back(); return true; } bool Board::isGameOver() const { if(Turns == MAX_TURNS) return true; if(MovablePos[Turns].size() != 0) return false; // 現在の手番と逆の色が打てるかどうか調べる Disc disc; disc.color = (Color) -CurrentColor; rep1(x, BOARD_SIZE){ disc.x = x; rep1(y, BOARD_SIZE){ disc.y = y; if(checkMobility(disc) != Direction::NONE) return false; } } return true; } unsigned Board::countDisc(Color color) const { return Discs[color]; } vP Board::getHistory() const { vP history; for(const auto& update : UpdateLog){ if(!update.empty()) history.emplace_back(update[0]); } return history; } Color Board::getColor(const Point& p) const { return RawBoard[p.x][p.y]; } const vP& Board::getMovablePos() const { return MovablePos[Turns]; } vD Board::getUpdate() const { if(UpdateLog.empty()) return vD(); else return UpdateLog.back(); } Color Board::getCurrentColor() const { return CurrentColor; } unsigned Board::getTurns() const { return Turns; } int Board::getLiberty(const Point& p) const { return Liberty[p.x][p.y]; } array<int, 8> Board::dx = {0, -1, -1, -1, 0, 1, 1, 1}; array<int, 8> Board::dy = {-1, -1, 0, 1, 1, 1, 0, -1}; void Board::flipDiscs(const Point& point){ // 行った操作を表す石 Disc operation(point.x, point.y, CurrentColor); // 打った石の周囲8マスの開放度を1ずつ減らす rep(k, 8) Liberty[point.x + dx[k]][point.y + dy[k]]--; unsigned dir = MovableDir[Turns][point.x][point.y]; vD update; RawBoard[point.x][point.y] = CurrentColor; update.emplace_back(operation); rep(k, 8){ if(dir & (1 << k)){ int x = point.x; int y = point.y; while(RawBoard[x + dx[k]][y + dy[k]] != CurrentColor){ x += dx[k]; y += dy[k]; RawBoard[x][y] = CurrentColor; operation.x = x; operation.y = y; update.emplace_back(operation); } } } // 石の数を更新 int discdiff = update.size(); Discs[CurrentColor] += discdiff; Discs[(Color) -CurrentColor] -= discdiff - 1; Discs[Color::EMPTY]--; UpdateLog.emplace_back(update); } unsigned Board::checkMobility(const Disc& disc) const { if(RawBoard[disc.x][disc.y] != Color::EMPTY){ return Direction::NONE; } unsigned dir = Direction::NONE; rep(k, 8){ if(RawBoard[disc.x + dx[k]][disc.y + dy[k]] == -disc.color){ int x = disc.x + 2 * dx[k]; int y = disc.y + 2 * dy[k]; while(RawBoard[x][y] == -disc.color){ x += dx[k]; y += dy[k]; } if(RawBoard[x][y] == disc.color) dir |= (1 << k); } } return dir; } void Board::initMovable(){ Disc disc(0, 0, CurrentColor); MovablePos[Turns].clear(); rep1(x, BOARD_SIZE){ disc.x = x; rep1(y, BOARD_SIZE){ disc.y = y; unsigned dir = checkMobility(disc); if(dir != Direction::NONE){ MovablePos[Turns].emplace_back(disc); } MovableDir[Turns][x][y] = dir; } } } <|endoftext|>
<commit_before>/* This file is part of the clazy static checker. Copyright (C) 2015 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com Author: Sérgio Martins <sergio.martins@kdab.com> Copyright (C) 2015-2016 Sergio Martins <smartins@kde.org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "Utils.h" #include "StringUtils.h" #include "clazy_stl.h" #include "checkbase.h" #include "checkmanager.h" #include "AccessSpecifierManager.h" #include "clang/Frontend/FrontendPluginRegistry.h" #include "clang/AST/AST.h" #include "clang/AST/ASTConsumer.h" #include "clang/Frontend/CompilerInstance.h" #include "llvm/Support/raw_ostream.h" #include "clang/AST/RecursiveASTVisitor.h" #include "clang/Rewrite/Frontend/FixItRewriter.h" #include "clang/AST/ParentMap.h" #include <llvm/Config/llvm-config.h> #include <stdio.h> #include <sstream> #include <iostream> using namespace clang; using namespace std; namespace { class MyFixItOptions : public FixItOptions { public: MyFixItOptions(const MyFixItOptions &other) = delete; MyFixItOptions(bool inplace) { InPlace = inplace; FixWhatYouCan = true; FixOnlyWarnings = true; Silent = false; } std::string RewriteFilename(const std::string &filename, int &fd) override { fd = -1; return InPlace ? filename : filename + "_fixed.cpp"; } #if LLVM_VERSION_MAJOR == 3 && LLVM_VERSION_MINOR <= 6 // Clang >= 3.7 already has this member. // We define it for clang <= 3.6 so it builds. bool InPlace; #endif }; static void manuallyPopulateParentMap(ParentMap *map, Stmt *s) { if (!s) return; for (Stmt *child : s->children()) { llvm::errs() << "Patching " << child->getStmtClassName() << "\n"; map->setParent(child, s); manuallyPopulateParentMap(map, child); } } class LazyASTConsumer : public ASTConsumer, public RecursiveASTVisitor<LazyASTConsumer> { LazyASTConsumer(const LazyASTConsumer &) = delete; public: LazyASTConsumer(CompilerInstance &ci, CheckManager *checkManager, const RegisteredCheck::List &requestedChecks, bool inplaceFixits) : m_ci(ci) , m_rewriter(nullptr) , m_parentMap(nullptr) , m_checkManager(checkManager) { m_createdChecks = checkManager->createChecks(requestedChecks, ci); if (checkManager->fixitsEnabled()) m_rewriter = new FixItRewriter(ci.getDiagnostics(), m_ci.getSourceManager(), m_ci.getLangOpts(), new MyFixItOptions(inplaceFixits)); } ~LazyASTConsumer() { if (m_rewriter) { m_rewriter->WriteFixedFiles(); delete m_rewriter; } delete m_parentMap; } void setParentMap(ParentMap *map) { assert(map && !m_parentMap); m_parentMap = map; for (auto &check : m_createdChecks) check->setParentMap(map); } bool VisitDecl(Decl *decl) { if (AccessSpecifierManager *a = m_checkManager->accessSpecifierManager()) a->VisitDeclaration(decl); for (const auto &check : m_createdChecks) check->VisitDeclaration(decl); return true; } bool VisitStmt(Stmt *stm) { if (!m_parentMap) { if (m_ci.getDiagnostics().hasUnrecoverableErrorOccurred()) return false; // ParentMap sometimes crashes when there were errors. Doesn't like a botched AST. setParentMap(new ParentMap(stm)); } // Workaround llvm bug: Crashes creating a parent map when encountering Catch Statements. if (lastStm && isa<CXXCatchStmt>(lastStm) && !m_parentMap->hasParent(stm)) { m_parentMap->setParent(stm, lastStm); manuallyPopulateParentMap(m_parentMap, stm); } lastStm = stm; // clang::ParentMap takes a root statement, but there's no root statement in the AST, the root is a declaration // So add to parent map each time we go into a different hierarchy if (!m_parentMap->hasParent(stm)) m_parentMap->addStmt(stm); for (const auto &check : m_createdChecks) { check->VisitStatement(stm); } return true; } void HandleTranslationUnit(ASTContext &ctx) override { TraverseDecl(ctx.getTranslationUnitDecl()); } Stmt *lastStm = nullptr; CompilerInstance &m_ci; FixItRewriter *m_rewriter; ParentMap *m_parentMap; CheckBase::List m_createdChecks; CheckManager *const m_checkManager; }; //------------------------------------------------------------------------------ static bool parseArgument(const string &arg, vector<string> &args) { auto it = clazy_std::find(args, arg); if (it != args.end()) { args.erase(it, it + 1); return true; } return false; } static CheckLevel parseLevel(vector<std::string> &args) { static const vector<string> levels = { "level0", "level1", "level2", "level3", "level4" }; const int numLevels = levels.size(); for (int i = 0; i < numLevels; ++i) { if (parseArgument(levels.at(i), args)) { return static_cast<CheckLevel>(i); } } return CheckLevelUndefined; } static bool checkLessThan(const RegisteredCheck &c1, const RegisteredCheck &c2) { return c1.name < c2.name; } static bool checkLessThanByLevel(const RegisteredCheck &c1, const RegisteredCheck &c2) { if (c1.level == c2.level) return checkLessThan(c1, c2); return c1.level < c2.level; } class LazyASTAction : public PluginASTAction { public: LazyASTAction() : PluginASTAction() , m_checkManager(CheckManager::instance()) { } protected: std::unique_ptr<clang::ASTConsumer> CreateASTConsumer(CompilerInstance &ci, llvm::StringRef) override { return llvm::make_unique<LazyASTConsumer>(ci, m_checkManager, m_checks, m_inplaceFixits); } bool ParseArgs(const CompilerInstance &ci, const std::vector<std::string> &args_) override { std::vector<std::string> args = args_; if (parseArgument("help", args)) { PrintHelp(llvm::errs()); return true; } if (parseArgument("no-inplace-fixits", args)) { // Unit-tests don't use inplace fixits m_inplaceFixits = false; } // This argument is for debugging purposes const bool printRequestedChecks = parseArgument("print-requested-checks", args); const CheckLevel requestedLevel = parseLevel(/*by-ref*/args); if (requestedLevel != CheckLevelUndefined) { m_checkManager->setRequestedLevel(requestedLevel); } if (parseArgument("enable-all-fixits", args)) { // This is useful for unit-tests, where we also want to run fixits. Don't use it otherwise. m_checkManager->enableAllFixIts(); } if (args.size() > 1) { // Too many arguments. llvm::errs() << "Too many arguments: "; for (const std::string &a : args) llvm::errs() << a << ' '; llvm::errs() << "\n"; PrintHelp(llvm::errs()); return false; } else if (args.size() == 1) { vector<string> userDisabledChecks; m_checks = m_checkManager->checksForCommaSeparatedString(args[0], /*by-ref=*/userDisabledChecks); if (m_checks.empty()) { llvm::errs() << "Could not find checks in comma separated string " + args[0] + "\n"; PrintHelp(llvm::errs()); return false; } } vector<string> userDisabledChecks; // Append checks specified from env variable RegisteredCheck::List checksFromEnv = m_checkManager->requestedChecksThroughEnv(/*by-ref*/userDisabledChecks); copy(checksFromEnv.cbegin(), checksFromEnv.cend(), back_inserter(m_checks)); if (m_checks.empty() && requestedLevel == CheckLevelUndefined) { // No check or level specified, lets use the default level m_checkManager->setRequestedLevel(DefaultCheckLevel); } // Add checks from requested level auto checksFromRequestedLevel = m_checkManager->checksFromRequestedLevel(); clazy_std::append(checksFromRequestedLevel, m_checks); clazy_std::sort_and_remove_dups(m_checks, checkLessThan); CheckManager::removeChecksFromList(m_checks, userDisabledChecks); if (printRequestedChecks) { llvm::errs() << "Requested checks: "; const unsigned int numChecks = m_checks.size(); for (unsigned int i = 0; i < numChecks; ++i) { llvm::errs() << m_checks.at(i).name; const bool isLast = i == numChecks - 1; if (!isLast) { llvm::errs() << ", "; } } llvm::errs() << "\n"; } return true; } void PrintHelp(llvm::raw_ostream &ros) { RegisteredCheck::List checks = m_checkManager->availableChecks(MaxCheckLevel); clazy_std::sort(checks, checkLessThanByLevel); ros << "Available checks and FixIts:\n\n"; int lastPrintedLevel = -1; const auto numChecks = checks.size(); for (unsigned int i = 0; i < numChecks; ++i) { const RegisteredCheck &check = checks[i]; if (lastPrintedLevel < check.level) { lastPrintedLevel = check.level; if (check.level > 0) ros << "\n"; ros << "Checks from level" << to_string(check.level) << ":\n"; } auto padded = check.name; padded.insert(padded.end(), 39 - padded.size(), ' '); ros << " " << check.name; auto fixits = m_checkManager->availableFixIts(check.name); if (!fixits.empty()) { ros << " ("; bool isFirst = true; for (const auto& fixit : fixits) { if (isFirst) { isFirst = false; } else { ros << ','; } ros << fixit.name; } ros << ')'; } ros << "\n"; } ros << "\nIf nothing is specified, all checks from level0 and level1 will be run.\n\n"; ros << "To specify which checks to enable set the CLAZY_CHECKS env variable, for example:\n"; ros << " export CLAZY_CHECKS=\"level0\"\n"; ros << " export CLAZY_CHECKS=\"level0,reserve-candidates,qstring-allocations\"\n"; ros << " export CLAZY_CHECKS=\"reserve-candidates\"\n\n"; ros << "or pass as compiler arguments, for example:\n"; ros << " -Xclang -plugin-arg-clang-lazy -Xclang reserve-candidates,qstring-allocations\n"; ros << "\n"; ros << "To enable FixIts for a check, also set the env variable CLAZY_FIXIT, for example:\n"; ros << " export CLAZY_FIXIT=\"fix-qlatin1string-allocations\"\n\n"; ros << "FixIts are experimental and rewrite your code therefore only one FixIt is allowed per build.\nSpecifying a list of different FixIts is not supported.\nBackup your code before running them.\n"; } private: RegisteredCheck::List m_checks; bool m_inplaceFixits = true; CheckManager *const m_checkManager; }; } static FrontendPluginRegistry::Add<LazyASTAction> X("clang-lazy", "clang lazy plugin"); #ifdef CLAZY_ON_WINDOWS_HACK LLVM_EXPORT_REGISTRY(FrontendPluginRegistry) #endif <commit_msg>One more place needing a clang-3.6 ifdef<commit_after>/* This file is part of the clazy static checker. Copyright (C) 2015 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com Author: Sérgio Martins <sergio.martins@kdab.com> Copyright (C) 2015-2016 Sergio Martins <smartins@kde.org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "Utils.h" #include "StringUtils.h" #include "clazy_stl.h" #include "checkbase.h" #include "checkmanager.h" #include "AccessSpecifierManager.h" #include "clang/Frontend/FrontendPluginRegistry.h" #include "clang/AST/AST.h" #include "clang/AST/ASTConsumer.h" #include "clang/Frontend/CompilerInstance.h" #include "llvm/Support/raw_ostream.h" #include "clang/AST/RecursiveASTVisitor.h" #include "clang/Rewrite/Frontend/FixItRewriter.h" #include "clang/AST/ParentMap.h" #include <llvm/Config/llvm-config.h> #include <stdio.h> #include <sstream> #include <iostream> using namespace clang; using namespace std; namespace { class MyFixItOptions : public FixItOptions { public: MyFixItOptions(const MyFixItOptions &other) = delete; MyFixItOptions(bool inplace) { InPlace = inplace; FixWhatYouCan = true; FixOnlyWarnings = true; Silent = false; } std::string RewriteFilename(const std::string &filename, int &fd) override { fd = -1; return InPlace ? filename : filename + "_fixed.cpp"; } #if LLVM_VERSION_MAJOR == 3 && LLVM_VERSION_MINOR <= 6 // Clang >= 3.7 already has this member. // We define it for clang <= 3.6 so it builds. bool InPlace; #endif }; static void manuallyPopulateParentMap(ParentMap *map, Stmt *s) { if (!s) return; for (Stmt *child : s->children()) { llvm::errs() << "Patching " << child->getStmtClassName() << "\n"; map->setParent(child, s); manuallyPopulateParentMap(map, child); } } class LazyASTConsumer : public ASTConsumer, public RecursiveASTVisitor<LazyASTConsumer> { LazyASTConsumer(const LazyASTConsumer &) = delete; public: LazyASTConsumer(CompilerInstance &ci, CheckManager *checkManager, const RegisteredCheck::List &requestedChecks, bool inplaceFixits) : m_ci(ci) , m_rewriter(nullptr) , m_parentMap(nullptr) , m_checkManager(checkManager) { m_createdChecks = checkManager->createChecks(requestedChecks, ci); if (checkManager->fixitsEnabled()) m_rewriter = new FixItRewriter(ci.getDiagnostics(), m_ci.getSourceManager(), m_ci.getLangOpts(), new MyFixItOptions(inplaceFixits)); } ~LazyASTConsumer() { if (m_rewriter) { m_rewriter->WriteFixedFiles(); delete m_rewriter; } delete m_parentMap; } void setParentMap(ParentMap *map) { assert(map && !m_parentMap); m_parentMap = map; for (auto &check : m_createdChecks) check->setParentMap(map); } bool VisitDecl(Decl *decl) { #if !defined(IS_OLD_CLANG) if (AccessSpecifierManager *a = m_checkManager->accessSpecifierManager()) a->VisitDeclaration(decl); #endif for (const auto &check : m_createdChecks) check->VisitDeclaration(decl); return true; } bool VisitStmt(Stmt *stm) { if (!m_parentMap) { if (m_ci.getDiagnostics().hasUnrecoverableErrorOccurred()) return false; // ParentMap sometimes crashes when there were errors. Doesn't like a botched AST. setParentMap(new ParentMap(stm)); } // Workaround llvm bug: Crashes creating a parent map when encountering Catch Statements. if (lastStm && isa<CXXCatchStmt>(lastStm) && !m_parentMap->hasParent(stm)) { m_parentMap->setParent(stm, lastStm); manuallyPopulateParentMap(m_parentMap, stm); } lastStm = stm; // clang::ParentMap takes a root statement, but there's no root statement in the AST, the root is a declaration // So add to parent map each time we go into a different hierarchy if (!m_parentMap->hasParent(stm)) m_parentMap->addStmt(stm); for (const auto &check : m_createdChecks) { check->VisitStatement(stm); } return true; } void HandleTranslationUnit(ASTContext &ctx) override { TraverseDecl(ctx.getTranslationUnitDecl()); } Stmt *lastStm = nullptr; CompilerInstance &m_ci; FixItRewriter *m_rewriter; ParentMap *m_parentMap; CheckBase::List m_createdChecks; CheckManager *const m_checkManager; }; //------------------------------------------------------------------------------ static bool parseArgument(const string &arg, vector<string> &args) { auto it = clazy_std::find(args, arg); if (it != args.end()) { args.erase(it, it + 1); return true; } return false; } static CheckLevel parseLevel(vector<std::string> &args) { static const vector<string> levels = { "level0", "level1", "level2", "level3", "level4" }; const int numLevels = levels.size(); for (int i = 0; i < numLevels; ++i) { if (parseArgument(levels.at(i), args)) { return static_cast<CheckLevel>(i); } } return CheckLevelUndefined; } static bool checkLessThan(const RegisteredCheck &c1, const RegisteredCheck &c2) { return c1.name < c2.name; } static bool checkLessThanByLevel(const RegisteredCheck &c1, const RegisteredCheck &c2) { if (c1.level == c2.level) return checkLessThan(c1, c2); return c1.level < c2.level; } class LazyASTAction : public PluginASTAction { public: LazyASTAction() : PluginASTAction() , m_checkManager(CheckManager::instance()) { } protected: std::unique_ptr<clang::ASTConsumer> CreateASTConsumer(CompilerInstance &ci, llvm::StringRef) override { return llvm::make_unique<LazyASTConsumer>(ci, m_checkManager, m_checks, m_inplaceFixits); } bool ParseArgs(const CompilerInstance &ci, const std::vector<std::string> &args_) override { std::vector<std::string> args = args_; if (parseArgument("help", args)) { PrintHelp(llvm::errs()); return true; } if (parseArgument("no-inplace-fixits", args)) { // Unit-tests don't use inplace fixits m_inplaceFixits = false; } // This argument is for debugging purposes const bool printRequestedChecks = parseArgument("print-requested-checks", args); const CheckLevel requestedLevel = parseLevel(/*by-ref*/args); if (requestedLevel != CheckLevelUndefined) { m_checkManager->setRequestedLevel(requestedLevel); } if (parseArgument("enable-all-fixits", args)) { // This is useful for unit-tests, where we also want to run fixits. Don't use it otherwise. m_checkManager->enableAllFixIts(); } if (args.size() > 1) { // Too many arguments. llvm::errs() << "Too many arguments: "; for (const std::string &a : args) llvm::errs() << a << ' '; llvm::errs() << "\n"; PrintHelp(llvm::errs()); return false; } else if (args.size() == 1) { vector<string> userDisabledChecks; m_checks = m_checkManager->checksForCommaSeparatedString(args[0], /*by-ref=*/userDisabledChecks); if (m_checks.empty()) { llvm::errs() << "Could not find checks in comma separated string " + args[0] + "\n"; PrintHelp(llvm::errs()); return false; } } vector<string> userDisabledChecks; // Append checks specified from env variable RegisteredCheck::List checksFromEnv = m_checkManager->requestedChecksThroughEnv(/*by-ref*/userDisabledChecks); copy(checksFromEnv.cbegin(), checksFromEnv.cend(), back_inserter(m_checks)); if (m_checks.empty() && requestedLevel == CheckLevelUndefined) { // No check or level specified, lets use the default level m_checkManager->setRequestedLevel(DefaultCheckLevel); } // Add checks from requested level auto checksFromRequestedLevel = m_checkManager->checksFromRequestedLevel(); clazy_std::append(checksFromRequestedLevel, m_checks); clazy_std::sort_and_remove_dups(m_checks, checkLessThan); CheckManager::removeChecksFromList(m_checks, userDisabledChecks); if (printRequestedChecks) { llvm::errs() << "Requested checks: "; const unsigned int numChecks = m_checks.size(); for (unsigned int i = 0; i < numChecks; ++i) { llvm::errs() << m_checks.at(i).name; const bool isLast = i == numChecks - 1; if (!isLast) { llvm::errs() << ", "; } } llvm::errs() << "\n"; } return true; } void PrintHelp(llvm::raw_ostream &ros) { RegisteredCheck::List checks = m_checkManager->availableChecks(MaxCheckLevel); clazy_std::sort(checks, checkLessThanByLevel); ros << "Available checks and FixIts:\n\n"; int lastPrintedLevel = -1; const auto numChecks = checks.size(); for (unsigned int i = 0; i < numChecks; ++i) { const RegisteredCheck &check = checks[i]; if (lastPrintedLevel < check.level) { lastPrintedLevel = check.level; if (check.level > 0) ros << "\n"; ros << "Checks from level" << to_string(check.level) << ":\n"; } auto padded = check.name; padded.insert(padded.end(), 39 - padded.size(), ' '); ros << " " << check.name; auto fixits = m_checkManager->availableFixIts(check.name); if (!fixits.empty()) { ros << " ("; bool isFirst = true; for (const auto& fixit : fixits) { if (isFirst) { isFirst = false; } else { ros << ','; } ros << fixit.name; } ros << ')'; } ros << "\n"; } ros << "\nIf nothing is specified, all checks from level0 and level1 will be run.\n\n"; ros << "To specify which checks to enable set the CLAZY_CHECKS env variable, for example:\n"; ros << " export CLAZY_CHECKS=\"level0\"\n"; ros << " export CLAZY_CHECKS=\"level0,reserve-candidates,qstring-allocations\"\n"; ros << " export CLAZY_CHECKS=\"reserve-candidates\"\n\n"; ros << "or pass as compiler arguments, for example:\n"; ros << " -Xclang -plugin-arg-clang-lazy -Xclang reserve-candidates,qstring-allocations\n"; ros << "\n"; ros << "To enable FixIts for a check, also set the env variable CLAZY_FIXIT, for example:\n"; ros << " export CLAZY_FIXIT=\"fix-qlatin1string-allocations\"\n\n"; ros << "FixIts are experimental and rewrite your code therefore only one FixIt is allowed per build.\nSpecifying a list of different FixIts is not supported.\nBackup your code before running them.\n"; } private: RegisteredCheck::List m_checks; bool m_inplaceFixits = true; CheckManager *const m_checkManager; }; } static FrontendPluginRegistry::Add<LazyASTAction> X("clang-lazy", "clang lazy plugin"); #ifdef CLAZY_ON_WINDOWS_HACK LLVM_EXPORT_REGISTRY(FrontendPluginRegistry) #endif <|endoftext|>
<commit_before>/* This file is part of the E_Rendering library. Copyright (C) 2009-2012 Benjamin Eikel <benjamin@eikel.org> Copyright (C) 2009-2012 Claudius Jähn <claudius@uni-paderborn.de> Copyright (C) 2009-2012 Ralf Petring <ralf@petring.net> This library is subject to the terms of the Mozilla Public License, v. 2.0. You should have received a copy of the MPL along with this library; see the file LICENSE. If not, you can obtain one at http://mozilla.org/MPL/2.0/. */ #include "E_FBO.h" #include "Texture/E_Texture.h" #include "E_RenderingContext.h" #include <EScript/Basics.h> #include <EScript/StdObjects.h> using namespace EScript; using namespace Rendering; namespace E_Rendering { //! (static) EScript::Type * E_FBO::getTypeObject() { // E_FBO ---|> Object static EScript::ERef<EScript::Type> typeObject = new EScript::Type(EScript::Object::getTypeObject()); return typeObject.get(); } //! initMembers void E_FBO::init(EScript::Namespace & lib) { EScript::Type * typeObject = getTypeObject(); declareConstant(&lib,getClassName(),typeObject); //! [ESMF] new Rendering.FBO() ES_CTOR(typeObject,0,0,new FBO) //! [ESMF] thisEObj FBO.attachColorTexture(RenderingContext,Texture,unit=0) ES_MFUN(typeObject,FBO,"attachColorTexture",2,3,(thisObj-> attachColorTexture(parameter[0].to<RenderingContext&>(rt), parameter[1].to<Rendering::Texture*>(rt),static_cast<uint8_t>(parameter[2].to<uint32_t>(rt))),thisEObj)) //! [ESMF] thisEObj FBO.attachDepthStencilTexture(RenderingContext, Texture) ES_MFUN(typeObject,FBO, "attachDepthStencilTexture", 2, 2,(thisObj-> attachDepthStencilTexture(parameter[0].to<RenderingContext&>(rt), parameter[1].to<Rendering::Texture*>(rt)), thisEObj)) //! [ESMF] thisEObj FBO.attachDepthTexture(RenderingContext,Texture) ES_MFUN(typeObject,FBO,"attachDepthTexture",2,2,(thisObj-> attachDepthTexture(parameter[0].to<RenderingContext&>(rt), parameter[1].to<Rendering::Texture*>(rt)),thisEObj)) //! [ESMF] thisEObj FBO.attachTexture(RenderingContext,attachmentPoint,Texture) ES_MFUN(typeObject,FBO,"attachTexture",3,3,(thisObj-> attachTexture(parameter[0].to<RenderingContext&>(rt), parameter[1].to<uint32_t>(rt), parameter[2].to<Rendering::Texture*>(rt)),thisEObj)) //! [ESMF] thisEObj FBO.detachColorTexture(RenderingContext,unit=0) ES_MFUN(typeObject,FBO,"detachColorTexture",1,2,(thisObj-> detachColorTexture(parameter[0].to<RenderingContext&>(rt), parameter[1].to<uint32_t>(rt,0)),thisEObj)) //! [ESMF] thisEObj FBO.detachDepthStencilTexture(RenderingContext) ES_MFUN(typeObject,FBO,"detachDepthStencilTexture",1,1,(thisObj-> detachDepthStencilTexture(parameter[0].to<RenderingContext&>(rt)),thisEObj)) //! [ESMF] thisEObj FBO.detachDepthTexture(RenderingContext) ES_MFUN(typeObject,FBO,"detachDepthTexture",1,1,(thisObj-> detachDepthTexture(parameter[0].to<RenderingContext&>(rt)),thisEObj)) //! [ESMF] thisEObj FBO.detachTexture(RenderingContext,attachmentPoint) ES_MFUN(typeObject,FBO,"detachTexture",2,2,(thisObj-> detachTexture(parameter[0].to<RenderingContext&>(rt), parameter[1].to<uint32_t>(rt)),thisEObj)) //! [ESMF] thisEObj FBO.getStatusMessage(RenderingContext) ES_MFUN(typeObject,FBO,"getStatusMessage",1,1,String::create(thisObj->getStatusMessage( parameter[0].to<RenderingContext&>(rt)))) //! [ESMF] Bool FBO.isComplete(RenderingContext) ES_MFUN(typeObject,FBO,"isComplete",1,1,Bool::create(thisObj->isComplete( parameter[0].to<RenderingContext&>(rt)))) //! [ESMF] thisEObj FBO.setDrawBuffers(Number) ES_MFUN(typeObject,FBO, "setDrawBuffers", 1, 1, (thisObj->setDrawBuffers(parameter[0].to<uint32_t>(rt)),thisEObj)) } } <commit_msg>FBO: All attach... methods support texture level and layer.<commit_after>/* This file is part of the E_Rendering library. Copyright (C) 2009-2012 Benjamin Eikel <benjamin@eikel.org> Copyright (C) 2009-2012 Claudius Jähn <claudius@uni-paderborn.de> Copyright (C) 2009-2012 Ralf Petring <ralf@petring.net> This library is subject to the terms of the Mozilla Public License, v. 2.0. You should have received a copy of the MPL along with this library; see the file LICENSE. If not, you can obtain one at http://mozilla.org/MPL/2.0/. */ #include "E_FBO.h" #include "Texture/E_Texture.h" #include "E_RenderingContext.h" #include <EScript/Basics.h> #include <EScript/StdObjects.h> using namespace EScript; using namespace Rendering; namespace E_Rendering { //! (static) EScript::Type * E_FBO::getTypeObject() { // E_FBO ---|> Object static EScript::ERef<EScript::Type> typeObject = new EScript::Type(EScript::Object::getTypeObject()); return typeObject.get(); } //! initMembers void E_FBO::init(EScript::Namespace & lib) { EScript::Type * typeObject = getTypeObject(); declareConstant(&lib,getClassName(),typeObject); //! [ESMF] new Rendering.FBO() ES_CTOR(typeObject,0,0,new FBO) //! [ESMF] thisEObj FBO.attachColorTexture(RenderingContext,Texture,colorBufferId=0,level=0,layer=0) ES_MFUN(typeObject,FBO,"attachColorTexture",2,5,(thisObj-> attachColorTexture(parameter[0].to<RenderingContext&>(rt), parameter[1].to<Rendering::Texture*>(rt), static_cast<uint8_t>(parameter[2].to<uint32_t>(rt)),parameter[3].toUInt(0),parameter[4].toUInt(0)),thisEObj)) //! [ESMF] thisEObj FBO.attachDepthStencilTexture(RenderingContext, Texture,level=0,layer=0) ES_MFUN(typeObject,FBO, "attachDepthStencilTexture", 2, 4,(thisObj-> attachDepthStencilTexture(parameter[0].to<RenderingContext&>(rt), parameter[1].to<Rendering::Texture*>(rt),parameter[2].toUInt(0),parameter[3].toUInt(0)), thisEObj)) //! [ESMF] thisEObj FBO.attachDepthTexture(RenderingContext,Texture,level=0,layer=0) ES_MFUN(typeObject,FBO,"attachDepthTexture",2,4,(thisObj-> attachDepthTexture(parameter[0].to<RenderingContext&>(rt), parameter[1].to<Rendering::Texture*>(rt),parameter[2].toUInt(0),parameter[3].toUInt(0)),thisEObj)) //! [ESMF] thisEObj FBO.attachTexture(RenderingContext,attachmentPoint,Texture, level=0,layer=0) ES_MFUN(typeObject,FBO,"attachTexture",3,5,(thisObj-> attachTexture(parameter[0].to<RenderingContext&>(rt), parameter[1].to<uint32_t>(rt), parameter[2].to<Rendering::Texture*>(rt),parameter[3].toUInt(0),parameter[4].toUInt(0)),thisEObj)) //! [ESMF] thisEObj FBO.detachColorTexture(RenderingContext,colorBufferId=0) ES_MFUN(typeObject,FBO,"detachColorTexture",1,2,(thisObj-> detachColorTexture(parameter[0].to<RenderingContext&>(rt), parameter[1].to<uint32_t>(rt,0)),thisEObj)) //! [ESMF] thisEObj FBO.detachDepthStencilTexture(RenderingContext) ES_MFUN(typeObject,FBO,"detachDepthStencilTexture",1,1,(thisObj-> detachDepthStencilTexture(parameter[0].to<RenderingContext&>(rt)),thisEObj)) //! [ESMF] thisEObj FBO.detachDepthTexture(RenderingContext) ES_MFUN(typeObject,FBO,"detachDepthTexture",1,1,(thisObj-> detachDepthTexture(parameter[0].to<RenderingContext&>(rt)),thisEObj)) //! [ESMF] thisEObj FBO.detachTexture(RenderingContext,attachmentPoint) ES_MFUN(typeObject,FBO,"detachTexture",2,2,(thisObj-> detachTexture(parameter[0].to<RenderingContext&>(rt), parameter[1].to<uint32_t>(rt)),thisEObj)) //! [ESMF] thisEObj FBO.getStatusMessage(RenderingContext) ES_MFUN(typeObject,FBO,"getStatusMessage",1,1,String::create(thisObj->getStatusMessage( parameter[0].to<RenderingContext&>(rt)))) //! [ESMF] Bool FBO.isComplete(RenderingContext) ES_MFUN(typeObject,FBO,"isComplete",1,1,Bool::create(thisObj->isComplete( parameter[0].to<RenderingContext&>(rt)))) //! [ESMF] thisEObj FBO.setDrawBuffers(Number) ES_MFUN(typeObject,FBO, "setDrawBuffers", 1, 1, (thisObj->setDrawBuffers(parameter[0].to<uint32_t>(rt)),thisEObj)) } } <|endoftext|>
<commit_before>#include "Main.hpp" using namespace std; unsigned int Level::levelCounter = 0; string Level::current = "NULL"; string Level::next = "NULL"; Level::Level(string name) { init(name, true); } void Level::init(string name, bool full) { if (name.empty() or (name == "NULL")) { current = "level9"; levelCounter = 0; menus.push_back(new Menu(MAIN)); } else {current = name;} stringstream ss; GLfloat x; GLfloat y = 0; fstream file(("levels/" + current + ".lvl").c_str(), fstream::in); string caption; if(!REPEAT_LEVEL) {levelCounter++;} if(!file.is_open()) {cerr << "Error with loading file: " << strerror(errno) << endl; QUIT = true; return;} textures.loadIMG("textures.png"); getline(file, caption); next = caption; getline(file, caption); ss << "Pertotman, Level " << levelCounter << ": " << caption; caption = ss.str(); SDL_WM_SetCaption(caption.c_str(), "Pertotman"); for(unsigned int counter = 1; file.eof() == false; counter++) { x = 0; string line; file >> line; for(unsigned int i = 0; i < line.size(); i++) { switch (line[i]) { case 'w': case 'W': walls.push_back(new Wall(x, y, textures)); break; case 'c': case 'C': if(full){coffees.push_back(new Coffee(x, y, textures));} spaces.push_back(new Space(x, y, textures)); break; case 'b': case 'B': if(full){enemies.push_back(new Enemy(x, y, textures));} spaces.push_back(new Space(x, y, textures)); break; case 'p': case 'P': if(full){pacmans.push_back(new Pacman(x, y, textures));} spaces.push_back(new Space(x, y, textures)); break; case 's': case 'S': spaces.push_back(new Space(x, y, textures)); break; default: cerr << "Error with loading level: Invalid character." << endl; QUIT = true; return; break; } x += 32; } y += 32; } for (unsigned int i = 0; i < spaces.size(); i++) { spaces[i]->neighbours(this); } if (full and(pacmans.size() != 1)) {cerr << "Error with loading level: Too many pacman instances." << endl; QUIT = true; return;} } void Level::save() const { size_t unit = sizeof(GLfloat); size_t sizeTemp; fstream file("savegame.sav", fstream::out | fstream::binary | fstream::trunc); if(!file.is_open()) {cerr << "Error with opening file: " << strerror(errno) << endl; QUIT = true; return;} file.write(reinterpret_cast<char*>(&unit), sizeof(size_t)); sizeTemp = sizeof(int); file.write(reinterpret_cast<char*>(&sizeTemp), sizeof(size_t)); file.write(reinterpret_cast<char*>(&levelCounter), sizeTemp); sizeTemp = current.size(); file.write(reinterpret_cast<char*>(&sizeTemp), sizeof(size_t)); file.write(current.c_str(), sizeTemp); sizeTemp = pacmans.size(); file.write(reinterpret_cast<char*>(&sizeTemp), sizeof(size_t)); for (unsigned int i = 0; i < pacmans.size(); i++) { file.write(reinterpret_cast<char*>(&pacmans[i]->x), unit); file.write(reinterpret_cast<char*>(&pacmans[i]->y), unit); } sizeTemp = coffees.size(); for (unsigned int i = 0; i < coffees.size(); i++) { if(!coffees[i]->armed){sizeTemp--;} } file.write(reinterpret_cast<char*>(&sizeTemp), sizeof(size_t)); for (unsigned int i = 0; i < coffees.size(); i++) { if(coffees[i]->armed) { file.write(reinterpret_cast<char*>(&coffees[i]->x), unit); file.write(reinterpret_cast<char*>(&coffees[i]->y), unit); } } sizeTemp = enemies.size(); file.write(reinterpret_cast<char*>(&sizeTemp), sizeof(size_t)); for (unsigned int i = 0; i < enemies.size(); i++) { file.write(reinterpret_cast<char*>(&enemies[i]->x), unit); file.write(reinterpret_cast<char*>(&enemies[i]->y), unit); } } void Level::load() { size_t unit = sizeof(GLfloat); size_t sizeTemp; char lvlName[50]; GLfloat xTemp, yTemp; fstream file("savegame.sav", fstream::in | fstream::binary); if(!file.is_open()) { levelCounter = 0; init("level1", true); return; } file.read(reinterpret_cast<char*>(&unit), sizeof(size_t)); file.read(reinterpret_cast<char*>(&sizeTemp), sizeof(size_t)); file.read(reinterpret_cast<char*>(&levelCounter), sizeTemp); levelCounter--; file.read(reinterpret_cast<char*>(&sizeTemp), sizeof(size_t)); file.read(lvlName, sizeTemp); lvlName[sizeTemp] = 0; init(lvlName, false); file.read(reinterpret_cast<char*>(&sizeTemp), sizeof(size_t)); for (unsigned int i = 0; i < sizeTemp; i++) { file.read(reinterpret_cast<char*>(&xTemp), unit); file.read(reinterpret_cast<char*>(&yTemp), unit); pacmans.push_back(new Pacman(xTemp, yTemp, textures)); } file.read(reinterpret_cast<char*>(&sizeTemp), sizeof(size_t)); for (unsigned int i = 0; i < sizeTemp; i++) { file.read(reinterpret_cast<char*>(&xTemp), unit); file.read(reinterpret_cast<char*>(&yTemp), unit); coffees.push_back(new Coffee(xTemp, yTemp, textures)); } file.read(reinterpret_cast<char*>(&sizeTemp), sizeof(size_t)); for (unsigned int i = 0; i < sizeTemp; i++) { file.read(reinterpret_cast<char*>(&xTemp), unit); file.read(reinterpret_cast<char*>(&yTemp), unit); enemies.push_back(new Enemy(xTemp, yTemp, textures)); } menus.push_back(new Menu(ESCAPE)); } void Level::handle(SDL_Event inputEvent) { if((inputEvent.type == SDL_KEYDOWN) and (inputEvent.key.keysym.sym == SDLK_ESCAPE)) { if (PAUSE == 0) { PAUSE = -1; } else { PAUSE = 0; } if(menus.empty()) {menus.push_back(new Menu(ESCAPE));} else {menus.pop_back();} } else { if(menus.size() > 0) { if(!menus[menus.size() - 1]->handle(inputEvent)) {menus.pop_back();} } for (unsigned int i = 0; i < pacmans.size(); i++) { pacmans[i]->handle(inputEvent); } } } void Level::update() { if(menus.empty()) { for (unsigned int i = 0; i < spaces.size(); i++) { spaces[i]->update(); } for (unsigned int i = 0; i < walls.size(); i++) { walls[i]->update(); } for (unsigned int i = 0; i < coffees.size(); i++) { coffees[i]->update(); } for (unsigned int i = 0; i < enemies.size(); i++) { enemies[i]->update(); } for (unsigned int i = 0; i < pacmans.size(); i++) { pacmans[i]->update(); } } } void Level::render() const { glClear(GL_COLOR_BUFFER_BIT); bool bgrender = true; if(menus.size() > 0) { if(menus[0]->type == MAIN) {bgrender = false;} } if (bgrender) { for (unsigned int i = 0; i < spaces.size(); i++) { spaces[i]->render(); } for (unsigned int i = 0; i < walls.size(); i++) { walls[i]->render(); } for (unsigned int i = 0; i < coffees.size(); i++) { coffees[i]->render(); } for (unsigned int i = 0; i < enemies.size(); i++) { enemies[i]->render(); } for (unsigned int i = 0; i < pacmans.size(); i++) { pacmans[i]->render(); } } if(menus.size() > 0) {menus[menus.size() - 1]->render();} } void Level::computeGraph(std::vector<Space*> endpoints, Space* start) { nodes.clear(); for(auto space: spaces) // Reset all nodes, everything { space->isDissolved = false; space->arcs.clear(); unsigned int neighbours{0}; if(space->up != nullptr) {++neighbours;} if(space->down != nullptr) {++neighbours;} if(space->left != nullptr) {++neighbours;} if(space->right != nullptr) {++neighbours;} if(neighbours > 2 or (std::find(endpoints.begin(), endpoints.end(), space) != endpoints.end())) { nodes.push_back(space); // Find nodes } } for(auto space: spaces) // "Dissolve" all spaces which aren't nodes { if(std::find(nodes.begin(), nodes.end(), space) != nodes.end()) { continue; } if(space->isDissolved) { continue; } vector<Space*> neighbours{vector<Space*>{}}; if(space->up != nullptr) {neighbours.push_back(space->up);} if(space->down != nullptr) {neighbours.push_back(space->down);} if(space->left != nullptr) {neighbours.push_back(space->left);} if(space->right != nullptr) {neighbours.push_back(space->right);} Arc* currentArc{new Arc{space}}; space->arcs.push_back(currentArc); space->isDissolved = true; if(neighbours.size() > 0) { neighbours[0]->continueArc(currentArc); } if(neighbours.size() > 1) { neighbours[1]->continueArc(currentArc); } } vector<Space*> done{vector<Space*>{}}; for(auto space: nodes) // Connect neighbouring nodes as well { vector<Space*> neighbours{vector<Space*>{}}; if(space->up != nullptr) {neighbours.push_back(space->up);} if(space->down != nullptr) {neighbours.push_back(space->down);} if(space->left != nullptr) {neighbours.push_back(space->left);} if(space->right != nullptr) {neighbours.push_back(space->right);} for(auto neighbour: neighbours) { if(std::find(done.begin(), done.end(), neighbour) != done.end()) { continue; } if(!neighbour->isDissolved) { Arc* currentArc{new Arc{space}}; currentArc->add(neighbour); space->arcs.push_back(currentArc); neighbour->arcs.push_back(currentArc); } } done.push_back(space); } // Pathfinder state clearing for(auto it: spaces) { it->dist = -1; // INF it->pred = nullptr; } permanent.clear(); permanent.push_back(start); start->dist = 0; start->added_to_permanent(); } void Level::pathfind(Space* target) { if(find(permanent.begin(), permanent.end(), target) != permanent.end()) { return; } while(true) { // Find the non-permanent node with the lowest node evaluation function Space* lowest{nullptr}; for(auto it: nodes) { if(find(permanent.begin(), permanent.end(), it) != permanent.end()) { continue; // SKIP permanently labelled } if(it->dist < 0) { continue; // Infinite distance } if(lowest == nullptr or (it->nodeEvaluation(target) < lowest->nodeEvaluation(target))) { lowest = it; } } permanent.push_back(lowest); lowest->added_to_permanent(); if(lowest == target) { break; } } } void Level::destroy() { for (unsigned int i = 0; i < menus.size(); i++) { menus.erase(menus.begin() + i); } for (unsigned int i = 0; i < spaces.size(); i++) { spaces.erase(spaces.begin() + i); } for (unsigned int i = 0; i < walls.size(); i++) { walls.erase(walls.begin() + i); } for (unsigned int i = 0; i < coffees.size(); i++) { coffees.erase(coffees.begin() + i); } for (unsigned int i = 0; i < enemies.size(); i++) { enemies.erase(enemies.begin() + i); } for (unsigned int i = 0; i < pacmans.size(); i++) { pacmans.erase(pacmans.begin() + i); } menus.clear(); spaces.clear(); walls.clear(); coffees.clear(); enemies.clear(); pacmans.clear(); Coffee::count = 0; } <commit_msg>Starting from level 1 again<commit_after>#include "Main.hpp" using namespace std; unsigned int Level::levelCounter = 0; string Level::current = "NULL"; string Level::next = "NULL"; Level::Level(string name) { init(name, true); } void Level::init(string name, bool full) { if (name.empty() or (name == "NULL")) { current = "level1"; levelCounter = 0; menus.push_back(new Menu(MAIN)); } else {current = name;} stringstream ss; GLfloat x; GLfloat y = 0; fstream file(("levels/" + current + ".lvl").c_str(), fstream::in); string caption; if(!REPEAT_LEVEL) {levelCounter++;} if(!file.is_open()) {cerr << "Error with loading file: " << strerror(errno) << endl; QUIT = true; return;} textures.loadIMG("textures.png"); getline(file, caption); next = caption; getline(file, caption); ss << "Pertotman, Level " << levelCounter << ": " << caption; caption = ss.str(); SDL_WM_SetCaption(caption.c_str(), "Pertotman"); for(unsigned int counter = 1; file.eof() == false; counter++) { x = 0; string line; file >> line; for(unsigned int i = 0; i < line.size(); i++) { switch (line[i]) { case 'w': case 'W': walls.push_back(new Wall(x, y, textures)); break; case 'c': case 'C': if(full){coffees.push_back(new Coffee(x, y, textures));} spaces.push_back(new Space(x, y, textures)); break; case 'b': case 'B': if(full){enemies.push_back(new Enemy(x, y, textures));} spaces.push_back(new Space(x, y, textures)); break; case 'p': case 'P': if(full){pacmans.push_back(new Pacman(x, y, textures));} spaces.push_back(new Space(x, y, textures)); break; case 's': case 'S': spaces.push_back(new Space(x, y, textures)); break; default: cerr << "Error with loading level: Invalid character." << endl; QUIT = true; return; break; } x += 32; } y += 32; } for (unsigned int i = 0; i < spaces.size(); i++) { spaces[i]->neighbours(this); } if (full and(pacmans.size() != 1)) {cerr << "Error with loading level: Too many pacman instances." << endl; QUIT = true; return;} } void Level::save() const { size_t unit = sizeof(GLfloat); size_t sizeTemp; fstream file("savegame.sav", fstream::out | fstream::binary | fstream::trunc); if(!file.is_open()) {cerr << "Error with opening file: " << strerror(errno) << endl; QUIT = true; return;} file.write(reinterpret_cast<char*>(&unit), sizeof(size_t)); sizeTemp = sizeof(int); file.write(reinterpret_cast<char*>(&sizeTemp), sizeof(size_t)); file.write(reinterpret_cast<char*>(&levelCounter), sizeTemp); sizeTemp = current.size(); file.write(reinterpret_cast<char*>(&sizeTemp), sizeof(size_t)); file.write(current.c_str(), sizeTemp); sizeTemp = pacmans.size(); file.write(reinterpret_cast<char*>(&sizeTemp), sizeof(size_t)); for (unsigned int i = 0; i < pacmans.size(); i++) { file.write(reinterpret_cast<char*>(&pacmans[i]->x), unit); file.write(reinterpret_cast<char*>(&pacmans[i]->y), unit); } sizeTemp = coffees.size(); for (unsigned int i = 0; i < coffees.size(); i++) { if(!coffees[i]->armed){sizeTemp--;} } file.write(reinterpret_cast<char*>(&sizeTemp), sizeof(size_t)); for (unsigned int i = 0; i < coffees.size(); i++) { if(coffees[i]->armed) { file.write(reinterpret_cast<char*>(&coffees[i]->x), unit); file.write(reinterpret_cast<char*>(&coffees[i]->y), unit); } } sizeTemp = enemies.size(); file.write(reinterpret_cast<char*>(&sizeTemp), sizeof(size_t)); for (unsigned int i = 0; i < enemies.size(); i++) { file.write(reinterpret_cast<char*>(&enemies[i]->x), unit); file.write(reinterpret_cast<char*>(&enemies[i]->y), unit); } } void Level::load() { size_t unit = sizeof(GLfloat); size_t sizeTemp; char lvlName[50]; GLfloat xTemp, yTemp; fstream file("savegame.sav", fstream::in | fstream::binary); if(!file.is_open()) { levelCounter = 0; init("level1", true); return; } file.read(reinterpret_cast<char*>(&unit), sizeof(size_t)); file.read(reinterpret_cast<char*>(&sizeTemp), sizeof(size_t)); file.read(reinterpret_cast<char*>(&levelCounter), sizeTemp); levelCounter--; file.read(reinterpret_cast<char*>(&sizeTemp), sizeof(size_t)); file.read(lvlName, sizeTemp); lvlName[sizeTemp] = 0; init(lvlName, false); file.read(reinterpret_cast<char*>(&sizeTemp), sizeof(size_t)); for (unsigned int i = 0; i < sizeTemp; i++) { file.read(reinterpret_cast<char*>(&xTemp), unit); file.read(reinterpret_cast<char*>(&yTemp), unit); pacmans.push_back(new Pacman(xTemp, yTemp, textures)); } file.read(reinterpret_cast<char*>(&sizeTemp), sizeof(size_t)); for (unsigned int i = 0; i < sizeTemp; i++) { file.read(reinterpret_cast<char*>(&xTemp), unit); file.read(reinterpret_cast<char*>(&yTemp), unit); coffees.push_back(new Coffee(xTemp, yTemp, textures)); } file.read(reinterpret_cast<char*>(&sizeTemp), sizeof(size_t)); for (unsigned int i = 0; i < sizeTemp; i++) { file.read(reinterpret_cast<char*>(&xTemp), unit); file.read(reinterpret_cast<char*>(&yTemp), unit); enemies.push_back(new Enemy(xTemp, yTemp, textures)); } menus.push_back(new Menu(ESCAPE)); } void Level::handle(SDL_Event inputEvent) { if((inputEvent.type == SDL_KEYDOWN) and (inputEvent.key.keysym.sym == SDLK_ESCAPE)) { if (PAUSE == 0) { PAUSE = -1; } else { PAUSE = 0; } if(menus.empty()) {menus.push_back(new Menu(ESCAPE));} else {menus.pop_back();} } else { if(menus.size() > 0) { if(!menus[menus.size() - 1]->handle(inputEvent)) {menus.pop_back();} } for (unsigned int i = 0; i < pacmans.size(); i++) { pacmans[i]->handle(inputEvent); } } } void Level::update() { if(menus.empty()) { for (unsigned int i = 0; i < spaces.size(); i++) { spaces[i]->update(); } for (unsigned int i = 0; i < walls.size(); i++) { walls[i]->update(); } for (unsigned int i = 0; i < coffees.size(); i++) { coffees[i]->update(); } for (unsigned int i = 0; i < enemies.size(); i++) { enemies[i]->update(); } for (unsigned int i = 0; i < pacmans.size(); i++) { pacmans[i]->update(); } } } void Level::render() const { glClear(GL_COLOR_BUFFER_BIT); bool bgrender = true; if(menus.size() > 0) { if(menus[0]->type == MAIN) {bgrender = false;} } if (bgrender) { for (unsigned int i = 0; i < spaces.size(); i++) { spaces[i]->render(); } for (unsigned int i = 0; i < walls.size(); i++) { walls[i]->render(); } for (unsigned int i = 0; i < coffees.size(); i++) { coffees[i]->render(); } for (unsigned int i = 0; i < enemies.size(); i++) { enemies[i]->render(); } for (unsigned int i = 0; i < pacmans.size(); i++) { pacmans[i]->render(); } } if(menus.size() > 0) {menus[menus.size() - 1]->render();} } void Level::computeGraph(std::vector<Space*> endpoints, Space* start) { nodes.clear(); for(auto space: spaces) // Reset all nodes, everything { space->isDissolved = false; space->arcs.clear(); unsigned int neighbours{0}; if(space->up != nullptr) {++neighbours;} if(space->down != nullptr) {++neighbours;} if(space->left != nullptr) {++neighbours;} if(space->right != nullptr) {++neighbours;} if(neighbours > 2 or (std::find(endpoints.begin(), endpoints.end(), space) != endpoints.end())) { nodes.push_back(space); // Find nodes } } for(auto space: spaces) // "Dissolve" all spaces which aren't nodes { if(std::find(nodes.begin(), nodes.end(), space) != nodes.end()) { continue; } if(space->isDissolved) { continue; } vector<Space*> neighbours{vector<Space*>{}}; if(space->up != nullptr) {neighbours.push_back(space->up);} if(space->down != nullptr) {neighbours.push_back(space->down);} if(space->left != nullptr) {neighbours.push_back(space->left);} if(space->right != nullptr) {neighbours.push_back(space->right);} Arc* currentArc{new Arc{space}}; space->arcs.push_back(currentArc); space->isDissolved = true; if(neighbours.size() > 0) { neighbours[0]->continueArc(currentArc); } if(neighbours.size() > 1) { neighbours[1]->continueArc(currentArc); } } vector<Space*> done{vector<Space*>{}}; for(auto space: nodes) // Connect neighbouring nodes as well { vector<Space*> neighbours{vector<Space*>{}}; if(space->up != nullptr) {neighbours.push_back(space->up);} if(space->down != nullptr) {neighbours.push_back(space->down);} if(space->left != nullptr) {neighbours.push_back(space->left);} if(space->right != nullptr) {neighbours.push_back(space->right);} for(auto neighbour: neighbours) { if(std::find(done.begin(), done.end(), neighbour) != done.end()) { continue; } if(!neighbour->isDissolved) { Arc* currentArc{new Arc{space}}; currentArc->add(neighbour); space->arcs.push_back(currentArc); neighbour->arcs.push_back(currentArc); } } done.push_back(space); } // Pathfinder state clearing for(auto it: spaces) { it->dist = -1; // INF it->pred = nullptr; } permanent.clear(); permanent.push_back(start); start->dist = 0; start->added_to_permanent(); } void Level::pathfind(Space* target) { if(find(permanent.begin(), permanent.end(), target) != permanent.end()) { return; } while(true) { // Find the non-permanent node with the lowest node evaluation function Space* lowest{nullptr}; for(auto it: nodes) { if(find(permanent.begin(), permanent.end(), it) != permanent.end()) { continue; // SKIP permanently labelled } if(it->dist < 0) { continue; // Infinite distance } if(lowest == nullptr or (it->nodeEvaluation(target) < lowest->nodeEvaluation(target))) { lowest = it; } } permanent.push_back(lowest); lowest->added_to_permanent(); if(lowest == target) { break; } } } void Level::destroy() { for (unsigned int i = 0; i < menus.size(); i++) { menus.erase(menus.begin() + i); } for (unsigned int i = 0; i < spaces.size(); i++) { spaces.erase(spaces.begin() + i); } for (unsigned int i = 0; i < walls.size(); i++) { walls.erase(walls.begin() + i); } for (unsigned int i = 0; i < coffees.size(); i++) { coffees.erase(coffees.begin() + i); } for (unsigned int i = 0; i < enemies.size(); i++) { enemies.erase(enemies.begin() + i); } for (unsigned int i = 0; i < pacmans.size(); i++) { pacmans.erase(pacmans.begin() + i); } menus.clear(); spaces.clear(); walls.clear(); coffees.clear(); enemies.clear(); pacmans.clear(); Coffee::count = 0; } <|endoftext|>
<commit_before>/* Copyright (c) 2006, NIF File Format Library and Tools All rights reserved. Please see niflib.h for licence. */ #include "NiSkinInstance.h" #include "NiNode.h" #include "NiSkinData.h" #include "NiSkinPartition.h" #include "NiNode.h" using namespace Niflib; //Definition of TYPE constant const Type NiSkinInstance::TYPE("NiSkinInstance", &NI_SKIN_INSTANCE_PARENT::TypeConst() ); NiSkinInstance::NiSkinInstance() NI_SKIN_INSTANCE_CONSTRUCT {} NiSkinInstance::NiSkinInstance( Ref<NiNode> skeleton_root, vector< Ref<NiNode> > bone_nodes ) NI_SKIN_INSTANCE_CONSTRUCT { //Ensure that all bones are below the skeleton root node on the scene graph for ( uint i = 0; i < bone_nodes.size(); ++i ) { bool is_decended = false; NiNodeRef node = bone_nodes[i]; while ( node != NULL ) { if ( node == skeleton_root ) { is_decended = true; break; } node = node->GetParent(); } if ( is_decended == false ) { throw runtime_error( "All bones must be lower than the skeleton root in the scene graph." ); } } //Add the bones to the internal list bones.resize( bone_nodes.size() ); for ( uint i = 0; i < bone_nodes.size(); ++i ) { bones[i] = bone_nodes[i]; } //Flag any bones that are part of this skin instance for ( uint i = 0; i < bones.size(); ++i ) { bones[i]->SetSkinFlag(true); } //Store skeleton root and inform it of this attachment skeletonRoot = skeleton_root; skeletonRoot->AddSkin( this ); } NiSkinInstance::~NiSkinInstance() { //Inform Skeleton Root of detatchment and clear it. skeletonRoot->RemoveSkin( this ); } void NiSkinInstance::Read( istream& in, list<uint> & link_stack, unsigned int version, unsigned int user_version ) { NI_SKIN_INSTANCE_READ } void NiSkinInstance::Write( ostream& out, map<NiObjectRef,uint> link_map, unsigned int version, unsigned int user_version ) const { NI_SKIN_INSTANCE_WRITE } string NiSkinInstance::asString( bool verbose ) const { NI_SKIN_INSTANCE_STRING } void NiSkinInstance::FixLinks( const vector<NiObjectRef> & objects, list<uint> & link_stack, unsigned int version, unsigned int user_version ) { NI_SKIN_INSTANCE_FIXLINKS //Inform newly fixed skeleton root of attachment if ( skeletonRoot != NULL ) { skeletonRoot->AddSkin( this ); } } list<NiObjectRef> NiSkinInstance::GetRefs() const { NI_SKIN_INSTANCE_GETREFS } const Type & NiSkinInstance::GetType() const { return TYPE; }; vector< Ref<NiNode> > NiSkinInstance::GetBones() const { vector<NiNodeRef> ref_bones( bones.size() ); for (uint i = 0; i < bones.size(); ++i ) { ref_bones[i] = bones[i]; } return ref_bones; } Ref<NiSkinData> NiSkinInstance::GetSkinData() const { return data; } void NiSkinInstance::SetSkinData( const Ref<NiSkinData> & n ) { data = n; } Ref<NiSkinPartition> NiSkinInstance::GetSkinPartition() const { return skinPartition; } void NiSkinInstance::SetSkinPartition( const Ref<NiSkinPartition> & n ) { skinPartition = n; } void NiSkinInstance::SkeletonLost() { skeletonRoot = NULL; //Clear bone list bones.clear(); //Destroy skin data data = NULL; skinPartition = NULL; } uint NiSkinInstance::GetBoneCount() const { return uint(bones.size()); } Ref<NiNode> NiSkinInstance::GetSkeletonRoot() const { return skeletonRoot; }<commit_msg>Added code to ensure that bones have their flag set properly, even if they are not so in the original NIF file.<commit_after>/* Copyright (c) 2006, NIF File Format Library and Tools All rights reserved. Please see niflib.h for licence. */ #include "NiSkinInstance.h" #include "NiNode.h" #include "NiSkinData.h" #include "NiSkinPartition.h" #include "NiNode.h" using namespace Niflib; //Definition of TYPE constant const Type NiSkinInstance::TYPE("NiSkinInstance", &NI_SKIN_INSTANCE_PARENT::TypeConst() ); NiSkinInstance::NiSkinInstance() NI_SKIN_INSTANCE_CONSTRUCT {} NiSkinInstance::NiSkinInstance( Ref<NiNode> skeleton_root, vector< Ref<NiNode> > bone_nodes ) NI_SKIN_INSTANCE_CONSTRUCT { //Ensure that all bones are below the skeleton root node on the scene graph for ( uint i = 0; i < bone_nodes.size(); ++i ) { bool is_decended = false; NiNodeRef node = bone_nodes[i]; while ( node != NULL ) { if ( node == skeleton_root ) { is_decended = true; break; } node = node->GetParent(); } if ( is_decended == false ) { throw runtime_error( "All bones must be lower than the skeleton root in the scene graph." ); } } //Add the bones to the internal list bones.resize( bone_nodes.size() ); for ( uint i = 0; i < bone_nodes.size(); ++i ) { bones[i] = bone_nodes[i]; } //Flag any bones that are part of this skin instance for ( uint i = 0; i < bones.size(); ++i ) { bones[i]->SetSkinFlag(true); } //Store skeleton root and inform it of this attachment skeletonRoot = skeleton_root; skeletonRoot->AddSkin( this ); } NiSkinInstance::~NiSkinInstance() { //Inform Skeleton Root of detatchment and clear it. skeletonRoot->RemoveSkin( this ); } void NiSkinInstance::Read( istream& in, list<uint> & link_stack, unsigned int version, unsigned int user_version ) { NI_SKIN_INSTANCE_READ } void NiSkinInstance::Write( ostream& out, map<NiObjectRef,uint> link_map, unsigned int version, unsigned int user_version ) const { NI_SKIN_INSTANCE_WRITE } string NiSkinInstance::asString( bool verbose ) const { NI_SKIN_INSTANCE_STRING } void NiSkinInstance::FixLinks( const vector<NiObjectRef> & objects, list<uint> & link_stack, unsigned int version, unsigned int user_version ) { NI_SKIN_INSTANCE_FIXLINKS //Inform newly fixed skeleton root of attachment if ( skeletonRoot != NULL ) { skeletonRoot->AddSkin( this ); } //Ensure that bones have the flag set properly for ( uint i = 0; i < bones.size(); ++i ) { bones[i]->SetSkinFlag(true); } } list<NiObjectRef> NiSkinInstance::GetRefs() const { NI_SKIN_INSTANCE_GETREFS } const Type & NiSkinInstance::GetType() const { return TYPE; }; vector< Ref<NiNode> > NiSkinInstance::GetBones() const { vector<NiNodeRef> ref_bones( bones.size() ); for (uint i = 0; i < bones.size(); ++i ) { ref_bones[i] = bones[i]; } return ref_bones; } Ref<NiSkinData> NiSkinInstance::GetSkinData() const { return data; } void NiSkinInstance::SetSkinData( const Ref<NiSkinData> & n ) { data = n; } Ref<NiSkinPartition> NiSkinInstance::GetSkinPartition() const { return skinPartition; } void NiSkinInstance::SetSkinPartition( const Ref<NiSkinPartition> & n ) { skinPartition = n; } void NiSkinInstance::SkeletonLost() { skeletonRoot = NULL; //Clear bone list bones.clear(); //Destroy skin data data = NULL; skinPartition = NULL; } uint NiSkinInstance::GetBoneCount() const { return uint(bones.size()); } Ref<NiNode> NiSkinInstance::GetSkeletonRoot() const { return skeletonRoot; }<|endoftext|>
<commit_before>#include "Accel.h" #define MOVING_AVERAGE_INTERVALS 20 #define COMPASS_ROTATE_FRACTION 0.05 #define ACCELEROMETER_FRACTION 0.1 #define ACCELEROMETER_CALIBRATE 0 #define MAG_CALIBRATE_X 0.7 #define MAG_CALIBRATE_Y -0.5 #define MAG_INVERT_Z -1.0 bool Accel::begin() { // Try to initialise and warn if we couldn't detect the chip if (!_lsm.begin()) { Serial.println("LSM!"); while (1); } // _lsm.setupAccel(_lsm.LSM9DS0_ACCELRANGE_4G); // _lsm.setupMag(_lsm.LSM9DS0_MAGGAIN_2GAUSS); _lsm.setupGyro(_lsm.LSM9DS0_GYROSCALE_500DPS); return true; } bool Accel::Update() { int newMillis = millis(); int elaspedMillis = newMillis - _lastUpdateMS; if ( elaspedMillis > _intervalMS + 10) { Serial.print("E: accel time: "); Serial.println(elaspedMillis); } if (elaspedMillis < _intervalMS) { return false; } _lastUpdateMS = newMillis; sensors_event_t accelEvent; sensors_event_t magEvent; sensors_event_t gyroEvent; //sensors_event_t tempEvent; _lsm.getEvent(&accelEvent, &magEvent, &gyroEvent, NULL); float magx = magEvent.magnetic.x + MAG_CALIBRATE_X; float magy = magEvent.magnetic.y + MAG_CALIBRATE_Y; float magz = magEvent.magnetic.z * MAG_INVERT_Z; // For some reason z points the opposite of north. // Gyro is in degrees per second, so we change to rads and mult by dt to get rotation. float degPerSec = Quaternion(gyroEvent.gyro.x, gyroEvent.gyro.y, gyroEvent.gyro.z).norm(); float degPerSecToRads = PI/180.0 * elaspedMillis / 1000.0; float gyrox = gyroEvent.gyro.x * degPerSecToRads; float gyroy = gyroEvent.gyro.y * degPerSecToRads; float gyroz = gyroEvent.gyro.z * degPerSecToRads; // Rotate by the gyro. This line takes 2ms to convert and multiply. _q *= Quaternion::from_euler_rotation_approx(gyrox, gyroy, gyroz); _q.normalize(); Quaternion gravity(accelEvent.acceleration.x, accelEvent.acceleration.y, accelEvent.acceleration.z); _currentAccel = gravity.norm() - SENSORS_GRAVITY_EARTH + ACCELEROMETER_CALIBRATE; float currentAbsAccel = abs(_currentAccel); _avgAbsAccel = (_avgAbsAccel * (MOVING_AVERAGE_INTERVALS - 1) + currentAbsAccel)/MOVING_AVERAGE_INTERVALS; // Ignore gravity if it isn't around G. We only want to update based on the accelrometer if we aren't bouncing. // We also want to ignore gravity if the gyro is moving a lot. // TODO: carrino: make these defines at the top if (degPerSec < 90 && currentAbsAccel < 1) { // cal expected gravity takes 1ms Quaternion expected_gravity = _q.conj().rotate(Quaternion(0, 0, 1)); if (_count++ % 2 == 0) { // This chunk of code takes 3ms gravity.normalize(); Quaternion toRotateG = gravity.rotation_between_vectors(expected_gravity); _q = _q * toRotateG.fractional(ACCELEROMETER_FRACTION); } else { // This code path of code takes 5ms // We want to subtract gravity from the magnetic reading. // mag readings point into the earth quite a bit, but gravity is handled by accelerometer ok. // We just want to use mag for rotation around the gravity axis. // https://en.wikipedia.org/wiki/Earth%27s_magnetic_field#Inclination Quaternion expected_north = _q.conj().rotate(Quaternion(1, 0, 0)); expected_north += expected_gravity * (-expected_gravity.dot_product(expected_north)); expected_north.normalize(); Quaternion mag(magx, magy, magz); mag += expected_gravity * (-expected_gravity.dot_product(mag)); mag.normalize(); Quaternion toRotateMag = mag.rotation_between_vectors(expected_north); _q = _q * toRotateMag.fractional(COMPASS_ROTATE_FRACTION); } } //int lastMillis = millis(); //Serial.print("Accel time: "); Serial.println(lastMillis - newMillis); return true; } const Quaternion Accel::getDeviceOrientation(const Quaternion &absolutePosition) const { return _q.conj().rotate(absolutePosition); } const Quaternion Accel::getAbsoluteOrientation(const Quaternion &deviceVector) const { return _q.rotate(deviceVector); } float Accel::getLinearAcceleration() const { return _currentAccel; } <commit_msg>zero out calibrate for breakout board<commit_after>#include "Accel.h" #define MOVING_AVERAGE_INTERVALS 20 #define COMPASS_ROTATE_FRACTION 0.05 #define ACCELEROMETER_FRACTION 0.1 #define ACCELEROMETER_CALIBRATE 0 #define MAG_CALIBRATE_X 0 #define MAG_CALIBRATE_Y 0 #define MAG_INVERT_Z -1.0 bool Accel::begin() { // Try to initialise and warn if we couldn't detect the chip if (!_lsm.begin()) { Serial.println("LSM!"); while (1); } // _lsm.setupAccel(_lsm.LSM9DS0_ACCELRANGE_4G); // _lsm.setupMag(_lsm.LSM9DS0_MAGGAIN_2GAUSS); _lsm.setupGyro(_lsm.LSM9DS0_GYROSCALE_500DPS); return true; } bool Accel::Update() { int newMillis = millis(); int elaspedMillis = newMillis - _lastUpdateMS; if ( elaspedMillis > _intervalMS + 10) { Serial.print("E: accel time: "); Serial.println(elaspedMillis); } if (elaspedMillis < _intervalMS) { return false; } _lastUpdateMS = newMillis; sensors_event_t accelEvent; sensors_event_t magEvent; sensors_event_t gyroEvent; //sensors_event_t tempEvent; _lsm.getEvent(&accelEvent, &magEvent, &gyroEvent, NULL); float magx = magEvent.magnetic.x + MAG_CALIBRATE_X; float magy = magEvent.magnetic.y + MAG_CALIBRATE_Y; float magz = magEvent.magnetic.z * MAG_INVERT_Z; // For some reason z points the opposite of north. // Gyro is in degrees per second, so we change to rads and mult by dt to get rotation. float degPerSec = Quaternion(gyroEvent.gyro.x, gyroEvent.gyro.y, gyroEvent.gyro.z).norm(); float degPerSecToRads = PI/180.0 * elaspedMillis / 1000.0; float gyrox = gyroEvent.gyro.x * degPerSecToRads; float gyroy = gyroEvent.gyro.y * degPerSecToRads; float gyroz = gyroEvent.gyro.z * degPerSecToRads; // Rotate by the gyro. This line takes 2ms to convert and multiply. _q *= Quaternion::from_euler_rotation_approx(gyrox, gyroy, gyroz); _q.normalize(); Quaternion gravity(accelEvent.acceleration.x, accelEvent.acceleration.y, accelEvent.acceleration.z); _currentAccel = gravity.norm() - SENSORS_GRAVITY_EARTH + ACCELEROMETER_CALIBRATE; float currentAbsAccel = abs(_currentAccel); _avgAbsAccel = (_avgAbsAccel * (MOVING_AVERAGE_INTERVALS - 1) + currentAbsAccel)/MOVING_AVERAGE_INTERVALS; // Ignore gravity if it isn't around G. We only want to update based on the accelrometer if we aren't bouncing. // We also want to ignore gravity if the gyro is moving a lot. // TODO: carrino: make these defines at the top if (degPerSec < 90 && currentAbsAccel < 1) { // cal expected gravity takes 1ms Quaternion expected_gravity = _q.conj().rotate(Quaternion(0, 0, 1)); if (_count++ % 2 == 0) { // This chunk of code takes 3ms gravity.normalize(); Quaternion toRotateG = gravity.rotation_between_vectors(expected_gravity); _q = _q * toRotateG.fractional(ACCELEROMETER_FRACTION); } else { // This code path of code takes 5ms // We want to subtract gravity from the magnetic reading. // mag readings point into the earth quite a bit, but gravity is handled by accelerometer ok. // We just want to use mag for rotation around the gravity axis. // https://en.wikipedia.org/wiki/Earth%27s_magnetic_field#Inclination Quaternion expected_north = _q.conj().rotate(Quaternion(1, 0, 0)); expected_north += expected_gravity * (-expected_gravity.dot_product(expected_north)); expected_north.normalize(); Quaternion mag(magx, magy, magz); mag += expected_gravity * (-expected_gravity.dot_product(mag)); mag.normalize(); Quaternion toRotateMag = mag.rotation_between_vectors(expected_north); _q = _q * toRotateMag.fractional(COMPASS_ROTATE_FRACTION); } } //int lastMillis = millis(); //Serial.print("Accel time: "); Serial.println(lastMillis - newMillis); return true; } const Quaternion Accel::getDeviceOrientation(const Quaternion &absolutePosition) const { return _q.conj().rotate(absolutePosition); } const Quaternion Accel::getAbsoluteOrientation(const Quaternion &deviceVector) const { return _q.rotate(deviceVector); } float Accel::getLinearAcceleration() const { return _currentAccel; } <|endoftext|>
<commit_before>#include "Board.hpp" Board::Board(string& name_, int& width_, int& height_, rapidjson::Value& mods) : name(name_), width(width_), height(height_) { this->board.resize(width); for (size_t i = 0; i < this->board.size(); i++) { this->board[i].resize(height); for (int j = 0; j < width; j++) { this->board[i][j] = new BoardMarker(); } } if (!mods["double_l"].IsNull()) { Modifier m = DOUBLE_L; apply_modifier_array(m, mods["double_l"]); } if (!mods["triple_l"].IsNull()) { Modifier m = TRIPLE_L; apply_modifier_array(m, mods["triple_l"]); } if (!mods["double_w"].IsNull()) { Modifier m = DOUBLE_W; apply_modifier_array(m, mods["double_w"]); } if (!mods["triple_w"].IsNull()) { Modifier m = TRIPLE_W; apply_modifier_array(m, mods["triple_w"]); } } void Board::apply_modifier_array(Modifier& m, rapidjson::Value& mod_array) { assert(mod_array.IsArray()); for (rapidjson::SizeType i = 0; i < mod_array.Size(); i++) { int x = mod_array[i]["x"].GetInt(); int y = mod_array[i]["y"].GetInt(); this->board[x - 1][y - 1]->apply_modifier(m); } } bool Board::set_char(char c, int w, int h) { if ( w < this->width && h < this->height && w >= 0 && h >= 0) { return this->board[w][h]->set_char(c); } return false; } void Board::print_board(Board& b) { for (size_t i = 0; i < this->board.size(); i++) { for (size_t j = 0; j < this->board[0].size(); j++) { this->board[i][j]->print_marker(); } cout << endl; } } <commit_msg>Fixed printing board<commit_after>#include "Board.hpp" Board::Board(string& name_, int& width_, int& height_, rapidjson::Value& mods) : name(name_), width(width_), height(height_) { this->board.resize(width); for (size_t i = 0; i < this->board.size(); i++) { this->board[i].resize(height); for (int j = 0; j < width; j++) { this->board[i][j] = new BoardMarker(); } } if (!mods["double_l"].IsNull()) { Modifier m = DOUBLE_L; apply_modifier_array(m, mods["double_l"]); } if (!mods["triple_l"].IsNull()) { Modifier m = TRIPLE_L; apply_modifier_array(m, mods["triple_l"]); } if (!mods["double_w"].IsNull()) { Modifier m = DOUBLE_W; apply_modifier_array(m, mods["double_w"]); } if (!mods["triple_w"].IsNull()) { Modifier m = TRIPLE_W; apply_modifier_array(m, mods["triple_w"]); } print_board(*this); } void Board::apply_modifier_array(Modifier& m, rapidjson::Value& mod_array) { assert(mod_array.IsArray()); for (rapidjson::SizeType i = 0; i < mod_array.Size(); i++) { int x = mod_array[i]["x"].GetInt(); int y = mod_array[i]["y"].GetInt(); this->board[x - 1][y - 1]->apply_modifier(m); } } bool Board::set_char(char c, int w, int h) { if ( w < this->width && h < this->height && w >= 0 && h >= 0) { return this->board[w][h]->set_char(c); } return false; } void Board::print_board(Board& b) { for (int j = (int) this->board[0].size() - 1; j > -1 ; j--) { for (size_t i = 0; i < this->board.size(); i++) { this->board[i][j]->print_marker(); } cout << endl; } } <|endoftext|>
<commit_before>#include <iostream> #include <functions.h> #include <kiste/raw.h> struct Data { float foo; }; int main() { const auto data = Data{3.1415}; auto& os = std::cout; auto serializer = kiste::raw{os}; auto sample = test::Sample(data, serializer); sample.render(); } <commit_msg>Remove conversion warning<commit_after>#include <iostream> #include <functions.h> #include <kiste/raw.h> struct Data { double foo; }; int main() { const auto data = Data{3.1415}; auto& os = std::cout; auto serializer = kiste::raw{os}; auto sample = test::Sample(data, serializer); sample.render(); } <|endoftext|>
<commit_before>/* * Copyright (C) 2010-2011, Mathieu Labbe and IntRoLab - Universite de Sherbrooke * * This file is part of RTAB-Map. * * RTAB-Map 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. * * RTAB-Map 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 RTAB-Map. If not, see <http://www.gnu.org/licenses/>. */ #include "rtabmap/core/Rtabmap.h" #include "rtabmap/core/RtabmapThread.h" #include "rtabmap/core/CameraOpenni.h" #include "rtabmap/core/Odometry.h" #include "rtabmap/utilite/UEventsManager.h" #include <QtGui/QApplication> #include <stdio.h> #include "MapBuilder.h" using namespace rtabmap; int main(int argc, char * argv[]) { ULogger::setType(ULogger::kTypeConsole); ULogger::setLevel(ULogger::kWarning); // GUI stuff, there the handler will receive RtabmapEvent and construct the map QApplication app(argc, argv); MapBuilder mapBuilder; // Here is the pipeline that we will use: // CameraOpenni -> "CameraEvent" -> OdometryThread -> "OdometryEvent" -> RtabmapThread -> "RtabmapEvent" // Create the OpenNI camera, it will send a CameraEvent at the rate specified. // Set transform to camera so z is up, y is left and x going forward CameraOpenni camera("", 10, rtabmap::Transform(0,0,1,0, -1,0,0,0, 0,-1,0,0)); if(!camera.init()) { UERROR("Camera init failed!"); exit(1); } // Create an odometry thread to process camera events, it will send OdometryEvent. OdometryThread odomThread(new OdometryBOW(0)); // 0=SURF 1=SIFT // Create RTAB-Map to process OdometryEvent Rtabmap * rtabmap = new Rtabmap(); rtabmap->init(); RtabmapThread rtabmapThread(rtabmap); // ownership is transfered rtabmapThread.setDetectorRate(0.0f); // as fast as we can // Setup handlers odomThread.registerToEventsManager(); rtabmapThread.registerToEventsManager(); mapBuilder.registerToEventsManager(); // The RTAB-Map is subscribed by default to CameraEvent, but we want // RTAB-Map to process OdometryEvent instead, ignoring the CameraEvent. // We can do that by creating a "pipe" between the camera and odometry, then // only the odometry will receive CameraEvent from that camera. RTAB-Map is // also subscribed to OdometryEvent by default, so no need to create a pipe between // odometry and RTAB-Map. UEventsManager::createPipe(&camera, &odomThread, "CameraEvent"); // Let's start the threads rtabmapThread.start(); odomThread.start(); camera.start(); mapBuilder.show(); app.exec(); // main loop // remove handlers mapBuilder.unregisterFromEventsManager(); rtabmapThread.unregisterFromEventsManager(); odomThread.unregisterFromEventsManager(); // Kill all threads camera.kill(); odomThread.join(true); rtabmapThread.join(true); return 0; } <commit_msg>updated rgbd example with rtabmap rate to 1 hz<commit_after>/* * Copyright (C) 2010-2011, Mathieu Labbe and IntRoLab - Universite de Sherbrooke * * This file is part of RTAB-Map. * * RTAB-Map 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. * * RTAB-Map 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 RTAB-Map. If not, see <http://www.gnu.org/licenses/>. */ #include "rtabmap/core/Rtabmap.h" #include "rtabmap/core/RtabmapThread.h" #include "rtabmap/core/CameraOpenni.h" #include "rtabmap/core/Odometry.h" #include "rtabmap/utilite/UEventsManager.h" #include <QtGui/QApplication> #include <stdio.h> #include "MapBuilder.h" using namespace rtabmap; int main(int argc, char * argv[]) { ULogger::setType(ULogger::kTypeConsole); ULogger::setLevel(ULogger::kWarning); // GUI stuff, there the handler will receive RtabmapEvent and construct the map QApplication app(argc, argv); MapBuilder mapBuilder; // Here is the pipeline that we will use: // CameraOpenni -> "CameraEvent" -> OdometryThread -> "OdometryEvent" -> RtabmapThread -> "RtabmapEvent" // Create the OpenNI camera, it will send a CameraEvent at the rate specified. // Set transform to camera so z is up, y is left and x going forward CameraOpenni camera("", 10, rtabmap::Transform(0,0,1,0, -1,0,0,0, 0,-1,0,0)); if(!camera.init()) { UERROR("Camera init failed!"); exit(1); } // Create an odometry thread to process camera events, it will send OdometryEvent. OdometryThread odomThread(new OdometryBOW(0)); // 0=SURF 1=SIFT // Create RTAB-Map to process OdometryEvent Rtabmap * rtabmap = new Rtabmap(); rtabmap->init(); RtabmapThread rtabmapThread(rtabmap); // ownership is transfered // Setup handlers odomThread.registerToEventsManager(); rtabmapThread.registerToEventsManager(); mapBuilder.registerToEventsManager(); // The RTAB-Map is subscribed by default to CameraEvent, but we want // RTAB-Map to process OdometryEvent instead, ignoring the CameraEvent. // We can do that by creating a "pipe" between the camera and odometry, then // only the odometry will receive CameraEvent from that camera. RTAB-Map is // also subscribed to OdometryEvent by default, so no need to create a pipe between // odometry and RTAB-Map. UEventsManager::createPipe(&camera, &odomThread, "CameraEvent"); // Let's start the threads rtabmapThread.start(); odomThread.start(); camera.start(); mapBuilder.show(); app.exec(); // main loop // remove handlers mapBuilder.unregisterFromEventsManager(); rtabmapThread.unregisterFromEventsManager(); odomThread.unregisterFromEventsManager(); // Kill all threads camera.kill(); odomThread.join(true); rtabmapThread.join(true); return 0; } <|endoftext|>