text
stringlengths 54
60.6k
|
|---|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: fieldmappingpage.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: rt $ $Date: 2005-09-08 19:07:52 $
*
* 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 EXTENSIONS_ABP_FIELDMAPPINGPAGE_HXX
#include "fieldmappingpage.hxx"
#endif
#ifndef EXTENSIONS_ABP_FIELDMAPPINGIMPL_HXX
#include "fieldmappingimpl.hxx"
#endif
#ifndef EXTENSIONS_ABP_ADDRESSSETTINGS_HXX
#include "addresssettings.hxx"
#endif
#ifndef EXTENSIONS_ABSPILOT_HXX
#include "abspilot.hxx"
#endif
//.........................................................................
namespace abp
{
//.........................................................................
//=====================================================================
//= FieldMappingPage
//=====================================================================
//---------------------------------------------------------------------
FieldMappingPage::FieldMappingPage( OAddessBookSourcePilot* _pParent )
:AddressBookSourcePage( _pParent, ModuleRes( RID_PAGE_FIELDMAPPING ) )
,m_aExplanation ( this, ResId( FT_FIELDASSIGMENTEXPL ) )
,m_aInvokeDialog ( this, ResId( PB_INVOKE_FIELDS_DIALOG ) )
,m_aHint ( this, ResId( FT_ASSIGNEDFIELDS ) )
{
FreeResource();
m_aInvokeDialog.SetClickHdl( LINK( this, FieldMappingPage, OnInvokeDialog ) );
// check the size of the InvokeDialog button - some languages are very ... gossipy here ....
// 96349 - 09.01.2002 - fs@openoffice.org
sal_Int32 nTextWidth = m_aInvokeDialog.GetTextWidth( m_aInvokeDialog.GetText() );
sal_Int32 nBorderSpace = m_aInvokeDialog.LogicToPixel( Point( 4, 0 ), MAP_APPFONT ).X();
sal_Int32 nSpace = m_aInvokeDialog.GetOutputSizePixel().Width() - 2 * nBorderSpace;
if ( nSpace < nTextWidth )
{
Size aButtonSize = m_aInvokeDialog.GetSizePixel();
aButtonSize.Width() += nTextWidth - nSpace;
m_aInvokeDialog.SetSizePixel( aButtonSize );
}
}
//---------------------------------------------------------------------
void FieldMappingPage::ActivatePage()
{
AddressBookSourcePage::ActivatePage();
m_aInvokeDialog.GrabFocus();
}
//---------------------------------------------------------------------
void FieldMappingPage::DeactivatePage()
{
AddressBookSourcePage::DeactivatePage();
}
//---------------------------------------------------------------------
void FieldMappingPage::initializePage()
{
AddressBookSourcePage::initializePage();
implUpdateHint();
}
//---------------------------------------------------------------------
sal_Bool FieldMappingPage::commitPage(COMMIT_REASON _eReason)
{
return AddressBookSourcePage::commitPage(_eReason);
}
//---------------------------------------------------------------------
void FieldMappingPage::implUpdateHint()
{
const AddressSettings& rSettings = getSettings();
String sHint;
if ( 0 == rSettings.aFieldMapping.size() )
sHint = String( ModuleRes( RID_STR_NOFIELDSASSIGNED ) );
m_aHint.SetText( sHint );
}
//---------------------------------------------------------------------
IMPL_LINK( FieldMappingPage, OnInvokeDialog, void*, NOTINTERESTEDIN )
{
AddressSettings& rSettings = getSettings();
// invoke the dialog doing the mapping
if ( fieldmapping::invokeDialog( getORB(), this, rSettings.bRegisterDataSource ? rSettings.sRegisteredDataSourceName : rSettings.sDataSourceName, rSettings.sSelectedTable, rSettings.aFieldMapping ) )
{
if ( rSettings.aFieldMapping.size() )
getDialog()->travelNext();
else
implUpdateHint();
}
return 0L;
}
//.........................................................................
} // namespace abp
//.........................................................................
<commit_msg>INTEGRATION: CWS dba201b (1.6.188); FILE MERGED 2005/09/21 06:41:51 oj 1.6.188.2: RESYNC: (1.6-1.7); FILE MERGED 2005/07/18 10:51:14 fs 1.6.188.1: #i51833# also pass the XDataSource object around - the field mapping dialog needs it, since the data source is not registered at the database context<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: fieldmappingpage.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: hr $ $Date: 2005-09-23 12:49:54 $
*
* 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 EXTENSIONS_ABP_FIELDMAPPINGPAGE_HXX
#include "fieldmappingpage.hxx"
#endif
#ifndef EXTENSIONS_ABP_FIELDMAPPINGIMPL_HXX
#include "fieldmappingimpl.hxx"
#endif
#ifndef EXTENSIONS_ABP_ADDRESSSETTINGS_HXX
#include "addresssettings.hxx"
#endif
#ifndef EXTENSIONS_ABSPILOT_HXX
#include "abspilot.hxx"
#endif
//.........................................................................
namespace abp
{
//.........................................................................
//=====================================================================
//= FieldMappingPage
//=====================================================================
//---------------------------------------------------------------------
FieldMappingPage::FieldMappingPage( OAddessBookSourcePilot* _pParent )
:AddressBookSourcePage( _pParent, ModuleRes( RID_PAGE_FIELDMAPPING ) )
,m_aExplanation ( this, ResId( FT_FIELDASSIGMENTEXPL ) )
,m_aInvokeDialog ( this, ResId( PB_INVOKE_FIELDS_DIALOG ) )
,m_aHint ( this, ResId( FT_ASSIGNEDFIELDS ) )
{
FreeResource();
m_aInvokeDialog.SetClickHdl( LINK( this, FieldMappingPage, OnInvokeDialog ) );
// check the size of the InvokeDialog button - some languages are very ... gossipy here ....
// 96349 - 09.01.2002 - fs@openoffice.org
sal_Int32 nTextWidth = m_aInvokeDialog.GetTextWidth( m_aInvokeDialog.GetText() );
sal_Int32 nBorderSpace = m_aInvokeDialog.LogicToPixel( Point( 4, 0 ), MAP_APPFONT ).X();
sal_Int32 nSpace = m_aInvokeDialog.GetOutputSizePixel().Width() - 2 * nBorderSpace;
if ( nSpace < nTextWidth )
{
Size aButtonSize = m_aInvokeDialog.GetSizePixel();
aButtonSize.Width() += nTextWidth - nSpace;
m_aInvokeDialog.SetSizePixel( aButtonSize );
}
}
//---------------------------------------------------------------------
void FieldMappingPage::ActivatePage()
{
AddressBookSourcePage::ActivatePage();
m_aInvokeDialog.GrabFocus();
}
//---------------------------------------------------------------------
void FieldMappingPage::DeactivatePage()
{
AddressBookSourcePage::DeactivatePage();
}
//---------------------------------------------------------------------
void FieldMappingPage::initializePage()
{
AddressBookSourcePage::initializePage();
implUpdateHint();
}
//---------------------------------------------------------------------
sal_Bool FieldMappingPage::commitPage(COMMIT_REASON _eReason)
{
return AddressBookSourcePage::commitPage(_eReason);
}
//---------------------------------------------------------------------
void FieldMappingPage::implUpdateHint()
{
const AddressSettings& rSettings = getSettings();
String sHint;
if ( 0 == rSettings.aFieldMapping.size() )
sHint = String( ModuleRes( RID_STR_NOFIELDSASSIGNED ) );
m_aHint.SetText( sHint );
}
//---------------------------------------------------------------------
IMPL_LINK( FieldMappingPage, OnInvokeDialog, void*, NOTINTERESTEDIN )
{
AddressSettings& rSettings = getSettings();
// invoke the dialog doing the mapping
if ( fieldmapping::invokeDialog( getORB(), this, getDialog()->getDataSource().getDataSource(), rSettings ) )
{
if ( rSettings.aFieldMapping.size() )
getDialog()->travelNext();
else
implUpdateHint();
}
return 0L;
}
//.........................................................................
} // namespace abp
//.........................................................................
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: propertyeditor.hxx,v $
*
* $Revision: 1.16 $
*
* last change: $Author: kz $ $Date: 2008-03-05 17:14:09 $
*
* 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 _EXTENSIONS_PROPCTRLR_PROPERTYEDITOR_HXX_
#define _EXTENSIONS_PROPCTRLR_PROPERTYEDITOR_HXX_
#ifndef _EXTENSIONS_PROPCTRLR_PCRCOMMON_HXX_
#include "pcrcommon.hxx"
#endif
/** === begin UNO includes === **/
#ifndef _COM_SUN_STAR_INSPECTION_XPROPERTYCONTROL_HPP_
#include <com/sun/star/inspection/XPropertyControl.hpp>
#endif
/** === end UNO includes === **/
#ifndef _SV_TABCTRL_HXX
#include <vcl/tabctrl.hxx>
#endif
#ifndef _COMPHELPER_STLTYPES_HXX_
#include <comphelper/stl_types.hxx>
#endif
#include <boost/mem_fn.hpp>
#include <map>
//............................................................................
namespace pcr
{
//............................................................................
class IPropertyLineListener;
class IPropertyControlObserver;
class OBrowserPage;
struct OLineDescriptor;
class OBrowserListBox;
//========================================================================
//= OPropertyEditor
//========================================================================
class OPropertyEditor : public Control
{
private:
typedef ::std::map< ::rtl::OUString, sal_uInt16 > MapStringToPageId;
struct HiddenPage
{
sal_uInt16 nPos;
TabPage* pPage;
HiddenPage() : nPos( 0 ), pPage( NULL ) { }
HiddenPage( sal_uInt16 _nPos, TabPage* _pPage ) : nPos( _nPos ), pPage( _pPage ) { }
};
private:
TabControl m_aTabControl;
IPropertyLineListener* m_pListener;
IPropertyControlObserver* m_pObserver;
sal_uInt16 m_nNextId;
Link m_aPageActivationHandler;
bool m_bHasHelpSection;
sal_Int32 m_nMinHelpLines;
sal_Int32 m_nMaxHelpLines;
MapStringToPageId m_aPropertyPageIds;
::std::map< sal_uInt16, HiddenPage > m_aHiddenPages;
protected:
void Resize();
void GetFocus();
public:
OPropertyEditor (Window* pParent, WinBits nWinStyle = WB_DIALOGCONTROL);
~OPropertyEditor();
sal_uInt16 CalcVisibleLines();
void EnableUpdate();
void DisableUpdate();
void SetLineListener( IPropertyLineListener* );
void SetControlObserver( IPropertyControlObserver* );
void EnableHelpSection( bool _bEnable );
bool HasHelpSection() const;
void SetHelpText( const ::rtl::OUString& _rHelpText );
void SetHelpLineLimites( sal_Int32 _nMinLines, sal_Int32 _nMaxLines );
void SetHelpId( sal_uInt32 nHelpId );
sal_uInt16 AppendPage( const String& r, const SmartId& _rHelpId );
void SetPage( sal_uInt16 );
void RemovePage(sal_uInt16 nID);
sal_uInt16 GetCurPage();
void ClearAll();
void SetPropertyValue(const ::rtl::OUString& _rEntryName, const ::com::sun::star::uno::Any& _rValue );
::com::sun::star::uno::Any GetPropertyValue(const ::rtl::OUString& rEntryName ) const;
sal_uInt16 GetPropertyPos(const ::rtl::OUString& rEntryName ) const;
::com::sun::star::uno::Reference< ::com::sun::star::inspection::XPropertyControl >
GetPropertyControl( const ::rtl::OUString& rEntryName );
void EnablePropertyLine( const ::rtl::OUString& _rEntryName, bool _bEnable );
void EnablePropertyControls( const ::rtl::OUString& _rEntryName, sal_Int16 _nControls, bool _bEnable );
sal_Bool IsPropertyInputEnabled( const ::rtl::OUString& _rEntryName ) const;
void ShowPropertyPage( sal_uInt16 _nPageId, bool _bShow );
sal_uInt16 InsertEntry( const OLineDescriptor&, sal_uInt16 _nPageId, sal_uInt16 nPos = EDITOR_LIST_APPEND );
void RemoveEntry( const ::rtl::OUString& _rName );
void ChangeEntry( const OLineDescriptor& );
void setPageActivationHandler(const Link& _rHdl) { m_aPageActivationHandler = _rHdl; }
Link getPageActivationHandler() const { return m_aPageActivationHandler; }
// #95343# -------------------------------
sal_Int32 getMinimumWidth();
sal_Int32 getMinimumHeight();
void CommitModified();
protected:
using Window::SetHelpText;
using Window::Update;
private:
OBrowserPage* getPage( sal_uInt16& _rPageId );
const OBrowserPage* getPage( sal_uInt16& _rPageId ) const;
OBrowserPage* getPage( const ::rtl::OUString& _rPropertyName );
const OBrowserPage* getPage( const ::rtl::OUString& _rPropertyName ) const;
void Update(const ::std::mem_fun_t<void,OBrowserListBox>& _aUpdateFunction);
typedef void (OPropertyEditor::*PageOperation)( OBrowserPage&, const void* );
void forEachPage( PageOperation _pOperation, const void* _pArgument = NULL );
void setPageLineListener( OBrowserPage& _rPage, const void* );
void setPageControlObserver( OBrowserPage& _rPage, const void* );
void enableHelpSection( OBrowserPage& _rPage, const void* );
void setHelpSectionText( OBrowserPage& _rPage, const void* _pPointerToOUString );
void setHelpLineLimits( OBrowserPage& _rPage, const void* );
protected:
DECL_LINK(OnPageDeactivate, TabControl*);
DECL_LINK(OnPageActivate, TabControl*);
};
//............................................................................
} // namespace pcr
//............................................................................
#endif // _EXTENSIONS_PROPCTRLR_PROPERTYEDITOR_HXX_
<commit_msg>INTEGRATION: CWS changefileheader (1.16.14); FILE MERGED 2008/04/01 15:15:20 thb 1.16.14.3: #i85898# Stripping all external header guards 2008/04/01 12:29:51 thb 1.16.14.2: #i85898# Stripping all external header guards 2008/03/31 12:31:53 rt 1.16.14.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: propertyeditor.hxx,v $
* $Revision: 1.17 $
*
* 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 _EXTENSIONS_PROPCTRLR_PROPERTYEDITOR_HXX_
#define _EXTENSIONS_PROPCTRLR_PROPERTYEDITOR_HXX_
#include "pcrcommon.hxx"
/** === begin UNO includes === **/
#include <com/sun/star/inspection/XPropertyControl.hpp>
/** === end UNO includes === **/
#include <vcl/tabctrl.hxx>
#include <comphelper/stl_types.hxx>
#include <boost/mem_fn.hpp>
#include <map>
//............................................................................
namespace pcr
{
//............................................................................
class IPropertyLineListener;
class IPropertyControlObserver;
class OBrowserPage;
struct OLineDescriptor;
class OBrowserListBox;
//========================================================================
//= OPropertyEditor
//========================================================================
class OPropertyEditor : public Control
{
private:
typedef ::std::map< ::rtl::OUString, sal_uInt16 > MapStringToPageId;
struct HiddenPage
{
sal_uInt16 nPos;
TabPage* pPage;
HiddenPage() : nPos( 0 ), pPage( NULL ) { }
HiddenPage( sal_uInt16 _nPos, TabPage* _pPage ) : nPos( _nPos ), pPage( _pPage ) { }
};
private:
TabControl m_aTabControl;
IPropertyLineListener* m_pListener;
IPropertyControlObserver* m_pObserver;
sal_uInt16 m_nNextId;
Link m_aPageActivationHandler;
bool m_bHasHelpSection;
sal_Int32 m_nMinHelpLines;
sal_Int32 m_nMaxHelpLines;
MapStringToPageId m_aPropertyPageIds;
::std::map< sal_uInt16, HiddenPage > m_aHiddenPages;
protected:
void Resize();
void GetFocus();
public:
OPropertyEditor (Window* pParent, WinBits nWinStyle = WB_DIALOGCONTROL);
~OPropertyEditor();
sal_uInt16 CalcVisibleLines();
void EnableUpdate();
void DisableUpdate();
void SetLineListener( IPropertyLineListener* );
void SetControlObserver( IPropertyControlObserver* );
void EnableHelpSection( bool _bEnable );
bool HasHelpSection() const;
void SetHelpText( const ::rtl::OUString& _rHelpText );
void SetHelpLineLimites( sal_Int32 _nMinLines, sal_Int32 _nMaxLines );
void SetHelpId( sal_uInt32 nHelpId );
sal_uInt16 AppendPage( const String& r, const SmartId& _rHelpId );
void SetPage( sal_uInt16 );
void RemovePage(sal_uInt16 nID);
sal_uInt16 GetCurPage();
void ClearAll();
void SetPropertyValue(const ::rtl::OUString& _rEntryName, const ::com::sun::star::uno::Any& _rValue );
::com::sun::star::uno::Any GetPropertyValue(const ::rtl::OUString& rEntryName ) const;
sal_uInt16 GetPropertyPos(const ::rtl::OUString& rEntryName ) const;
::com::sun::star::uno::Reference< ::com::sun::star::inspection::XPropertyControl >
GetPropertyControl( const ::rtl::OUString& rEntryName );
void EnablePropertyLine( const ::rtl::OUString& _rEntryName, bool _bEnable );
void EnablePropertyControls( const ::rtl::OUString& _rEntryName, sal_Int16 _nControls, bool _bEnable );
sal_Bool IsPropertyInputEnabled( const ::rtl::OUString& _rEntryName ) const;
void ShowPropertyPage( sal_uInt16 _nPageId, bool _bShow );
sal_uInt16 InsertEntry( const OLineDescriptor&, sal_uInt16 _nPageId, sal_uInt16 nPos = EDITOR_LIST_APPEND );
void RemoveEntry( const ::rtl::OUString& _rName );
void ChangeEntry( const OLineDescriptor& );
void setPageActivationHandler(const Link& _rHdl) { m_aPageActivationHandler = _rHdl; }
Link getPageActivationHandler() const { return m_aPageActivationHandler; }
// #95343# -------------------------------
sal_Int32 getMinimumWidth();
sal_Int32 getMinimumHeight();
void CommitModified();
protected:
using Window::SetHelpText;
using Window::Update;
private:
OBrowserPage* getPage( sal_uInt16& _rPageId );
const OBrowserPage* getPage( sal_uInt16& _rPageId ) const;
OBrowserPage* getPage( const ::rtl::OUString& _rPropertyName );
const OBrowserPage* getPage( const ::rtl::OUString& _rPropertyName ) const;
void Update(const ::std::mem_fun_t<void,OBrowserListBox>& _aUpdateFunction);
typedef void (OPropertyEditor::*PageOperation)( OBrowserPage&, const void* );
void forEachPage( PageOperation _pOperation, const void* _pArgument = NULL );
void setPageLineListener( OBrowserPage& _rPage, const void* );
void setPageControlObserver( OBrowserPage& _rPage, const void* );
void enableHelpSection( OBrowserPage& _rPage, const void* );
void setHelpSectionText( OBrowserPage& _rPage, const void* _pPointerToOUString );
void setHelpLineLimits( OBrowserPage& _rPage, const void* );
protected:
DECL_LINK(OnPageDeactivate, TabControl*);
DECL_LINK(OnPageActivate, TabControl*);
};
//............................................................................
} // namespace pcr
//............................................................................
#endif // _EXTENSIONS_PROPCTRLR_PROPERTYEDITOR_HXX_
<|endoftext|>
|
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/renderer/renderer_main_platform_delegate.h"
#include "base/debug_util.h"
extern "C" {
#include <sandbox.h>
}
#include "base/sys_info.h"
#include "third_party/WebKit/WebKit/mac/WebCoreSupport/WebSystemInterface.h"
RendererMainPlatformDelegate::RendererMainPlatformDelegate(
const MainFunctionParams& parameters)
: parameters_(parameters) {
}
RendererMainPlatformDelegate::~RendererMainPlatformDelegate() {
}
void RendererMainPlatformDelegate::PlatformInitialize() {
// Load WebKit system interfaces.
InitWebCoreSystemInterface();
}
void RendererMainPlatformDelegate::PlatformUninitialize() {
}
bool RendererMainPlatformDelegate::InitSandboxTests(bool no_sandbox) {
return true;
}
bool RendererMainPlatformDelegate::EnableSandbox() {
// TODO(port): hack
// With the sandbox on we don't have fonts in WebKit!
return true;
// This call doesn't work when the sandbox is enabled, the implementation
// caches it's return value so we call it here and then future calls will
// succeed.
DebugUtil::BeingDebugged();
// Cache the System info information, since we can't query certain attributes
// with the Sandbox enabled.
base::SysInfo::CacheSysInfo();
char* error_buff = NULL;
int error = sandbox_init(kSBXProfilePureComputation, SANDBOX_NAMED,
&error_buff);
bool success = (error == 0 && error_buff == NULL);
if (error == -1) {
LOG(ERROR) << "Failed to Initialize Sandbox: " << error_buff;
}
sandbox_free_error(error_buff);
return success;
}
void RendererMainPlatformDelegate::RunSandboxTests() {
// TODO(port): Run sandbox unit test here.
}
<commit_msg>Hack to get CG functions working in the OS X sandbox.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/renderer/renderer_main_platform_delegate.h"
#include "base/debug_util.h"
#include <ApplicationServices/ApplicationServices.h>
extern "C" {
#include <sandbox.h>
}
#include "base/sys_info.h"
#include "third_party/WebKit/WebKit/mac/WebCoreSupport/WebSystemInterface.h"
RendererMainPlatformDelegate::RendererMainPlatformDelegate(
const MainFunctionParams& parameters)
: parameters_(parameters) {
}
RendererMainPlatformDelegate::~RendererMainPlatformDelegate() {
}
void RendererMainPlatformDelegate::PlatformInitialize() {
// Load WebKit system interfaces.
InitWebCoreSystemInterface();
// Warmup CG - without these calls these two functions won't work in the
// sandbox.
CGColorSpaceRef rgb_colorspace =
CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB);
// Allocate a 1 byte image.
char data[8];
CGContextRef tmp = CGBitmapContextCreate(data, 1, 1, 8, 1*8,
rgb_colorspace,
kCGImageAlphaPremultipliedFirst |
kCGBitmapByteOrder32Host);
CGColorSpaceRelease(rgb_colorspace);
CGContextRelease(tmp);
}
void RendererMainPlatformDelegate::PlatformUninitialize() {
}
bool RendererMainPlatformDelegate::InitSandboxTests(bool no_sandbox) {
return true;
}
bool RendererMainPlatformDelegate::EnableSandbox() {
// TODO(port): hack
// With the sandbox on we don't have fonts in WebKit!
return true;
// This call doesn't work when the sandbox is enabled, the implementation
// caches it's return value so we call it here and then future calls will
// succeed.
DebugUtil::BeingDebugged();
// Cache the System info information, since we can't query certain attributes
// with the Sandbox enabled.
base::SysInfo::CacheSysInfo();
char* error_buff = NULL;
int error = sandbox_init(kSBXProfilePureComputation, SANDBOX_NAMED,
&error_buff);
bool success = (error == 0 && error_buff == NULL);
if (error == -1) {
LOG(ERROR) << "Failed to Initialize Sandbox: " << error_buff;
}
sandbox_free_error(error_buff);
return success;
}
void RendererMainPlatformDelegate::RunSandboxTests() {
// TODO(port): Run sandbox unit test here.
}
<|endoftext|>
|
<commit_before>#ifndef DD_BUNDLE_CALLER_HXX_
#define DD_BUNDLE_CALLER_HXX_
#include <opengm/inference/dualdecomposition/dualdecomposition_bundle.hxx>
#include <opengm/inference/dynamicprogramming.hxx>
#include <opengm/inference/messagepassing/messagepassing.hxx>
#ifdef WITH_CPLEX
#include <opengm/inference/lpcplex.hxx>
#endif
#include <opengm/inference/graphcut.hxx>
#ifdef WITH_MAXFLOW
# include <opengm/inference/auxiliary/minstcutkolmogorov.hxx>
#endif
#include "inference_caller_base.hxx"
#include "../argument/argument.hxx"
namespace opengm {
namespace interface {
template <class IO, class GM, class ACC>
class DDBundleCaller : public InferenceCallerBase<IO, GM, ACC, DDBundleCaller<IO, GM, ACC> >
{
protected:
typedef InferenceCallerBase<IO, GM, ACC, DDBundleCaller<IO, GM, ACC> > BaseClass;
typedef typename BaseClass::OutputBase OutputBase;
using BaseClass::addArgument;
using BaseClass::io_;
using BaseClass::infer;
double minimalAbsAccuracy_;
double minimalRelAccuracy_;
size_t maximalDualOrder_;
size_t numberOfBlocks_;
size_t maximalNumberOfIterations_;
size_t numberOfThreads_;
double relativeDualBoundPrecision_;
size_t maxBundlesize_;
bool activeBoundFixing_;
bool noBundle_;
double minDualWeight_;
double maxDualWeight_;
std::string stepsizeRule_;
std::string decomposition_;
std::string subInf_;
// Update Parameters
double stepsizeStride_; //updateStride_;
double stepsizeScale_; //updateScale_;
double stepsizeExponent_; //updateExponent_;
double stepsizeMin_; //updateMin_;
double stepsizeMax_; //updateMax_;
virtual void runImpl(GM& model, OutputBase& output, const bool verbose);
private:
template<class Parameter> void setParameter(Parameter& p);
public:
const static std::string name_;
DDBundleCaller(IO& ioIn);
};
template <class IO, class GM, class ACC>
const std::string DDBundleCaller<IO, GM, ACC>::name_ = "DDBundle";
template <class IO, class GM, class ACC>
inline DDBundleCaller<IO, GM, ACC>::DDBundleCaller(IO& ioIn)
: BaseClass("DD-Bundle", "detailed description of DD-Bundle Parser...", ioIn)
{
addArgument(Size_TArgument<>(maximalNumberOfIterations_,
"", "maxIt", "Maximum number of iterations.", size_t(100)));
addArgument(DoubleArgument<>(minimalAbsAccuracy_,
"", "absStop", "Stop if primal-dual-gap is smaller than this value", double(0.0)));
addArgument(DoubleArgument<>(minimalRelAccuracy_,
"", "relStop", "Stop if primal-dual-gap/(|dual|+1) is smale than this value", double(0.0)));
addArgument(DoubleArgument<>(stepsizeStride_,
"", "ssStride", "stride (s) of stepsize rule", double(1.0)));
addArgument(DoubleArgument<>(stepsizeScale_,
"", "ssScale", "scale (a) of stepsize rule", double(1.0)));
addArgument(DoubleArgument<>(stepsizeExponent_,
"", "ssExponent", "exponent (e) of stepsize rule", double(0.5)));
addArgument(DoubleArgument<>(stepsizeMin_,
"", "ssMin", "minimal stepsize", double(0.0)));
addArgument(DoubleArgument<>(stepsizeMax_,
"", "ssMax", "maximal stepsize", double(std::numeric_limits<double>::infinity())));
addArgument(Size_TArgument<>(numberOfBlocks_,
"", "numBlocks", "Number of blocks (subproblems).", size_t(2)));
addArgument(Size_TArgument<>(numberOfThreads_,
"", "numThreads", "Number of Threads used for primal subproblems", size_t(1)));
addArgument(Size_TArgument<>(maxBundlesize_,
"", "maxBS", "Maximum size of the bundle.", size_t(100)));
addArgument(DoubleArgument<>(relativeDualBoundPrecision_, "", "relDual", "Relative dual precision for termination", 0.00001));
addArgument(DoubleArgument<>(minDualWeight_, "", "minDW", "Minimal weight for the quadratic term.", -1.0));
addArgument(DoubleArgument<>(maxDualWeight_, "", "maxDW", "Maximal weight for the quadratic term.", -1.0));
addArgument(BoolArgument(activeBoundFixing_, "", "useFixing", "Fix duals if they are strong active "));
addArgument(BoolArgument(noBundle_, "", "noBundle", "Using one agregated subgradient instead of a bundle"));
std::vector<std::string> stepsizeRules;
stepsizeRules.push_back("KiwielsRule");
stepsizeRules.push_back("ProjectedAdaptive");
stepsizeRules.push_back("Adaptive");
stepsizeRules.push_back("StepLength");
stepsizeRules.push_back("StepSize");
addArgument(StringArgument<>(stepsizeRule_,
"", "stepsizeRule", "Stepsize rule for dual update \n \t\t\t\t\t\t\t* Kieweils Ruls: adaptive convergent heuristic\n \t\t\t\t\t\t\t* ProjectedAdaptive: primalDualGap/(1+ (a*i)^e)/|P(s)|\n \t\t\t\t\t\t\t* Adaptive: primalDualGap/(1+ (a*i)^e)/|s|\n \t\t\t\t\t\t\t* StepLength: s/(1+ (a*i)^e)/|P(s)|\n \t\t\t\t\t\t\t* StepSize: s/(1+ (a*i)^e)", stepsizeRules[0], stepsizeRules));
std::vector<std::string> subInfs;
subInfs.push_back("ILP");
subInfs.push_back("DPTree");
subInfs.push_back("DPHTree");
subInfs.push_back("GraphCut");
addArgument(StringArgument<>(subInf_,
"", "subInf", "Algorithm used for subproblems", subInfs[0], subInfs));
std::vector<std::string> decompositions;
decompositions.push_back("Tree");
decompositions.push_back("SpanningTrees");
decompositions.push_back("Blocks");
addArgument(StringArgument<>(decomposition_,
"", "decomp", "Type of used decomposition", decompositions[0], decompositions));
}
template <class IO, class GM, class ACC>
template<class Parameter>
void DDBundleCaller<IO, GM, ACC>::setParameter(Parameter& p)
{
p.minimalAbsAccuracy_=minimalAbsAccuracy_;
p.minimalRelAccuracy_=minimalRelAccuracy_;
p.maximalDualOrder_=maximalDualOrder_;
p.numberOfBlocks_=numberOfBlocks_;
p.maximalNumberOfIterations_=maximalNumberOfIterations_;
p.numberOfThreads_=numberOfThreads_;
p.relativeDualBoundPrecision_ = relativeDualBoundPrecision_;
p.maxBundlesize_=maxBundlesize_;
p.activeBoundFixing_=activeBoundFixing_;
p.noBundle_=noBundle_;
p.minDualWeight_=minDualWeight_;
p.maxDualWeight_=maxDualWeight_;
// Update Parameters
p.stepsizeStride_=stepsizeStride_; //updateStride_;
p.stepsizeScale_=stepsizeScale_; //updateScale_;
p.stepsizeExponent_=stepsizeExponent_; //updateExponent_;
p.stepsizeMin_=stepsizeMin_; //updateMin_;
p.stepsizeMax_=stepsizeMax_; //updateMax_;
//UpdateRule
if(stepsizeRule_.compare("KiewelsRule")==0){
p.useHeuristicStepsize_ = true;
}else if(stepsizeRule_.compare("ProjectedAdaptive")==0){
p.stepsizePrimalDualGapStride_ = true;
p.stepsizeNormalizedSubgradient_ = true;
p.useHeuristicStepsize_ = false;
}else if(stepsizeRule_.compare("Adaptive")==0){
p.stepsizePrimalDualGapStride_ = true;
p.stepsizeNormalizedSubgradient_ = false;
p.useHeuristicStepsize_ = false;
}else if(stepsizeRule_.compare("StepLength")==0){
p.stepsizePrimalDualGapStride_ = false;
p.stepsizeNormalizedSubgradient_ = true;
p.useHeuristicStepsize_ = false;
}else if(stepsizeRule_.compare("StepSize")==0){
p.stepsizePrimalDualGapStride_ = false;
p.stepsizeNormalizedSubgradient_ = false;
p.useHeuristicStepsize_ = false;
}else{
std::cout << "Unknown stepsize rule !!! " << std::endl;
}
//Decompositions
if(decomposition_.compare("Tree")==0){
p.decompositionId_= opengm::DualDecompositionBaseParameter::TREE;
}else if(decomposition_.compare("SpanningTrees")==0){
p.decompositionId_= opengm::DualDecompositionBaseParameter::SPANNINGTREES;
}else if(decomposition_.compare("Blocks")==0){
p.decompositionId_= opengm::DualDecompositionBaseParameter::BLOCKS;
}else{
std::cout << "Unknown decomposition type !!! " << std::endl;
}
}
template <class IO, class GM, class ACC>
inline void DDBundleCaller<IO, GM, ACC>::runImpl(GM& model, OutputBase& output, const bool verbose)
{
std::cout << "running DD-Bundle caller" << std::endl;
typedef typename GM::ValueType ValueType;
typedef opengm::DDDualVariableBlock2<marray::View<ValueType,false> > DualBlockType;
typedef typename opengm::DualDecompositionBase<GM,DualBlockType>::SubGmType SubGmType;
if((*this).subInf_.compare("ILP")==0){
#ifdef WITH_CPLEX
typedef opengm::LPCplex<SubGmType, ACC> InfType;
typedef opengm::DualDecompositionBundle<GM,InfType,DualBlockType> DDBundle;
typedef typename DDBundle::TimingVisitorType TimingVisitorType;
typename DDBundle::Parameter parameter;
setParameter(parameter);
parameter.subPara_.integerConstraint_ = true;
parameter.subPara_.numberOfThreads_ = 1;
this-> template infer<DDBundle, TimingVisitorType, typename DDBundle::Parameter>(model, output, verbose, parameter);
#else
std::cout << "CPLEX not enabled!!!" <<std::endl;
#endif
}
else if((*this).subInf_.compare("DPTree")==0){
typedef opengm::DynamicProgramming<SubGmType, ACC> InfType;
typedef opengm::DualDecompositionBundle<GM,InfType,DualBlockType> DDBundle;
typedef typename DDBundle::TimingVisitorType TimingVisitorType;
typename DDBundle::Parameter parameter;
setParameter(parameter);
this-> template infer<DDBundle, TimingVisitorType, typename DDBundle::Parameter>(model, output, verbose, parameter);
}
else if((*this).subInf_.compare("DPHTree")==0){
typedef opengm::BeliefPropagationUpdateRules<SubGmType, ACC> UpdateRulesType;
typedef opengm::MessagePassing<SubGmType, ACC, UpdateRulesType> InfType;
typedef opengm::DualDecompositionBundle<GM,InfType,DualBlockType> DDType;
typedef typename DDType::TimingVisitorType TimingVisitorType;
typename DDType::Parameter parameter;
setParameter(parameter);
parameter.subPara_.isAcyclic_ = true;
this-> template infer<DDType, TimingVisitorType, typename DDType::Parameter>(model, output, verbose, parameter);
}
else if((*this).subInf_.compare("GraphCut")==0){
#ifdef WITH_MAXFLOW
typedef opengm::external::MinSTCutKolmogorov<size_t, double> MinStCutType;
typedef opengm::GraphCut<SubGmType, ACC, MinStCutType> InfType;
typedef opengm::DualDecompositionBundle<GM,InfType,DualBlockType> DDBundle;
typedef typename DDBundle::TimingVisitorType TimingVisitorType;
typename DDBundle::Parameter parameter;
setParameter(parameter);
this-> template infer<DDBundle, TimingVisitorType, typename DDBundle::Parameter>(model, output, verbose, parameter);
#else
std::cout << "MaxFlow not enabled!!!" <<std::endl;
#endif
}
else{
std::cout << "Unknown Sub-Inference-Algorithm !!!" <<std::endl;
}
}
} // namespace interface
} // namespace opengm
#endif /* DDBUNDLE_CALLER_HXX_ */
<commit_msg>update caller<commit_after>#ifndef DD_BUNDLE_CALLER_HXX_
#define DD_BUNDLE_CALLER_HXX_
#include <opengm/inference/dualdecomposition/dualdecomposition_bundle.hxx>
#include <opengm/inference/dynamicprogramming.hxx>
#include <opengm/inference/messagepassing/messagepassing.hxx>
#ifdef WITH_CPLEX
#include <opengm/inference/lpcplex.hxx>
#endif
#include <opengm/inference/graphcut.hxx>
#ifdef WITH_MAXFLOW
# include <opengm/inference/auxiliary/minstcutkolmogorov.hxx>
#endif
#ifdef WITH_QPBO
#include <opengm/inference/reducedinference.hxx>
#endif
#include "inference_caller_base.hxx"
#include "../argument/argument.hxx"
#include <iostream>
#include <fstream>
namespace opengm {
namespace interface {
template <class IO, class GM, class ACC>
class DDBundleCaller : public InferenceCallerBase<IO, GM, ACC, DDBundleCaller<IO, GM, ACC> >
{
protected:
typedef InferenceCallerBase<IO, GM, ACC, DDBundleCaller<IO, GM, ACC> > BaseClass;
typedef typename BaseClass::OutputBase OutputBase;
using BaseClass::addArgument;
using BaseClass::io_;
using BaseClass::infer;
double minimalAbsAccuracy_;
double minimalRelAccuracy_;
size_t maximalDualOrder_;
size_t numberOfBlocks_;
size_t maximalNumberOfIterations_;
size_t numberOfThreads_;
double relativeDualBoundPrecision_;
size_t maxBundlesize_;
bool activeBoundFixing_;
bool noBundle_;
double minDualWeight_;
double maxDualWeight_;
size_t kfansize_;
std::string stepsizeRule_;
std::string decomposition_;
std::string subInf_;
std::string decompositionFile_;
// Update Parameters
double stepsizeStride_; //updateStride_;
double stepsizeScale_; //updateScale_;
double stepsizeExponent_; //updateExponent_;
double stepsizeMin_; //updateMin_;
double stepsizeMax_; //updateMax_;
virtual void runImpl(GM& model, OutputBase& output, const bool verbose);
private:
template<class Parameter> void setParameter(Parameter& p);
public:
const static std::string name_;
DDBundleCaller(IO& ioIn);
};
template <class IO, class GM, class ACC>
const std::string DDBundleCaller<IO, GM, ACC>::name_ = "DDBundle";
template <class IO, class GM, class ACC>
inline DDBundleCaller<IO, GM, ACC>::DDBundleCaller(IO& ioIn)
: BaseClass("DD-Bundle", "detailed description of DD-Bundle Parser...", ioIn)
{
addArgument(Size_TArgument<>(maximalNumberOfIterations_,
"", "maxIt", "Maximum number of iterations.", size_t(100)));
addArgument(DoubleArgument<>(minimalAbsAccuracy_,
"", "absStop", "Stop if primal-dual-gap is smaller than this value", double(0.0)));
addArgument(DoubleArgument<>(minimalRelAccuracy_,
"", "relStop", "Stop if primal-dual-gap/(|dual|+1) is smale than this value", double(0.0)));
addArgument(DoubleArgument<>(stepsizeStride_,
"", "ssStride", "stride (s) of stepsize rule", double(1.0)));
addArgument(DoubleArgument<>(stepsizeScale_,
"", "ssScale", "scale (a) of stepsize rule", double(1.0)));
addArgument(DoubleArgument<>(stepsizeExponent_,
"", "ssExponent", "exponent (e) of stepsize rule", double(0.5)));
addArgument(DoubleArgument<>(stepsizeMin_,
"", "ssMin", "minimal stepsize", double(0.0)));
addArgument(DoubleArgument<>(stepsizeMax_,
"", "ssMax", "maximal stepsize", double(std::numeric_limits<double>::infinity())));
addArgument(Size_TArgument<>(numberOfBlocks_,
"", "numBlocks", "Number of blocks (subproblems).", size_t(2)));
addArgument(Size_TArgument<>(numberOfThreads_,
"", "numThreads", "Number of Threads used for primal subproblems", size_t(1)));
addArgument(Size_TArgument<>(maxBundlesize_,
"", "maxBS", "Maximum size of the bundle.", size_t(100)));
addArgument(DoubleArgument<>(relativeDualBoundPrecision_, "", "relDual", "Relative dual precision for termination", 0.00001));
addArgument(DoubleArgument<>(minDualWeight_, "", "minDW", "Minimal weight for the quadratic term.", -1.0));
addArgument(DoubleArgument<>(maxDualWeight_, "", "maxDW", "Maximal weight for the quadratic term.", -1.0));
addArgument(BoolArgument(activeBoundFixing_, "", "useFixing", "Fix duals if they are strong active "));
addArgument(BoolArgument(noBundle_, "", "noBundle", "Using one agregated subgradient instead of a bundle"));
addArgument(Size_TArgument<>(kfansize_,
"", "kfansize", "Size of the kfan", size_t(4)));
std::vector<std::string> stepsizeRules;
stepsizeRules.push_back("KiwielsRule");
stepsizeRules.push_back("ProjectedAdaptive");
stepsizeRules.push_back("Adaptive");
stepsizeRules.push_back("StepLength");
stepsizeRules.push_back("StepSize");
addArgument(StringArgument<>(stepsizeRule_,
"", "stepsizeRule", "Stepsize rule for dual update \n \t\t\t\t\t\t\t* Kieweils Ruls: adaptive convergent heuristic\n \t\t\t\t\t\t\t* ProjectedAdaptive: primalDualGap/(1+ (a*i)^e)/|P(s)|\n \t\t\t\t\t\t\t* Adaptive: primalDualGap/(1+ (a*i)^e)/|s|\n \t\t\t\t\t\t\t* StepLength: s/(1+ (a*i)^e)/|P(s)|\n \t\t\t\t\t\t\t* StepSize: s/(1+ (a*i)^e)", stepsizeRules[0], stepsizeRules));
std::vector<std::string> subInfs;
subInfs.push_back("ILP");
subInfs.push_back("DPTree");
subInfs.push_back("DPHTree");
subInfs.push_back("GraphCut");
subInfs.push_back("RILP");
addArgument(StringArgument<>(subInf_,
"", "subInf", "Algorithm used for subproblems", subInfs[2], subInfs));
std::vector<std::string> decompositions;
decompositions.push_back("Tree");
decompositions.push_back("SpanningTrees");
decompositions.push_back("Blocks");
decompositions.push_back("KFans");
decompositions.push_back("File");
addArgument(StringArgument<>(decomposition_,
"", "decomp", "Type of used decomposition", decompositions[0], decompositions));
addArgument(StringArgument<>(decompositionFile_, "", "decompfile", "File with lists of variable Ids"));
}
template <class IO, class GM, class ACC>
template<class Parameter>
void DDBundleCaller<IO, GM, ACC>::setParameter(Parameter& p)
{
p.minimalAbsAccuracy_=minimalAbsAccuracy_;
p.minimalRelAccuracy_=minimalRelAccuracy_;
p.maximalDualOrder_=maximalDualOrder_;
p.numberOfBlocks_=numberOfBlocks_;
p.maximalNumberOfIterations_=maximalNumberOfIterations_;
p.numberOfThreads_=numberOfThreads_;
p.relativeDualBoundPrecision_ = relativeDualBoundPrecision_;
p.maxBundlesize_=maxBundlesize_;
p.activeBoundFixing_=activeBoundFixing_;
p.noBundle_=noBundle_;
p.minDualWeight_=minDualWeight_;
p.maxDualWeight_=maxDualWeight_;
// Update Parameters
p.stepsizeStride_=stepsizeStride_; //updateStride_;
p.stepsizeScale_=stepsizeScale_; //updateScale_;
p.stepsizeExponent_=stepsizeExponent_; //updateExponent_;
p.stepsizeMin_=stepsizeMin_; //updateMin_;
p.stepsizeMax_=stepsizeMax_; //updateMax_;
p.k_ = kfansize_;
//UpdateRule
if(stepsizeRule_.compare("KiewelsRule")==0){
p.useHeuristicStepsize_ = true;
}else if(stepsizeRule_.compare("ProjectedAdaptive")==0){
p.stepsizePrimalDualGapStride_ = true;
p.stepsizeNormalizedSubgradient_ = true;
p.useHeuristicStepsize_ = false;
}else if(stepsizeRule_.compare("Adaptive")==0){
p.stepsizePrimalDualGapStride_ = true;
p.stepsizeNormalizedSubgradient_ = false;
p.useHeuristicStepsize_ = false;
}else if(stepsizeRule_.compare("StepLength")==0){
p.stepsizePrimalDualGapStride_ = false;
p.stepsizeNormalizedSubgradient_ = true;
p.useHeuristicStepsize_ = false;
}else if(stepsizeRule_.compare("StepSize")==0){
p.stepsizePrimalDualGapStride_ = false;
p.stepsizeNormalizedSubgradient_ = false;
p.useHeuristicStepsize_ = false;
}else{
std::cout << "Unknown stepsize rule !!! " << std::endl;
}
//Decompositions
if(decomposition_.compare("Tree")==0){
p.decompositionId_= opengm::DualDecompositionBaseParameter::TREE;
}else if(decomposition_.compare("SpanningTrees")==0){
p.decompositionId_= opengm::DualDecompositionBaseParameter::SPANNINGTREES;
}else if(decomposition_.compare("Blocks")==0){
p.decompositionId_= opengm::DualDecompositionBaseParameter::BLOCKS;
}else if(decomposition_.compare("KFans")==0){
p.decompositionId_= opengm::DualDecompositionBaseParameter::KFANS;
}
else if(decomposition_.compare("File")==0){
std::cout << "Read decomposition from file "<<decompositionFile_<<"!"<<std::endl;
std::ifstream in(decompositionFile_.c_str());
std::string line;
std::vector<std::set<size_t> > decomp;
while(getline(in, line)) {
decomp.push_back(std::set<size_t>());
//cout << line << endl;
std::istringstream iss(line);
size_t num;
while (iss >> num){
decomp.back().insert(num);
}
std::cout << "Subproblem "<< decomp.size() << " has " << decomp.back().size() <<" variables."<<std::endl;
}
in.close();
//p.decompositionId_= opengm::DualDecompositionBaseParameter::MANUALVARCLOSE; // add neighbored variables
p.decompositionId_= opengm::DualDecompositionBaseParameter::MANUALVAROPEN;
p.subVariables_ = decomp;
}
else{
std::cout << "Unknown decomposition type !!! " << std::endl;
}
}
template <class IO, class GM, class ACC>
inline void DDBundleCaller<IO, GM, ACC>::runImpl(GM& model, OutputBase& output, const bool verbose)
{
std::cout << "running DD-Bundle caller" << std::endl;
typedef typename GM::ValueType ValueType;
typedef opengm::DDDualVariableBlock2<marray::View<ValueType,false> > DualBlockType;
typedef typename opengm::DualDecompositionBase<GM,DualBlockType>::SubGmType SubGmType;
if((*this).subInf_.compare("ILP")==0){
#ifdef WITH_CPLEX
typedef opengm::LPCplex<SubGmType, ACC> InfType;
typedef opengm::DualDecompositionBundle<GM,InfType,DualBlockType> DDBundle;
typedef typename DDBundle::TimingVisitorType TimingVisitorType;
typename DDBundle::Parameter parameter;
setParameter(parameter);
parameter.subPara_.integerConstraint_ = true;
parameter.subPara_.numberOfThreads_ = 1;
this-> template infer<DDBundle, TimingVisitorType, typename DDBundle::Parameter>(model, output, verbose, parameter);
#else
std::cout << "CPLEX not enabled!!!" <<std::endl;
#endif
}
else if((*this).subInf_.compare("DPTree")==0){
typedef opengm::DynamicProgramming<SubGmType, ACC> InfType;
typedef opengm::DualDecompositionBundle<GM,InfType,DualBlockType> DDBundle;
typedef typename DDBundle::TimingVisitorType TimingVisitorType;
typename DDBundle::Parameter parameter;
setParameter(parameter);
this-> template infer<DDBundle, TimingVisitorType, typename DDBundle::Parameter>(model, output, verbose, parameter);
}
else if((*this).subInf_.compare("DPHTree")==0){
typedef opengm::BeliefPropagationUpdateRules<SubGmType, ACC> UpdateRulesType;
typedef opengm::MessagePassing<SubGmType, ACC, UpdateRulesType> InfType;
typedef opengm::DualDecompositionBundle<GM,InfType,DualBlockType> DDType;
typedef typename DDType::TimingVisitorType TimingVisitorType;
typename DDType::Parameter parameter;
setParameter(parameter);
parameter.subPara_.isAcyclic_ = true;
this-> template infer<DDType, TimingVisitorType, typename DDType::Parameter>(model, output, verbose, parameter);
}
else if((*this).subInf_.compare("GraphCut")==0){
#ifdef WITH_MAXFLOW
typedef opengm::external::MinSTCutKolmogorov<size_t, double> MinStCutType;
typedef opengm::GraphCut<SubGmType, ACC, MinStCutType> InfType;
typedef opengm::DualDecompositionBundle<GM,InfType,DualBlockType> DDBundle;
typedef typename DDBundle::TimingVisitorType TimingVisitorType;
typename DDBundle::Parameter parameter;
setParameter(parameter);
this-> template infer<DDBundle, TimingVisitorType, typename DDBundle::Parameter>(model, output, verbose, parameter);
#else
std::cout << "MaxFlow not enabled!!!" <<std::endl;
#endif
}
else if((*this).subInf_.compare("RILP")==0){
#ifdef WITH_QPBO
#ifdef WITH_CPLEX
typedef typename ReducedInferenceHelper<SubGmType>::InfGmType GM2;
typedef opengm::LPCplex<GM2, ACC> ILP;
typedef ReducedInference<SubGmType,ACC,ILP> InfType;
typedef opengm::DualDecompositionBundle<GM,InfType,DualBlockType> DDBundle;
typedef typename DDBundle::TimingVisitorType TimingVisitorType;
typename DDBundle::Parameter parameter;
setParameter(parameter);
parameter.subPara_.Persistency_ = true;
parameter.subPara_.Tentacle_ = true;
parameter.subPara_.ConnectedComponents_ = true;
parameter.subPara_.subParameter_.integerConstraint_ = true;
parameter.subPara_.subParameter_.numberOfThreads_ = 1;
this-> template infer<DDBundle, TimingVisitorType, typename DDBundle::Parameter>(model, output, verbose, parameter);
#else
std::cout << "CPLEX not enabled!!!" <<std::endl;
#endif
#else
std::cout << "QPBO not enabled!!!" <<std::endl;
#endif
}
else{
std::cout << "Unknown Sub-Inference-Algorithm !!!" <<std::endl;
}
}
} // namespace interface
} // namespace opengm
#endif /* DDBUNDLE_CALLER_HXX_ */
<|endoftext|>
|
<commit_before>// Copyright (c) 2011-2013 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#if defined(HAVE_CONFIG_H)
#include "config/pivx-config.h"
#endif
#include "optionsdialog.h"
#include "ui_optionsdialog.h"
#include "bitcoinunits.h"
#include "guiutil.h"
#include "obfuscation.h"
#include "optionsmodel.h"
#include "main.h" // for MAX_SCRIPTCHECK_THREADS
#include "netbase.h"
#include "txdb.h" // for -dbcache defaults
#ifdef ENABLE_WALLET
#include "wallet.h" // for CWallet::minTxFee
#endif
#include <boost/thread.hpp>
#include <QDataWidgetMapper>
#include <QDir>
#include <QIntValidator>
#include <QLocale>
#include <QMessageBox>
#include <QTimer>
OptionsDialog::OptionsDialog(QWidget* parent, bool enableWallet) : QDialog(parent),
ui(new Ui::OptionsDialog),
model(0),
mapper(0),
fProxyIpValid(true)
{
ui->setupUi(this);
GUIUtil::restoreWindowGeometry("nOptionsDialogWindow", this->size(), this);
/* Main elements init */
ui->databaseCache->setMinimum(nMinDbCache);
ui->databaseCache->setMaximum(nMaxDbCache);
ui->threadsScriptVerif->setMinimum(-(int)boost::thread::hardware_concurrency());
ui->threadsScriptVerif->setMaximum(MAX_SCRIPTCHECK_THREADS);
/* Network elements init */
#ifndef USE_UPNP
ui->mapPortUpnp->setEnabled(false);
#endif
ui->proxyIp->setEnabled(false);
ui->proxyPort->setEnabled(false);
ui->proxyPort->setValidator(new QIntValidator(1, 65535, this));
connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->proxyIp, SLOT(setEnabled(bool)));
connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->proxyPort, SLOT(setEnabled(bool)));
ui->proxyIp->installEventFilter(this);
/* Window elements init */
#ifdef Q_OS_MAC
/* remove Window tab on Mac */
ui->tabWidget->removeTab(ui->tabWidget->indexOf(ui->tabWindow));
#endif
/* remove Wallet tab in case of -disablewallet */
if (!enableWallet) {
ui->tabWidget->removeTab(ui->tabWidget->indexOf(ui->tabWallet));
}
/* Display elements init */
/* Number of displayed decimal digits selector */
QString digits;
for (int index = 2; index <= 8; index++) {
digits.setNum(index);
ui->digits->addItem(digits, digits);
}
/* Preferred Zerocoin Denominations */
ui->theme->addItem(QString("Default"), QVariant("default"));
/* Theme selector static themes */
ui->preferredDenom->addItem(QString(tr("I don't care")), QVariant("0"));
ui->preferredDenom->addItem(QString("1"), QVariant("1"));
ui->preferredDenom->addItem(QString("5"), QVariant("5"));
ui->preferredDenom->addItem(QString("10"), QVariant("10"));
ui->preferredDenom->addItem(QString("50"), QVariant("50"));
ui->preferredDenom->addItem(QString("100"), QVariant("100"));
ui->preferredDenom->addItem(QString("500"), QVariant("500"));
ui->preferredDenom->addItem(QString("1000"), QVariant("1000"));
ui->preferredDenom->addItem(QString("5000"), QVariant("5000"));
/* Theme selector external themes */
boost::filesystem::path pathAddr = GetDataDir() / "themes";
QDir dir(pathAddr.string().c_str());
dir.setFilter(QDir::Dirs | QDir::NoSymLinks | QDir::NoDotAndDotDot);
QFileInfoList list = dir.entryInfoList();
for (int i = 0; i < list.size(); ++i) {
QFileInfo fileInfo = list.at(i);
ui->theme->addItem(fileInfo.fileName(), QVariant(fileInfo.fileName()));
}
/* Language selector */
QDir translations(":translations");
ui->lang->addItem(QString("(") + tr("default") + QString(")"), QVariant(""));
foreach (const QString& langStr, translations.entryList()) {
QLocale locale(langStr);
/** check if the locale name consists of 2 parts (language_country) */
if (langStr.contains("_")) {
#if QT_VERSION >= 0x040800
/** display language strings as "native language - native country (locale name)", e.g. "Deutsch - Deutschland (de)" */
ui->lang->addItem(locale.nativeLanguageName() + QString(" - ") + locale.nativeCountryName() + QString(" (") + langStr + QString(")"), QVariant(langStr));
#else
/** display language strings as "language - country (locale name)", e.g. "German - Germany (de)" */
ui->lang->addItem(QLocale::languageToString(locale.language()) + QString(" - ") + QLocale::countryToString(locale.country()) + QString(" (") + langStr + QString(")"), QVariant(langStr));
#endif
} else {
#if QT_VERSION >= 0x040800
/** display language strings as "native language (locale name)", e.g. "Deutsch (de)" */
ui->lang->addItem(locale.nativeLanguageName() + QString(" (") + langStr + QString(")"), QVariant(langStr));
#else
/** display language strings as "language (locale name)", e.g. "German (de)" */
ui->lang->addItem(QLocale::languageToString(locale.language()) + QString(" (") + langStr + QString(")"), QVariant(langStr));
#endif
}
}
#if QT_VERSION >= 0x040700
ui->thirdPartyTxUrls->setPlaceholderText("https://example.com/tx/%s");
#endif
ui->unit->setModel(new BitcoinUnits(this));
/* Widget-to-option mapper */
mapper = new QDataWidgetMapper(this);
mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit);
mapper->setOrientation(Qt::Vertical);
/* setup/change UI elements when proxy IP is invalid/valid */
connect(this, SIGNAL(proxyIpChecks(QValidatedLineEdit*, int)), this, SLOT(doProxyIpChecks(QValidatedLineEdit*, int)));
}
OptionsDialog::~OptionsDialog()
{
GUIUtil::saveWindowGeometry("nOptionsDialogWindow", this);
delete ui;
}
void OptionsDialog::setModel(OptionsModel* model)
{
this->model = model;
if (model) {
/* check if client restart is needed and show persistent message */
if (model->isRestartRequired())
showRestartWarning(true);
QString strLabel = model->getOverriddenByCommandLine();
if (strLabel.isEmpty())
strLabel = tr("none");
ui->overriddenByCommandLineLabel->setText(strLabel);
mapper->setModel(model);
setMapper();
mapper->toFirst();
}
/* warn when one of the following settings changes by user action (placed here so init via mapper doesn't trigger them) */
/* Main */
connect(ui->databaseCache, SIGNAL(valueChanged(int)), this, SLOT(showRestartWarning()));
connect(ui->threadsScriptVerif, SIGNAL(valueChanged(int)), this, SLOT(showRestartWarning()));
/* Wallet */
connect(ui->spendZeroConfChange, SIGNAL(clicked(bool)), this, SLOT(showRestartWarning()));
/* Network */
connect(ui->allowIncoming, SIGNAL(clicked(bool)), this, SLOT(showRestartWarning()));
connect(ui->connectSocks, SIGNAL(clicked(bool)), this, SLOT(showRestartWarning()));
/* Display */
connect(ui->digits, SIGNAL(valueChanged()), this, SLOT(showRestartWarning()));
connect(ui->theme, SIGNAL(valueChanged()), this, SLOT(showRestartWarning()));
connect(ui->lang, SIGNAL(valueChanged()), this, SLOT(showRestartWarning()));
connect(ui->thirdPartyTxUrls, SIGNAL(textChanged(const QString&)), this, SLOT(showRestartWarning()));
connect(ui->showMasternodesTab, SIGNAL(clicked(bool)), this, SLOT(showRestartWarning()));
}
void OptionsDialog::setMapper()
{
/* Main */
mapper->addMapping(ui->bitcoinAtStartup, OptionsModel::StartAtStartup);
mapper->addMapping(ui->threadsScriptVerif, OptionsModel::ThreadsScriptVerif);
mapper->addMapping(ui->databaseCache, OptionsModel::DatabaseCache);
// Zerocoin mint percentage
mapper->addMapping(ui->zeromintPercentage, OptionsModel::ZeromintPercentage);
// Zerocoin preferred denomination
mapper->addMapping(ui->preferredDenom, OptionsModel::ZeromintPrefDenom);
/* Wallet */
mapper->addMapping(ui->spendZeroConfChange, OptionsModel::SpendZeroConfChange);
mapper->addMapping(ui->coinControlFeatures, OptionsModel::CoinControlFeatures);
/* Network */
mapper->addMapping(ui->mapPortUpnp, OptionsModel::MapPortUPnP);
mapper->addMapping(ui->allowIncoming, OptionsModel::Listen);
mapper->addMapping(ui->connectSocks, OptionsModel::ProxyUse);
mapper->addMapping(ui->proxyIp, OptionsModel::ProxyIP);
mapper->addMapping(ui->proxyPort, OptionsModel::ProxyPort);
/* Window */
#ifndef Q_OS_MAC
mapper->addMapping(ui->minimizeToTray, OptionsModel::MinimizeToTray);
mapper->addMapping(ui->minimizeOnClose, OptionsModel::MinimizeOnClose);
#endif
/* Display */
mapper->addMapping(ui->digits, OptionsModel::Digits);
mapper->addMapping(ui->theme, OptionsModel::Theme);
mapper->addMapping(ui->theme, OptionsModel::Theme);
mapper->addMapping(ui->lang, OptionsModel::Language);
mapper->addMapping(ui->unit, OptionsModel::DisplayUnit);
mapper->addMapping(ui->thirdPartyTxUrls, OptionsModel::ThirdPartyTxUrls);
/* Masternode Tab */
mapper->addMapping(ui->showMasternodesTab, OptionsModel::ShowMasternodesTab);
}
void OptionsDialog::enableOkButton()
{
/* prevent enabling of the OK button when data modified, if there is an invalid proxy address present */
if (fProxyIpValid)
setOkButtonState(true);
}
void OptionsDialog::disableOkButton()
{
setOkButtonState(false);
}
void OptionsDialog::setOkButtonState(bool fState)
{
ui->okButton->setEnabled(fState);
}
void OptionsDialog::on_resetButton_clicked()
{
if (model) {
// confirmation dialog
QMessageBox::StandardButton btnRetVal = QMessageBox::question(this, tr("Confirm options reset"),
tr("Client restart required to activate changes.") + "<br><br>" + tr("Client will be shutdown, do you want to proceed?"),
QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Cancel);
if (btnRetVal == QMessageBox::Cancel)
return;
/* reset all options and close GUI */
model->Reset();
QApplication::quit();
}
}
void OptionsDialog::on_okButton_clicked()
{
mapper->submit();
obfuScationPool.cachedNumBlocks = std::numeric_limits<int>::max();
pwalletMain->MarkDirty();
accept();
}
void OptionsDialog::on_cancelButton_clicked()
{
reject();
}
void OptionsDialog::showRestartWarning(bool fPersistent)
{
ui->statusLabel->setStyleSheet("QLabel { color: red; }");
if (fPersistent) {
ui->statusLabel->setText(tr("Client restart required to activate changes."));
} else {
ui->statusLabel->setText(tr("This change would require a client restart."));
// clear non-persistent status label after 10 seconds
// Todo: should perhaps be a class attribute, if we extend the use of statusLabel
QTimer::singleShot(10000, this, SLOT(clearStatusLabel()));
}
}
void OptionsDialog::clearStatusLabel()
{
ui->statusLabel->clear();
}
void OptionsDialog::doProxyIpChecks(QValidatedLineEdit* pUiProxyIp, int nProxyPort)
{
Q_UNUSED(nProxyPort);
const std::string strAddrProxy = pUiProxyIp->text().toStdString();
CService addrProxy;
/* Check for a valid IPv4 / IPv6 address */
if (!(fProxyIpValid = LookupNumeric(strAddrProxy.c_str(), addrProxy))) {
disableOkButton();
pUiProxyIp->setValid(false);
ui->statusLabel->setStyleSheet("QLabel { color: red; }");
ui->statusLabel->setText(tr("The supplied proxy address is invalid."));
} else {
enableOkButton();
ui->statusLabel->clear();
}
}
bool OptionsDialog::eventFilter(QObject* object, QEvent* event)
{
if (event->type() == QEvent::FocusOut) {
if (object == ui->proxyIp) {
emit proxyIpChecks(ui->proxyIp, ui->proxyPort->text().toInt());
}
}
return QDialog::eventFilter(object, event);
}
<commit_msg>Comments swapped<commit_after>// Copyright (c) 2011-2013 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#if defined(HAVE_CONFIG_H)
#include "config/pivx-config.h"
#endif
#include "optionsdialog.h"
#include "ui_optionsdialog.h"
#include "bitcoinunits.h"
#include "guiutil.h"
#include "obfuscation.h"
#include "optionsmodel.h"
#include "main.h" // for MAX_SCRIPTCHECK_THREADS
#include "netbase.h"
#include "txdb.h" // for -dbcache defaults
#ifdef ENABLE_WALLET
#include "wallet.h" // for CWallet::minTxFee
#endif
#include <boost/thread.hpp>
#include <QDataWidgetMapper>
#include <QDir>
#include <QIntValidator>
#include <QLocale>
#include <QMessageBox>
#include <QTimer>
OptionsDialog::OptionsDialog(QWidget* parent, bool enableWallet) : QDialog(parent),
ui(new Ui::OptionsDialog),
model(0),
mapper(0),
fProxyIpValid(true)
{
ui->setupUi(this);
GUIUtil::restoreWindowGeometry("nOptionsDialogWindow", this->size(), this);
/* Main elements init */
ui->databaseCache->setMinimum(nMinDbCache);
ui->databaseCache->setMaximum(nMaxDbCache);
ui->threadsScriptVerif->setMinimum(-(int)boost::thread::hardware_concurrency());
ui->threadsScriptVerif->setMaximum(MAX_SCRIPTCHECK_THREADS);
/* Network elements init */
#ifndef USE_UPNP
ui->mapPortUpnp->setEnabled(false);
#endif
ui->proxyIp->setEnabled(false);
ui->proxyPort->setEnabled(false);
ui->proxyPort->setValidator(new QIntValidator(1, 65535, this));
connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->proxyIp, SLOT(setEnabled(bool)));
connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->proxyPort, SLOT(setEnabled(bool)));
ui->proxyIp->installEventFilter(this);
/* Window elements init */
#ifdef Q_OS_MAC
/* remove Window tab on Mac */
ui->tabWidget->removeTab(ui->tabWidget->indexOf(ui->tabWindow));
#endif
/* remove Wallet tab in case of -disablewallet */
if (!enableWallet) {
ui->tabWidget->removeTab(ui->tabWidget->indexOf(ui->tabWallet));
}
/* Display elements init */
/* Number of displayed decimal digits selector */
QString digits;
for (int index = 2; index <= 8; index++) {
digits.setNum(index);
ui->digits->addItem(digits, digits);
}
/* Theme selector static themes */
ui->theme->addItem(QString("Default"), QVariant("default"));
/* Preferred Zerocoin Denominations */
ui->preferredDenom->addItem(QString(tr("I don't care")), QVariant("0"));
ui->preferredDenom->addItem(QString("1"), QVariant("1"));
ui->preferredDenom->addItem(QString("5"), QVariant("5"));
ui->preferredDenom->addItem(QString("10"), QVariant("10"));
ui->preferredDenom->addItem(QString("50"), QVariant("50"));
ui->preferredDenom->addItem(QString("100"), QVariant("100"));
ui->preferredDenom->addItem(QString("500"), QVariant("500"));
ui->preferredDenom->addItem(QString("1000"), QVariant("1000"));
ui->preferredDenom->addItem(QString("5000"), QVariant("5000"));
/* Theme selector external themes */
boost::filesystem::path pathAddr = GetDataDir() / "themes";
QDir dir(pathAddr.string().c_str());
dir.setFilter(QDir::Dirs | QDir::NoSymLinks | QDir::NoDotAndDotDot);
QFileInfoList list = dir.entryInfoList();
for (int i = 0; i < list.size(); ++i) {
QFileInfo fileInfo = list.at(i);
ui->theme->addItem(fileInfo.fileName(), QVariant(fileInfo.fileName()));
}
/* Language selector */
QDir translations(":translations");
ui->lang->addItem(QString("(") + tr("default") + QString(")"), QVariant(""));
foreach (const QString& langStr, translations.entryList()) {
QLocale locale(langStr);
/** check if the locale name consists of 2 parts (language_country) */
if (langStr.contains("_")) {
#if QT_VERSION >= 0x040800
/** display language strings as "native language - native country (locale name)", e.g. "Deutsch - Deutschland (de)" */
ui->lang->addItem(locale.nativeLanguageName() + QString(" - ") + locale.nativeCountryName() + QString(" (") + langStr + QString(")"), QVariant(langStr));
#else
/** display language strings as "language - country (locale name)", e.g. "German - Germany (de)" */
ui->lang->addItem(QLocale::languageToString(locale.language()) + QString(" - ") + QLocale::countryToString(locale.country()) + QString(" (") + langStr + QString(")"), QVariant(langStr));
#endif
} else {
#if QT_VERSION >= 0x040800
/** display language strings as "native language (locale name)", e.g. "Deutsch (de)" */
ui->lang->addItem(locale.nativeLanguageName() + QString(" (") + langStr + QString(")"), QVariant(langStr));
#else
/** display language strings as "language (locale name)", e.g. "German (de)" */
ui->lang->addItem(QLocale::languageToString(locale.language()) + QString(" (") + langStr + QString(")"), QVariant(langStr));
#endif
}
}
#if QT_VERSION >= 0x040700
ui->thirdPartyTxUrls->setPlaceholderText("https://example.com/tx/%s");
#endif
ui->unit->setModel(new BitcoinUnits(this));
/* Widget-to-option mapper */
mapper = new QDataWidgetMapper(this);
mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit);
mapper->setOrientation(Qt::Vertical);
/* setup/change UI elements when proxy IP is invalid/valid */
connect(this, SIGNAL(proxyIpChecks(QValidatedLineEdit*, int)), this, SLOT(doProxyIpChecks(QValidatedLineEdit*, int)));
}
OptionsDialog::~OptionsDialog()
{
GUIUtil::saveWindowGeometry("nOptionsDialogWindow", this);
delete ui;
}
void OptionsDialog::setModel(OptionsModel* model)
{
this->model = model;
if (model) {
/* check if client restart is needed and show persistent message */
if (model->isRestartRequired())
showRestartWarning(true);
QString strLabel = model->getOverriddenByCommandLine();
if (strLabel.isEmpty())
strLabel = tr("none");
ui->overriddenByCommandLineLabel->setText(strLabel);
mapper->setModel(model);
setMapper();
mapper->toFirst();
}
/* warn when one of the following settings changes by user action (placed here so init via mapper doesn't trigger them) */
/* Main */
connect(ui->databaseCache, SIGNAL(valueChanged(int)), this, SLOT(showRestartWarning()));
connect(ui->threadsScriptVerif, SIGNAL(valueChanged(int)), this, SLOT(showRestartWarning()));
/* Wallet */
connect(ui->spendZeroConfChange, SIGNAL(clicked(bool)), this, SLOT(showRestartWarning()));
/* Network */
connect(ui->allowIncoming, SIGNAL(clicked(bool)), this, SLOT(showRestartWarning()));
connect(ui->connectSocks, SIGNAL(clicked(bool)), this, SLOT(showRestartWarning()));
/* Display */
connect(ui->digits, SIGNAL(valueChanged()), this, SLOT(showRestartWarning()));
connect(ui->theme, SIGNAL(valueChanged()), this, SLOT(showRestartWarning()));
connect(ui->lang, SIGNAL(valueChanged()), this, SLOT(showRestartWarning()));
connect(ui->thirdPartyTxUrls, SIGNAL(textChanged(const QString&)), this, SLOT(showRestartWarning()));
connect(ui->showMasternodesTab, SIGNAL(clicked(bool)), this, SLOT(showRestartWarning()));
}
void OptionsDialog::setMapper()
{
/* Main */
mapper->addMapping(ui->bitcoinAtStartup, OptionsModel::StartAtStartup);
mapper->addMapping(ui->threadsScriptVerif, OptionsModel::ThreadsScriptVerif);
mapper->addMapping(ui->databaseCache, OptionsModel::DatabaseCache);
// Zerocoin mint percentage
mapper->addMapping(ui->zeromintPercentage, OptionsModel::ZeromintPercentage);
// Zerocoin preferred denomination
mapper->addMapping(ui->preferredDenom, OptionsModel::ZeromintPrefDenom);
/* Wallet */
mapper->addMapping(ui->spendZeroConfChange, OptionsModel::SpendZeroConfChange);
mapper->addMapping(ui->coinControlFeatures, OptionsModel::CoinControlFeatures);
/* Network */
mapper->addMapping(ui->mapPortUpnp, OptionsModel::MapPortUPnP);
mapper->addMapping(ui->allowIncoming, OptionsModel::Listen);
mapper->addMapping(ui->connectSocks, OptionsModel::ProxyUse);
mapper->addMapping(ui->proxyIp, OptionsModel::ProxyIP);
mapper->addMapping(ui->proxyPort, OptionsModel::ProxyPort);
/* Window */
#ifndef Q_OS_MAC
mapper->addMapping(ui->minimizeToTray, OptionsModel::MinimizeToTray);
mapper->addMapping(ui->minimizeOnClose, OptionsModel::MinimizeOnClose);
#endif
/* Display */
mapper->addMapping(ui->digits, OptionsModel::Digits);
mapper->addMapping(ui->theme, OptionsModel::Theme);
mapper->addMapping(ui->theme, OptionsModel::Theme);
mapper->addMapping(ui->lang, OptionsModel::Language);
mapper->addMapping(ui->unit, OptionsModel::DisplayUnit);
mapper->addMapping(ui->thirdPartyTxUrls, OptionsModel::ThirdPartyTxUrls);
/* Masternode Tab */
mapper->addMapping(ui->showMasternodesTab, OptionsModel::ShowMasternodesTab);
}
void OptionsDialog::enableOkButton()
{
/* prevent enabling of the OK button when data modified, if there is an invalid proxy address present */
if (fProxyIpValid)
setOkButtonState(true);
}
void OptionsDialog::disableOkButton()
{
setOkButtonState(false);
}
void OptionsDialog::setOkButtonState(bool fState)
{
ui->okButton->setEnabled(fState);
}
void OptionsDialog::on_resetButton_clicked()
{
if (model) {
// confirmation dialog
QMessageBox::StandardButton btnRetVal = QMessageBox::question(this, tr("Confirm options reset"),
tr("Client restart required to activate changes.") + "<br><br>" + tr("Client will be shutdown, do you want to proceed?"),
QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Cancel);
if (btnRetVal == QMessageBox::Cancel)
return;
/* reset all options and close GUI */
model->Reset();
QApplication::quit();
}
}
void OptionsDialog::on_okButton_clicked()
{
mapper->submit();
obfuScationPool.cachedNumBlocks = std::numeric_limits<int>::max();
pwalletMain->MarkDirty();
accept();
}
void OptionsDialog::on_cancelButton_clicked()
{
reject();
}
void OptionsDialog::showRestartWarning(bool fPersistent)
{
ui->statusLabel->setStyleSheet("QLabel { color: red; }");
if (fPersistent) {
ui->statusLabel->setText(tr("Client restart required to activate changes."));
} else {
ui->statusLabel->setText(tr("This change would require a client restart."));
// clear non-persistent status label after 10 seconds
// Todo: should perhaps be a class attribute, if we extend the use of statusLabel
QTimer::singleShot(10000, this, SLOT(clearStatusLabel()));
}
}
void OptionsDialog::clearStatusLabel()
{
ui->statusLabel->clear();
}
void OptionsDialog::doProxyIpChecks(QValidatedLineEdit* pUiProxyIp, int nProxyPort)
{
Q_UNUSED(nProxyPort);
const std::string strAddrProxy = pUiProxyIp->text().toStdString();
CService addrProxy;
/* Check for a valid IPv4 / IPv6 address */
if (!(fProxyIpValid = LookupNumeric(strAddrProxy.c_str(), addrProxy))) {
disableOkButton();
pUiProxyIp->setValid(false);
ui->statusLabel->setStyleSheet("QLabel { color: red; }");
ui->statusLabel->setText(tr("The supplied proxy address is invalid."));
} else {
enableOkButton();
ui->statusLabel->clear();
}
}
bool OptionsDialog::eventFilter(QObject* object, QEvent* event)
{
if (event->type() == QEvent::FocusOut) {
if (object == ui->proxyIp) {
emit proxyIpChecks(ui->proxyIp, ui->proxyPort->text().toInt());
}
}
return QDialog::eventFilter(object, event);
}
<|endoftext|>
|
<commit_before>#include <qt/splitutxopage.h>
#include <qt/forms/ui_splitutxopage.h>
#include <qt/bitcoinunits.h>
#include <qt/execrpccommand.h>
#include <qt/guiutil.h>
#include <qt/optionsmodel.h>
#include <qt/sendcoinsdialog.h>
#include <qt/walletmodel.h>
#include <validation.h>
namespace SplitUTXO_NS
{
static const QString PRC_COMMAND = "splitutxosforaddress";
static const QString PARAM_ADDRESS = "address";
static const QString PARAM_MIN_VALUE = "minValue";
static const QString PARAM_MAX_VALUE = "maxValue";
static const QString PARAM_MAX_OUTPUTS = "maxOutputs";
}
using namespace SplitUTXO_NS;
SplitUTXOPage::SplitUTXOPage(QWidget *parent, Mode mode) :
QDialog(parent),
ui(new Ui::SplitUTXOPage),
m_model(nullptr),
m_mode(mode)
{
ui->setupUi(this);
switch (m_mode) {
case Normal:
setWindowTitle(tr("Split coins for address"));
ui->labelAddress->setText(tr("Address"));
break;
case Delegation:
setWindowTitle(tr("Split coins for offline staking"));
ui->labelAddress->setText(tr("Delegate address"));
ui->labelDescription->setText(tr("Split coins for offline staking. The UTXO value need to be minimum <b> %1 </b>.").
arg(BitcoinUnits::formatHtmlWithUnit(BitcoinUnits::BTC, DEFAULT_STAKING_MIN_UTXO_VALUE)));
break;
case SuperStaker:
setWindowTitle(tr("Split coins for super staker"));
ui->labelAddress->setText(tr("Staker address"));
ui->labelDescription->setText(tr("Split coins for super staker. The UTXO value need to be minimum <b> %1 </b>.").
arg(BitcoinUnits::formatHtmlWithUnit(BitcoinUnits::BTC, DEFAULT_STAKING_MIN_UTXO_VALUE)));
break;
}
ui->labelAddress->setToolTip(tr("The qtum address to split utxos."));
ui->labelMinValue->setToolTip(tr("Select utxo which value is smaller than value (minimum 0.1 COIN)."));
ui->labelMaxValue->setToolTip(tr("Select utxo which value is greater than value (minimum 0.1 COIN)."));
ui->labelMaxOutputs->setToolTip(tr("Maximum outputs to create"));
ui->lineEditAddress->setSenderAddress(true);
ui->txtAddress->setReadOnly(true);
ui->txtAddress->setVisible(false);
QFont font = QApplication::font();
font.setPointSizeF(font.pointSizeF() * 0.8);
ui->labelDescription->setFont(font);
// Set defaults
ui->lineEditMinValue->setValue(DEFAULT_STAKING_MIN_UTXO_VALUE);
ui->lineEditMaxValue->setValue(DEFAULT_STAKING_MIN_UTXO_VALUE * 2);
ui->spinBoxMaxOutputs->setMinimum(1);
ui->spinBoxMaxOutputs->setMaximum(10000);
ui->spinBoxMaxOutputs->setValue(100);
ui->splitCoinsButton->setEnabled(false);
// Create new PRC command line interface
QStringList lstMandatory;
lstMandatory.append(PARAM_ADDRESS);
lstMandatory.append(PARAM_MIN_VALUE);
lstMandatory.append(PARAM_MAX_VALUE);
QStringList lstOptional;
lstOptional.append(PARAM_MAX_OUTPUTS);
QMap<QString, QString> lstTranslations;
lstTranslations[PARAM_ADDRESS] = ui->labelAddress->text();
lstTranslations[PARAM_MIN_VALUE] = ui->labelMinValue->text();
lstTranslations[PARAM_MAX_VALUE] = ui->labelMaxValue->text();
lstTranslations[PARAM_MAX_OUTPUTS] = ui->labelMaxOutputs->text();
m_execRPCCommand = new ExecRPCCommand(PRC_COMMAND, lstMandatory, lstOptional, lstTranslations, this);
connect(ui->splitCoinsButton, &QPushButton::clicked, this, &SplitUTXOPage::on_splitCoinsClicked);
connect(ui->cancelButton, &QPushButton::clicked, this, &SplitUTXOPage::on_cancelButtonClicked);
connect(ui->lineEditAddress, &QComboBox::currentTextChanged, this, &SplitUTXOPage::on_updateSplitCoinsButton);
}
SplitUTXOPage::~SplitUTXOPage()
{
delete ui;
}
void SplitUTXOPage::setModel(WalletModel *_model)
{
m_model = _model;
ui->lineEditAddress->setWalletModel(m_model);
if (m_model && m_model->getOptionsModel())
connect(m_model->getOptionsModel(), &OptionsModel::displayUnitChanged, this, &SplitUTXOPage::updateDisplayUnit);
// update the display unit, to not use the default ("QTUM")
updateDisplayUnit();
}
void SplitUTXOPage::setAddress(const QString &address)
{
ui->lineEditAddress->setVisible(false);
ui->txtAddress->setVisible(true);
ui->txtAddress->setText(address);
if(m_mode == Normal)
setWindowTitle(tr("Split coins for address %1").arg(address));
ui->splitCoinsButton->setEnabled(true);
}
bool SplitUTXOPage::isDataValid()
{
bool dataValid = true;
ui->lineEditMinValue->setValid(true);
ui->lineEditMaxValue->setValid(true);
CAmount minValue = ui->lineEditMinValue->value();
CAmount maxValue = ui->lineEditMaxValue->value();
if(ui->lineEditAddress->isVisible() && !ui->lineEditAddress->isValidAddress())
dataValid = false;
if(minValue < COIN/10)
{
ui->lineEditMinValue->setValid(false);
dataValid = false;
}
if(maxValue < COIN/10)
{
ui->lineEditMaxValue->setValid(false);
dataValid = false;
}
if(minValue > COIN/10 && maxValue > COIN/10 && minValue > maxValue)
{
ui->lineEditMinValue->setValid(false);
ui->lineEditMaxValue->setValid(false);
dataValid = false;
}
return dataValid;
}
void SplitUTXOPage::clearAll()
{
if(ui->lineEditAddress->isVisible())
{
ui->lineEditAddress->setCurrentIndex(-1);
ui->splitCoinsButton->setEnabled(false);
}
ui->lineEditMinValue->setValue(DEFAULT_STAKING_MIN_UTXO_VALUE);
ui->lineEditMaxValue->setValue(DEFAULT_STAKING_MIN_UTXO_VALUE * 2);
ui->spinBoxMaxOutputs->setValue(100);
}
void SplitUTXOPage::accept()
{
clearAll();
QDialog::accept();
}
void SplitUTXOPage::reject()
{
clearAll();
QDialog::reject();
}
void SplitUTXOPage::updateDisplayUnit()
{
if(m_model && m_model->getOptionsModel())
{
// Update min and max value with the current unit
ui->lineEditMinValue->setDisplayUnit(m_model->getOptionsModel()->getDisplayUnit());
ui->lineEditMaxValue->setDisplayUnit(m_model->getOptionsModel()->getDisplayUnit());
}
}
void SplitUTXOPage::on_splitCoinsClicked()
{
if(m_model && m_model->getOptionsModel())
{
if(!isDataValid())
return;
// Initialize variables
QMap<QString, QString> lstParams;
QVariant result;
QString errorMessage;
QString resultJson;
int unit = BitcoinUnits::BTC;
QString address = ui->lineEditAddress->isVisible() ? ui->lineEditAddress->currentText() : ui->txtAddress->text();
CAmount minValue = ui->lineEditMinValue->value();
CAmount maxValue = ui->lineEditMaxValue->value();
CAmount maxOutputs = ui->spinBoxMaxOutputs->value();
// Append params to the list
ExecRPCCommand::appendParam(lstParams, PARAM_ADDRESS, address);
ExecRPCCommand::appendParam(lstParams, PARAM_MIN_VALUE, BitcoinUnits::format(unit, minValue, false, BitcoinUnits::separatorNever));
ExecRPCCommand::appendParam(lstParams, PARAM_MAX_VALUE, BitcoinUnits::format(unit, maxValue, false, BitcoinUnits::separatorNever));
ExecRPCCommand::appendParam(lstParams, PARAM_MAX_OUTPUTS, QString::number(maxOutputs));
QString questionString = tr("Are you sure you want to split coins for address");
questionString.append(QString("<br/><br/><b>%1</b>?")
.arg(address));
SendConfirmationDialog confirmationDialog(tr("Confirm splitting coins for address."), questionString, "", "", SEND_CONFIRM_DELAY, this);
confirmationDialog.exec();
QMessageBox::StandardButton retval = (QMessageBox::StandardButton)confirmationDialog.result();
if(retval == QMessageBox::Yes)
{
if(!m_execRPCCommand->exec(m_model->node(), m_model, lstParams, result, resultJson, errorMessage))
{
QMessageBox::warning(this, tr("Split coins for address"), errorMessage);
}
else
{
QVariantMap variantMap = result.toMap();
QString selectedString = variantMap.value("selected").toString();
CAmount selected;
BitcoinUnits::parse(unit, selectedString, &selected);
QString splitedString = variantMap.value("splited").toString();
CAmount splited;
BitcoinUnits::parse(unit, splitedString, &splited);
int displayUnit = m_model->getOptionsModel()->getDisplayUnit();
QString infoString = tr("Selected: %1 less than %2 and above of %3.").
arg(BitcoinUnits::formatHtmlWithUnit(displayUnit, selected)).
arg(BitcoinUnits::formatHtmlWithUnit(displayUnit, minValue)).
arg(BitcoinUnits::formatHtmlWithUnit(displayUnit, maxValue));
infoString.append("<br/><br/>");
infoString.append(tr("Splitted: %1.").arg(BitcoinUnits::formatHtmlWithUnit(displayUnit, splited)));
QMessageBox::information(this, tr("Split coins for address"), infoString);
if(splited == selected || splited == 0)
accept();
}
}
}
}
void SplitUTXOPage::on_cancelButtonClicked()
{
reject();
}
void SplitUTXOPage::on_updateSplitCoinsButton()
{
bool enabled = true;
bool validAddress = !ui->lineEditAddress->isVisible() || (ui->lineEditAddress->isVisible() && !ui->lineEditAddress->currentText().isEmpty());
if(!validAddress)
{
enabled = false;
}
ui->splitCoinsButton->setEnabled(enabled);
}
<commit_msg>Update message for split the delegated coins for offline stake<commit_after>#include <qt/splitutxopage.h>
#include <qt/forms/ui_splitutxopage.h>
#include <qt/bitcoinunits.h>
#include <qt/execrpccommand.h>
#include <qt/guiutil.h>
#include <qt/optionsmodel.h>
#include <qt/sendcoinsdialog.h>
#include <qt/walletmodel.h>
#include <validation.h>
namespace SplitUTXO_NS
{
static const QString PRC_COMMAND = "splitutxosforaddress";
static const QString PARAM_ADDRESS = "address";
static const QString PARAM_MIN_VALUE = "minValue";
static const QString PARAM_MAX_VALUE = "maxValue";
static const QString PARAM_MAX_OUTPUTS = "maxOutputs";
}
using namespace SplitUTXO_NS;
SplitUTXOPage::SplitUTXOPage(QWidget *parent, Mode mode) :
QDialog(parent),
ui(new Ui::SplitUTXOPage),
m_model(nullptr),
m_mode(mode)
{
ui->setupUi(this);
switch (m_mode) {
case Normal:
setWindowTitle(tr("Split coins for address"));
ui->labelAddress->setText(tr("Address"));
break;
case Delegation:
setWindowTitle(tr("Split coins for offline staking"));
ui->labelAddress->setText(tr("Delegate address"));
ui->labelDescription->setText(tr("Split coins for offline staking."));
break;
case SuperStaker:
setWindowTitle(tr("Split coins for super staker"));
ui->labelAddress->setText(tr("Staker address"));
ui->labelDescription->setText(tr("Split coins for super staker. The UTXO value need to be minimum <b> %1 </b>.").
arg(BitcoinUnits::formatHtmlWithUnit(BitcoinUnits::BTC, DEFAULT_STAKING_MIN_UTXO_VALUE)));
break;
}
ui->labelAddress->setToolTip(tr("The qtum address to split utxos."));
ui->labelMinValue->setToolTip(tr("Select utxo which value is smaller than value (minimum 0.1 COIN)."));
ui->labelMaxValue->setToolTip(tr("Select utxo which value is greater than value (minimum 0.1 COIN)."));
ui->labelMaxOutputs->setToolTip(tr("Maximum outputs to create"));
ui->lineEditAddress->setSenderAddress(true);
ui->txtAddress->setReadOnly(true);
ui->txtAddress->setVisible(false);
QFont font = QApplication::font();
font.setPointSizeF(font.pointSizeF() * 0.8);
ui->labelDescription->setFont(font);
// Set defaults
ui->lineEditMinValue->setValue(DEFAULT_STAKING_MIN_UTXO_VALUE);
ui->lineEditMaxValue->setValue(DEFAULT_STAKING_MIN_UTXO_VALUE * 2);
ui->spinBoxMaxOutputs->setMinimum(1);
ui->spinBoxMaxOutputs->setMaximum(10000);
ui->spinBoxMaxOutputs->setValue(100);
ui->splitCoinsButton->setEnabled(false);
// Create new PRC command line interface
QStringList lstMandatory;
lstMandatory.append(PARAM_ADDRESS);
lstMandatory.append(PARAM_MIN_VALUE);
lstMandatory.append(PARAM_MAX_VALUE);
QStringList lstOptional;
lstOptional.append(PARAM_MAX_OUTPUTS);
QMap<QString, QString> lstTranslations;
lstTranslations[PARAM_ADDRESS] = ui->labelAddress->text();
lstTranslations[PARAM_MIN_VALUE] = ui->labelMinValue->text();
lstTranslations[PARAM_MAX_VALUE] = ui->labelMaxValue->text();
lstTranslations[PARAM_MAX_OUTPUTS] = ui->labelMaxOutputs->text();
m_execRPCCommand = new ExecRPCCommand(PRC_COMMAND, lstMandatory, lstOptional, lstTranslations, this);
connect(ui->splitCoinsButton, &QPushButton::clicked, this, &SplitUTXOPage::on_splitCoinsClicked);
connect(ui->cancelButton, &QPushButton::clicked, this, &SplitUTXOPage::on_cancelButtonClicked);
connect(ui->lineEditAddress, &QComboBox::currentTextChanged, this, &SplitUTXOPage::on_updateSplitCoinsButton);
}
SplitUTXOPage::~SplitUTXOPage()
{
delete ui;
}
void SplitUTXOPage::setModel(WalletModel *_model)
{
m_model = _model;
ui->lineEditAddress->setWalletModel(m_model);
if (m_model && m_model->getOptionsModel())
connect(m_model->getOptionsModel(), &OptionsModel::displayUnitChanged, this, &SplitUTXOPage::updateDisplayUnit);
// update the display unit, to not use the default ("QTUM")
updateDisplayUnit();
}
void SplitUTXOPage::setAddress(const QString &address)
{
ui->lineEditAddress->setVisible(false);
ui->txtAddress->setVisible(true);
ui->txtAddress->setText(address);
if(m_mode == Normal)
setWindowTitle(tr("Split coins for address %1").arg(address));
ui->splitCoinsButton->setEnabled(true);
}
bool SplitUTXOPage::isDataValid()
{
bool dataValid = true;
ui->lineEditMinValue->setValid(true);
ui->lineEditMaxValue->setValid(true);
CAmount minValue = ui->lineEditMinValue->value();
CAmount maxValue = ui->lineEditMaxValue->value();
if(ui->lineEditAddress->isVisible() && !ui->lineEditAddress->isValidAddress())
dataValid = false;
if(minValue < COIN/10)
{
ui->lineEditMinValue->setValid(false);
dataValid = false;
}
if(maxValue < COIN/10)
{
ui->lineEditMaxValue->setValid(false);
dataValid = false;
}
if(minValue > COIN/10 && maxValue > COIN/10 && minValue > maxValue)
{
ui->lineEditMinValue->setValid(false);
ui->lineEditMaxValue->setValid(false);
dataValid = false;
}
return dataValid;
}
void SplitUTXOPage::clearAll()
{
if(ui->lineEditAddress->isVisible())
{
ui->lineEditAddress->setCurrentIndex(-1);
ui->splitCoinsButton->setEnabled(false);
}
ui->lineEditMinValue->setValue(DEFAULT_STAKING_MIN_UTXO_VALUE);
ui->lineEditMaxValue->setValue(DEFAULT_STAKING_MIN_UTXO_VALUE * 2);
ui->spinBoxMaxOutputs->setValue(100);
}
void SplitUTXOPage::accept()
{
clearAll();
QDialog::accept();
}
void SplitUTXOPage::reject()
{
clearAll();
QDialog::reject();
}
void SplitUTXOPage::updateDisplayUnit()
{
if(m_model && m_model->getOptionsModel())
{
// Update min and max value with the current unit
ui->lineEditMinValue->setDisplayUnit(m_model->getOptionsModel()->getDisplayUnit());
ui->lineEditMaxValue->setDisplayUnit(m_model->getOptionsModel()->getDisplayUnit());
}
}
void SplitUTXOPage::on_splitCoinsClicked()
{
if(m_model && m_model->getOptionsModel())
{
if(!isDataValid())
return;
// Initialize variables
QMap<QString, QString> lstParams;
QVariant result;
QString errorMessage;
QString resultJson;
int unit = BitcoinUnits::BTC;
QString address = ui->lineEditAddress->isVisible() ? ui->lineEditAddress->currentText() : ui->txtAddress->text();
CAmount minValue = ui->lineEditMinValue->value();
CAmount maxValue = ui->lineEditMaxValue->value();
CAmount maxOutputs = ui->spinBoxMaxOutputs->value();
// Append params to the list
ExecRPCCommand::appendParam(lstParams, PARAM_ADDRESS, address);
ExecRPCCommand::appendParam(lstParams, PARAM_MIN_VALUE, BitcoinUnits::format(unit, minValue, false, BitcoinUnits::separatorNever));
ExecRPCCommand::appendParam(lstParams, PARAM_MAX_VALUE, BitcoinUnits::format(unit, maxValue, false, BitcoinUnits::separatorNever));
ExecRPCCommand::appendParam(lstParams, PARAM_MAX_OUTPUTS, QString::number(maxOutputs));
QString questionString = tr("Are you sure you want to split coins for address");
questionString.append(QString("<br/><br/><b>%1</b>?")
.arg(address));
SendConfirmationDialog confirmationDialog(tr("Confirm splitting coins for address."), questionString, "", "", SEND_CONFIRM_DELAY, this);
confirmationDialog.exec();
QMessageBox::StandardButton retval = (QMessageBox::StandardButton)confirmationDialog.result();
if(retval == QMessageBox::Yes)
{
if(!m_execRPCCommand->exec(m_model->node(), m_model, lstParams, result, resultJson, errorMessage))
{
QMessageBox::warning(this, tr("Split coins for address"), errorMessage);
}
else
{
QVariantMap variantMap = result.toMap();
QString selectedString = variantMap.value("selected").toString();
CAmount selected;
BitcoinUnits::parse(unit, selectedString, &selected);
QString splitedString = variantMap.value("splited").toString();
CAmount splited;
BitcoinUnits::parse(unit, splitedString, &splited);
int displayUnit = m_model->getOptionsModel()->getDisplayUnit();
QString infoString = tr("Selected: %1 less than %2 and above of %3.").
arg(BitcoinUnits::formatHtmlWithUnit(displayUnit, selected)).
arg(BitcoinUnits::formatHtmlWithUnit(displayUnit, minValue)).
arg(BitcoinUnits::formatHtmlWithUnit(displayUnit, maxValue));
infoString.append("<br/><br/>");
infoString.append(tr("Splitted: %1.").arg(BitcoinUnits::formatHtmlWithUnit(displayUnit, splited)));
QMessageBox::information(this, tr("Split coins for address"), infoString);
if(splited == selected || splited == 0)
accept();
}
}
}
}
void SplitUTXOPage::on_cancelButtonClicked()
{
reject();
}
void SplitUTXOPage::on_updateSplitCoinsButton()
{
bool enabled = true;
bool validAddress = !ui->lineEditAddress->isVisible() || (ui->lineEditAddress->isVisible() && !ui->lineEditAddress->currentText().isEmpty());
if(!validAddress)
{
enabled = false;
}
ui->splitCoinsButton->setEnabled(enabled);
}
<|endoftext|>
|
<commit_before>
#include <functional>
#include <string>
#include "google/protobuf/stubs/common.h"
#include "glog/logging.h"
#include "gtest/gtest.h"
#include "quantities/astronomy.hpp"
#include "quantities/bipm.hpp"
#include "quantities/constants.hpp"
#include "quantities/elementary_functions.hpp"
#include "quantities/quantities.hpp"
#include "quantities/si.hpp"
#include "quantities/uk.hpp"
#include "testing_utilities/almost_equals.hpp"
#include "testing_utilities/numerics.hpp"
#include "testing_utilities/vanishes_before.hpp"
namespace principia {
namespace quantities {
using astronomy::AstronomicalUnit;
using astronomy::JulianYear;
using astronomy::LightYear;
using astronomy::Parsec;
using astronomy::JovianGravitationalParameter;
using astronomy::SolarGravitationalParameter;
using astronomy::TerrestrialGravitationalParameter;
using constants::GravitationalConstant;
using constants::SpeedOfLight;
using constants::StandardGravity;
using constants::VacuumPermeability;
using constants::VacuumPermittivity;
using si::Ampere;
using si::Coulomb;
using si::Day;
using si::Degree;
using si::Kilo;
using si::Kilogram;
using si::Mega;
using si::Metre;
using si::Mole;
using si::Radian;
using si::Second;
using testing_utilities::AlmostEquals;
using testing_utilities::RelativeError;
using testing_utilities::VanishesBefore;
using uk::Foot;
using uk::Gallon;
using uk::Rood;
using ::testing::Eq;
using ::testing::Lt;
class ElementaryFunctionsTest : public testing::Test {};
TEST_F(ElementaryFunctionsTest, FMA) {
EXPECT_EQ(11 * Coulomb,
FusedMultiplyAdd(2 * Ampere, 3 * Second, 5 * Coulomb));
EXPECT_EQ(11 * Radian, FusedMultiplyAdd(2.0, 3 * Radian, 5 * Radian));
EXPECT_EQ(11.0, FusedMultiplyAdd(2.0, 3.0, 5.0));
}
TEST_F(ElementaryFunctionsTest, AbsoluteValue) {
EXPECT_EQ(Abs(-1729), 1729);
EXPECT_EQ(Abs(1729), 1729);
EXPECT_EQ(Abs(-1729 * Metre), 1729 * Metre);
}
TEST_F(ElementaryFunctionsTest, DimensionlessExponentiation) {
double const number = π - 42;
double positivePower = 1;
double negativePower = 1;
EXPECT_EQ(positivePower, Pow<0>(number));
positivePower *= number;
negativePower /= number;
EXPECT_EQ(positivePower, Pow<1>(number));
EXPECT_EQ(negativePower, Pow<-1>(number));
positivePower *= number;
negativePower /= number;
EXPECT_EQ(positivePower, Pow<2>(number));
EXPECT_EQ(negativePower, Pow<-2>(number));
positivePower *= number;
negativePower /= number;
EXPECT_EQ(positivePower, Pow<3>(number));
EXPECT_EQ(negativePower, Pow<-3>(number));
positivePower *= number;
negativePower /= number;
// This one calls |std::pow|.
EXPECT_THAT(positivePower, AlmostEquals(Pow<4>(number), 0, 1));
EXPECT_THAT(negativePower, AlmostEquals(Pow<-4>(number), 0, 1));
}
// The Greek letters cause a warning when stringified by the macros, because
// apparently Visual Studio doesn't encode strings in UTF-8 by default.
#pragma warning(disable: 4566)
TEST_F(ElementaryFunctionsTest, PhysicalConstants) {
Length const lunar_distance = 384402 * Kilo(Metre);
// By definition.
EXPECT_THAT(1 / Pow<2>(SpeedOfLight),
AlmostEquals(VacuumPermittivity * VacuumPermeability, 1));
// The Keplerian approximation for the mass of the Sun
// is fairly accurate.
EXPECT_THAT(RelativeError(
4 * Pow<2>(π) * Pow<3>(AstronomicalUnit) / Pow<2>(JulianYear),
SolarGravitationalParameter),
Lt(4e-5));
EXPECT_THAT(RelativeError(1 * Parsec, 3.26156 * LightYear), Lt(2e-6));
// The Keplerian approximation for the mass of the Earth
// is pretty bad, but the error is still only 1%.
EXPECT_THAT(RelativeError(4 * Pow<2>(π) * Pow<3>(lunar_distance) /
Pow<2>(27.321582 * Day),
TerrestrialGravitationalParameter),
Lt(1e-2));
EXPECT_THAT(RelativeError(1 * SolarGravitationalParameter,
1047 * JovianGravitationalParameter),
Lt(6e-4));
// Delambre & Méchain.
EXPECT_THAT(RelativeError(TerrestrialGravitationalParameter /
Pow<2>(40 * Mega(Metre) / (2 * π)),
StandardGravity),
Lt(4e-3));
// Talleyrand.
EXPECT_THAT(RelativeError(π * Sqrt(1 * Metre / StandardGravity), 1 * Second),
Lt(4e-3));
}
#pragma warning(default: 4566)
TEST_F(ElementaryFunctionsTest, TrigonometricFunctions) {
EXPECT_EQ(Cos(0 * Degree), 1);
EXPECT_EQ(Sin(0 * Degree), 0);
EXPECT_THAT(Cos(90 * Degree), VanishesBefore(1.0, 0));
EXPECT_EQ(Sin(90 * Degree), 1);
EXPECT_EQ(Cos(180 * Degree), -1);
EXPECT_THAT(Sin(180 * Degree), VanishesBefore(1.0, 1));
EXPECT_THAT(Cos(-90 * Degree), VanishesBefore(1.0, 0));
EXPECT_EQ(Sin(-90 * Degree), -1);
for (int k = 1; k < 360; ++k) {
// Don't test for multiples of 90 degrees as zeros lead to horrible
// conditioning.
if (k % 90 != 0) {
EXPECT_THAT(Cos((90 - k) * Degree),
AlmostEquals(Sin(k * Degree), 0, 47));
EXPECT_THAT(Sin(k * Degree) / Cos(k * Degree),
AlmostEquals(Tan(k * Degree), 0, 2));
EXPECT_THAT(((k + 179) % 360 - 179) * Degree,
AlmostEquals(ArcTan(Sin(k * Degree), Cos(k * Degree)),
0, 77));
EXPECT_THAT(((k + 179) % 360 - 179) * Degree,
AlmostEquals(ArcTan(Sin(k * Degree) * AstronomicalUnit,
Cos(k * Degree) * AstronomicalUnit),
0, 77));
EXPECT_THAT(Cos(ArcCos(Cos(k * Degree))),
AlmostEquals(Cos(k * Degree), 0, 7));
EXPECT_THAT(Sin(ArcSin(Sin(k * Degree))),
AlmostEquals(Sin(k * Degree), 0, 1));
}
}
// Horribly conditioned near 0, so not in the loop above.
EXPECT_EQ(Tan(ArcTan(Tan(-42 * Degree))), Tan(-42 * Degree));
}
TEST_F(ElementaryFunctionsTest, HyperbolicFunctions) {
EXPECT_EQ(Sinh(0 * Radian), 0);
EXPECT_EQ(Cosh(0 * Radian), 1);
EXPECT_EQ(Tanh(0 * Radian), 0);
// Limits:
EXPECT_EQ(Sinh(20 * Radian), Cosh(20 * Radian));
EXPECT_EQ(Tanh(20 * Radian), 1);
EXPECT_EQ(Sinh(-20 * Radian), -Cosh(-20 * Radian));
EXPECT_EQ(Tanh(-20 * Radian), -1);
EXPECT_THAT(Sinh(2 * Radian) / Cosh(2 * Radian),
AlmostEquals(Tanh(2 * Radian), 0, 1));
EXPECT_THAT(ArcSinh(Sinh(-10 * Degree)),
AlmostEquals(-10 * Degree, 0, 1));
EXPECT_THAT(ArcCosh(Cosh(-10 * Degree)),
AlmostEquals(10 * Degree, 19, 20));
EXPECT_THAT(ArcTanh(Tanh(-10 * Degree)),
AlmostEquals(-10 * Degree, 0, 1));
}
TEST_F(ElementaryFunctionsTest, ExpLogAndRoots) {
// The ULP distance is 1 if everything is correctly rounded.
EXPECT_THAT(std::exp(std::log(2) / 2), AlmostEquals(Sqrt(2), 1));
// The ULP distance is 0 if everything is correctly rounded.
EXPECT_THAT(std::exp(std::log(2) / 3), AlmostEquals(Cbrt(2), 0));
EXPECT_THAT(
Sqrt(Rood),
AlmostEquals(std::exp(std::log(Rood / Pow<2>(Foot)) / 2) * Foot, 0));
EXPECT_THAT(
Cbrt(Gallon),
AlmostEquals(std::exp(std::log(Gallon / Pow<3>(Foot)) / 3) * Foot, 0, 1));
}
} // namespace quantities
} // namespace principia
<commit_msg>missed a test<commit_after>
#include <functional>
#include <string>
#include "google/protobuf/stubs/common.h"
#include "glog/logging.h"
#include "gtest/gtest.h"
#include "quantities/astronomy.hpp"
#include "quantities/bipm.hpp"
#include "quantities/constants.hpp"
#include "quantities/elementary_functions.hpp"
#include "quantities/quantities.hpp"
#include "quantities/si.hpp"
#include "quantities/uk.hpp"
#include "testing_utilities/almost_equals.hpp"
#include "testing_utilities/numerics.hpp"
#include "testing_utilities/vanishes_before.hpp"
namespace principia {
namespace quantities {
using astronomy::AstronomicalUnit;
using astronomy::JulianYear;
using astronomy::LightYear;
using astronomy::Parsec;
using astronomy::JovianGravitationalParameter;
using astronomy::SolarGravitationalParameter;
using astronomy::TerrestrialGravitationalParameter;
using base::CPUFeatureFlags;
using base::HasCPUFeatures;
using constants::GravitationalConstant;
using constants::SpeedOfLight;
using constants::StandardGravity;
using constants::VacuumPermeability;
using constants::VacuumPermittivity;
using numerics::CanEmitFMAInstructions;
using si::Ampere;
using si::Coulomb;
using si::Day;
using si::Degree;
using si::Kilo;
using si::Kilogram;
using si::Mega;
using si::Metre;
using si::Mole;
using si::Radian;
using si::Second;
using testing_utilities::AlmostEquals;
using testing_utilities::RelativeError;
using testing_utilities::VanishesBefore;
using uk::Foot;
using uk::Gallon;
using uk::Rood;
using ::testing::Eq;
using ::testing::Lt;
class ElementaryFunctionsTest : public testing::Test {};
TEST_F(ElementaryFunctionsTest, FMA) {
if (!CanEmitFMAInstructions || !HasCPUFeatures(CPUFeatureFlags::FMA)) {
LOG(ERROR) << "Cannot test FMA on a machine without FMA";
return;
}
EXPECT_EQ(11 * Coulomb,
FusedMultiplyAdd(2 * Ampere, 3 * Second, 5 * Coulomb));
EXPECT_EQ(11 * Radian, FusedMultiplyAdd(2.0, 3 * Radian, 5 * Radian));
EXPECT_EQ(11.0, FusedMultiplyAdd(2.0, 3.0, 5.0));
}
TEST_F(ElementaryFunctionsTest, AbsoluteValue) {
EXPECT_EQ(Abs(-1729), 1729);
EXPECT_EQ(Abs(1729), 1729);
EXPECT_EQ(Abs(-1729 * Metre), 1729 * Metre);
}
TEST_F(ElementaryFunctionsTest, DimensionlessExponentiation) {
double const number = π - 42;
double positivePower = 1;
double negativePower = 1;
EXPECT_EQ(positivePower, Pow<0>(number));
positivePower *= number;
negativePower /= number;
EXPECT_EQ(positivePower, Pow<1>(number));
EXPECT_EQ(negativePower, Pow<-1>(number));
positivePower *= number;
negativePower /= number;
EXPECT_EQ(positivePower, Pow<2>(number));
EXPECT_EQ(negativePower, Pow<-2>(number));
positivePower *= number;
negativePower /= number;
EXPECT_EQ(positivePower, Pow<3>(number));
EXPECT_EQ(negativePower, Pow<-3>(number));
positivePower *= number;
negativePower /= number;
// This one calls |std::pow|.
EXPECT_THAT(positivePower, AlmostEquals(Pow<4>(number), 0, 1));
EXPECT_THAT(negativePower, AlmostEquals(Pow<-4>(number), 0, 1));
}
// The Greek letters cause a warning when stringified by the macros, because
// apparently Visual Studio doesn't encode strings in UTF-8 by default.
#pragma warning(disable: 4566)
TEST_F(ElementaryFunctionsTest, PhysicalConstants) {
Length const lunar_distance = 384402 * Kilo(Metre);
// By definition.
EXPECT_THAT(1 / Pow<2>(SpeedOfLight),
AlmostEquals(VacuumPermittivity * VacuumPermeability, 1));
// The Keplerian approximation for the mass of the Sun
// is fairly accurate.
EXPECT_THAT(RelativeError(
4 * Pow<2>(π) * Pow<3>(AstronomicalUnit) / Pow<2>(JulianYear),
SolarGravitationalParameter),
Lt(4e-5));
EXPECT_THAT(RelativeError(1 * Parsec, 3.26156 * LightYear), Lt(2e-6));
// The Keplerian approximation for the mass of the Earth
// is pretty bad, but the error is still only 1%.
EXPECT_THAT(RelativeError(4 * Pow<2>(π) * Pow<3>(lunar_distance) /
Pow<2>(27.321582 * Day),
TerrestrialGravitationalParameter),
Lt(1e-2));
EXPECT_THAT(RelativeError(1 * SolarGravitationalParameter,
1047 * JovianGravitationalParameter),
Lt(6e-4));
// Delambre & Méchain.
EXPECT_THAT(RelativeError(TerrestrialGravitationalParameter /
Pow<2>(40 * Mega(Metre) / (2 * π)),
StandardGravity),
Lt(4e-3));
// Talleyrand.
EXPECT_THAT(RelativeError(π * Sqrt(1 * Metre / StandardGravity), 1 * Second),
Lt(4e-3));
}
#pragma warning(default: 4566)
TEST_F(ElementaryFunctionsTest, TrigonometricFunctions) {
EXPECT_EQ(Cos(0 * Degree), 1);
EXPECT_EQ(Sin(0 * Degree), 0);
EXPECT_THAT(Cos(90 * Degree), VanishesBefore(1.0, 0));
EXPECT_EQ(Sin(90 * Degree), 1);
EXPECT_EQ(Cos(180 * Degree), -1);
EXPECT_THAT(Sin(180 * Degree), VanishesBefore(1.0, 1));
EXPECT_THAT(Cos(-90 * Degree), VanishesBefore(1.0, 0));
EXPECT_EQ(Sin(-90 * Degree), -1);
for (int k = 1; k < 360; ++k) {
// Don't test for multiples of 90 degrees as zeros lead to horrible
// conditioning.
if (k % 90 != 0) {
EXPECT_THAT(Cos((90 - k) * Degree),
AlmostEquals(Sin(k * Degree), 0, 47));
EXPECT_THAT(Sin(k * Degree) / Cos(k * Degree),
AlmostEquals(Tan(k * Degree), 0, 2));
EXPECT_THAT(((k + 179) % 360 - 179) * Degree,
AlmostEquals(ArcTan(Sin(k * Degree), Cos(k * Degree)),
0, 77));
EXPECT_THAT(((k + 179) % 360 - 179) * Degree,
AlmostEquals(ArcTan(Sin(k * Degree) * AstronomicalUnit,
Cos(k * Degree) * AstronomicalUnit),
0, 77));
EXPECT_THAT(Cos(ArcCos(Cos(k * Degree))),
AlmostEquals(Cos(k * Degree), 0, 7));
EXPECT_THAT(Sin(ArcSin(Sin(k * Degree))),
AlmostEquals(Sin(k * Degree), 0, 1));
}
}
// Horribly conditioned near 0, so not in the loop above.
EXPECT_EQ(Tan(ArcTan(Tan(-42 * Degree))), Tan(-42 * Degree));
}
TEST_F(ElementaryFunctionsTest, HyperbolicFunctions) {
EXPECT_EQ(Sinh(0 * Radian), 0);
EXPECT_EQ(Cosh(0 * Radian), 1);
EXPECT_EQ(Tanh(0 * Radian), 0);
// Limits:
EXPECT_EQ(Sinh(20 * Radian), Cosh(20 * Radian));
EXPECT_EQ(Tanh(20 * Radian), 1);
EXPECT_EQ(Sinh(-20 * Radian), -Cosh(-20 * Radian));
EXPECT_EQ(Tanh(-20 * Radian), -1);
EXPECT_THAT(Sinh(2 * Radian) / Cosh(2 * Radian),
AlmostEquals(Tanh(2 * Radian), 0, 1));
EXPECT_THAT(ArcSinh(Sinh(-10 * Degree)),
AlmostEquals(-10 * Degree, 0, 1));
EXPECT_THAT(ArcCosh(Cosh(-10 * Degree)),
AlmostEquals(10 * Degree, 19, 20));
EXPECT_THAT(ArcTanh(Tanh(-10 * Degree)),
AlmostEquals(-10 * Degree, 0, 1));
}
TEST_F(ElementaryFunctionsTest, ExpLogAndRoots) {
// The ULP distance is 1 if everything is correctly rounded.
EXPECT_THAT(std::exp(std::log(2) / 2), AlmostEquals(Sqrt(2), 1));
// The ULP distance is 0 if everything is correctly rounded.
EXPECT_THAT(std::exp(std::log(2) / 3), AlmostEquals(Cbrt(2), 0));
EXPECT_THAT(
Sqrt(Rood),
AlmostEquals(std::exp(std::log(Rood / Pow<2>(Foot)) / 2) * Foot, 0));
EXPECT_THAT(
Cbrt(Gallon),
AlmostEquals(std::exp(std::log(Gallon / Pow<3>(Foot)) / 3) * Foot, 0, 1));
}
} // namespace quantities
} // namespace principia
<|endoftext|>
|
<commit_before>#include "core/FS/file_system.h"
#include "core/FS/ifile.h"
#include "core/blob.h"
#include "core/crc32.h"
#include "debug/debug.h"
#include "core/log.h"
#include "core/path_utils.h"
#include "core/profiler.h"
#include "core/resource_manager.h"
#include "core/resource_manager_base.h"
#include "editor/gizmo.h"
#include "editor/world_editor.h"
#include "engine/engine.h"
#include "engine/plugin_manager.h"
#include "renderer/pipeline.h"
#include "renderer/renderer.h"
#include "renderer/texture.h"
#include <Windows.h>
#include <cstdio>
class App
{
public:
App()
: m_tests(m_allocator)
{
m_current_test = -1;
m_is_test_universe_loaded = false;
m_universe_context = nullptr;
}
~App() { ASSERT(!m_universe_context); }
void universeFileLoaded(Lumix::FS::IFile& file, bool success)
{
ASSERT(success);
if (!success) return;
ASSERT(file.getBuffer());
Lumix::InputBlob blob(file.getBuffer(), (int)file.size());
uint32_t hash = 0;
blob.read(hash);
uint32_t engine_hash = 0;
blob.read(engine_hash);
if (Lumix::crc32((const uint8_t*)blob.getData() + sizeof(hash),
blob.getSize() - sizeof(hash)) != hash)
{
Lumix::g_log_error.log("render_test") << "Universe corrupted";
return;
}
bool deserialize_succeeded = m_engine->deserialize(*m_universe_context, blob);
m_is_test_universe_loaded = true;
if (!deserialize_succeeded)
{
Lumix::g_log_error.log("render_test") << "Failed to deserialize universe";
}
}
static LRESULT WINAPI msgProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
return DefWindowProc(hWnd, msg, wParam, lParam);
}
HWND createWindow()
{
HINSTANCE hInst = GetModuleHandle(NULL);
WNDCLASSEX wnd;
memset(&wnd, 0, sizeof(wnd));
wnd.cbSize = sizeof(wnd);
wnd.style = CS_HREDRAW | CS_VREDRAW;
wnd.lpfnWndProc = msgProc;
wnd.hInstance = hInst;
wnd.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wnd.hCursor = LoadCursor(NULL, IDC_ARROW);
wnd.lpszClassName = "render_test";
wnd.hIconSm = LoadIcon(NULL, IDI_APPLICATION);
RegisterClassExA(&wnd);
auto hwnd = CreateWindowA("render_test",
"render_test",
WS_OVERLAPPEDWINDOW | WS_VISIBLE,
0,
0,
800,
600,
NULL,
NULL,
hInst,
0);
Lumix::Renderer::setInitData(hwnd);
m_hwnd = hwnd;
return hwnd;
}
void init()
{
auto hwnd = createWindow();
Lumix::g_log_info.getCallback().bind<outputToVS>();
Lumix::g_log_warning.getCallback().bind<outputToVS>();
Lumix::g_log_error.getCallback().bind<outputToVS>();
Lumix::g_log_info.getCallback().bind<outputToConsole>();
Lumix::g_log_warning.getCallback().bind<outputToConsole>();
Lumix::g_log_error.getCallback().bind<outputToConsole>();
Lumix::enableCrashReporting(false);
m_engine = Lumix::Engine::create(NULL, m_allocator);
m_engine->getPluginManager().load("renderer.dll");
m_engine->getPluginManager().load("animation.dll");
m_engine->getPluginManager().load("audio.dll");
m_engine->getPluginManager().load("lua_script.dll");
m_engine->getPluginManager().load("physics.dll");
Lumix::Pipeline* pipeline_object =
static_cast<Lumix::Pipeline*>(m_engine->getResourceManager()
.get(Lumix::ResourceManager::PIPELINE)
->load(Lumix::Path("pipelines/render_test.lua")));
ASSERT(pipeline_object);
if (pipeline_object)
{
m_pipeline =
Lumix::PipelineInstance::create(*pipeline_object, m_engine->getAllocator());
}
m_universe_context = &m_engine->createUniverse();
m_pipeline->setScene(
(Lumix::RenderScene*)m_universe_context->getScene(Lumix::crc32("renderer")));
m_pipeline->setViewport(0, 0, 600, 400);
Lumix::Renderer* renderer =
static_cast<Lumix::Renderer*>(m_engine->getPluginManager().getPlugin("renderer"));
renderer->resize(600, 400);
enumerateTests();
}
void shutdown()
{
m_engine->destroyUniverse(*m_universe_context);
Lumix::PipelineInstance::destroy(m_pipeline);
Lumix::Engine::destroy(m_engine, m_allocator);
m_engine = nullptr;
m_pipeline = nullptr;
m_universe_context = nullptr;
}
void handleEvents()
{
MSG msg;
while (PeekMessage(&msg, 0, 0, 0, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
if (msg.message == WM_QUIT)
{
m_finished = true;
}
}
}
static void outputToVS(const char* system, const char* message)
{
char tmp[2048];
Lumix::copyString(tmp, system);
Lumix::catString(tmp, " : ");
Lumix::catString(tmp, message);
Lumix::catString(tmp, "\r");
OutputDebugString(tmp);
}
static void outputToConsole(const char* system, const char* message)
{
printf("%s: %s\n", system, message);
}
void enumerateTests()
{
WIN32_FIND_DATAA data;
char buf[100];
GetCurrentDirectory(100, buf);
auto handle = FindFirstFile(".\\render_tests\\*.unv", &data);
auto push_test = [&](const char* name) {
char basename[Lumix::MAX_PATH_LENGTH];
Lumix::PathUtils::getBasename(basename, Lumix::lengthOf(basename), name);
auto& test = m_tests.pushEmpty();
Lumix::copyString(test.path, "render_tests/");
Lumix::catString(test.path, basename);
test.failed = false;
};
if (handle != INVALID_HANDLE_VALUE)
{
push_test(data.cFileName);
while (FindNextFile(handle, &data))
{
push_test(data.cFileName);
}
FindClose(handle);
}
Lumix::g_log_info.log("render_test") << "Found " << m_tests.size() << " tests";
}
bool nextTest()
{
Lumix::FS::FileSystem& fs = m_engine->getFileSystem();
bool can_do_next_test = m_current_test == -1 ||
(!m_engine->getFileSystem().hasWork() && m_is_test_universe_loaded);
if (can_do_next_test)
{
char path[Lumix::MAX_PATH_LENGTH];
if (m_current_test >= 0)
{
Lumix::Renderer* renderer = static_cast<Lumix::Renderer*>(
m_engine->getPluginManager().getPlugin("renderer"));
Lumix::copyString(path, sizeof(path), m_tests[m_current_test].path);
Lumix::catString(path, sizeof(path), "_res.tga");
renderer->makeScreenshot(Lumix::Path(path));
char path_preimage[Lumix::MAX_PATH_LENGTH];
Lumix::copyString(path_preimage, sizeof(path), m_tests[m_current_test].path);
Lumix::catString(path_preimage, sizeof(path), ".tga");
auto file1 = fs.open(fs.getDefaultDevice(),
Lumix::Path(path),
Lumix::FS::Mode::OPEN | Lumix::FS::Mode::READ);
auto file2 = fs.open(fs.getDefaultDevice(),
Lumix::Path(path_preimage),
Lumix::FS::Mode::OPEN | Lumix::FS::Mode::READ);
if(!file1)
{
if (file2) fs.close(*file2);
Lumix::g_log_error.log("render_test") << "Failed to open " << path;
}
else if(!file2)
{
fs.close(*file1);
Lumix::g_log_error.log("render_test") << "Failed to open " << path_preimage;
}
else
{
unsigned int difference = Lumix::Texture::compareTGA(m_allocator, file1, file2, 10);
Lumix::g_log_info.log("render_test") << "Difference between " << path << " and "
<< path_preimage << " is " << difference;
fs.close(*file1);
fs.close(*file2);
m_tests[m_current_test].failed = difference > 100;
}
}
++m_current_test;
if (m_current_test < m_tests.size())
{
Lumix::copyString(path, sizeof(path), m_tests[m_current_test].path);
Lumix::catString(path, sizeof(path), ".unv");
Lumix::g_log_info.log("render_test") << "Loading " << path << "...";
Lumix::FS::ReadCallback file_read_cb;
file_read_cb.bind<App, &App::universeFileLoaded>(this);
fs.openAsync(fs.getDefaultDevice(),
Lumix::Path(path),
Lumix::FS::Mode::OPEN | Lumix::FS::Mode::READ,
file_read_cb);
m_is_test_universe_loaded = false;
return true;
}
return false;
}
return true;
}
void run()
{
m_finished = false;
while (!m_finished)
{
m_engine->update(*m_universe_context);
m_pipeline->setViewport(0, 0, 600, 400);
m_pipeline->render();
auto* renderer = m_engine->getPluginManager().getPlugin("renderer");
static_cast<Lumix::Renderer*>(renderer)->frame();
if (!m_engine->getFileSystem().hasWork())
{
if (!nextTest()) return;
}
m_engine->getFileSystem().updateAsyncTransactions();
handleEvents();
}
int failed_count = getFailedCount();
if (failed_count)
{
Lumix::g_log_info.log("render_test") << failed_count << " tests failed";
}
}
int getFailedCount() const
{
int count = 0;
for (auto& test : m_tests)
{
if (test.failed) ++count;
}
return count;
}
private:
struct Test
{
char path[Lumix::MAX_PATH_LENGTH];
bool failed;
};
Lumix::DefaultAllocator m_allocator;
Lumix::Engine* m_engine;
Lumix::UniverseContext* m_universe_context;
Lumix::PipelineInstance* m_pipeline;
Lumix::Array<Test> m_tests;
int m_current_test;
bool m_is_test_universe_loaded;
bool m_finished;
HWND m_hwnd;
};
INT WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, INT)
{
App app;
app.init();
app.run();
int failed_count = app.getFailedCount();
app.shutdown();
return failed_count;
}
<commit_msg>render tests fixed<commit_after>#include "core/FS/file_system.h"
#include "core/FS/ifile.h"
#include "core/blob.h"
#include "core/crc32.h"
#include "debug/debug.h"
#include "core/log.h"
#include "core/path_utils.h"
#include "core/profiler.h"
#include "core/resource_manager.h"
#include "core/resource_manager_base.h"
#include "editor/gizmo.h"
#include "editor/world_editor.h"
#include "engine/engine.h"
#include "engine/plugin_manager.h"
#include "renderer/pipeline.h"
#include "renderer/renderer.h"
#include "renderer/texture.h"
#include <Windows.h>
#include <cstdio>
class App
{
public:
App()
: m_tests(m_allocator)
{
m_current_test = -1;
m_is_test_universe_loaded = false;
m_universe_context = nullptr;
}
~App() { ASSERT(!m_universe_context); }
void universeFileLoaded(Lumix::FS::IFile& file, bool success)
{
ASSERT(success);
if (!success) return;
ASSERT(file.getBuffer());
Lumix::InputBlob blob(file.getBuffer(), (int)file.size());
#pragma pack(1)
struct Header
{
Lumix::uint32 magic;
int version;
Lumix::uint32 hash;
Lumix::uint32 engine_hash;
};
#pragma pack()
Header header;
blob.read(header);
if (Lumix::crc32((const uint8_t*)blob.getData() + sizeof(header),
blob.getSize() - sizeof(header)) != header.hash)
{
Lumix::g_log_error.log("render_test") << "Universe corrupted";
return;
}
bool deserialize_succeeded = m_engine->deserialize(*m_universe_context, blob);
m_is_test_universe_loaded = true;
if (!deserialize_succeeded)
{
Lumix::g_log_error.log("render_test") << "Failed to deserialize universe";
}
}
static LRESULT WINAPI msgProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
return DefWindowProc(hWnd, msg, wParam, lParam);
}
HWND createWindow()
{
HINSTANCE hInst = GetModuleHandle(NULL);
WNDCLASSEX wnd;
memset(&wnd, 0, sizeof(wnd));
wnd.cbSize = sizeof(wnd);
wnd.style = CS_HREDRAW | CS_VREDRAW;
wnd.lpfnWndProc = msgProc;
wnd.hInstance = hInst;
wnd.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wnd.hCursor = LoadCursor(NULL, IDC_ARROW);
wnd.lpszClassName = "render_test";
wnd.hIconSm = LoadIcon(NULL, IDI_APPLICATION);
RegisterClassExA(&wnd);
auto hwnd = CreateWindowA("render_test",
"render_test",
WS_OVERLAPPEDWINDOW | WS_VISIBLE,
0,
0,
800,
600,
NULL,
NULL,
hInst,
0);
Lumix::Renderer::setInitData(hwnd);
m_hwnd = hwnd;
return hwnd;
}
void init()
{
auto hwnd = createWindow();
Lumix::g_log_info.getCallback().bind<outputToVS>();
Lumix::g_log_warning.getCallback().bind<outputToVS>();
Lumix::g_log_error.getCallback().bind<outputToVS>();
Lumix::g_log_info.getCallback().bind<outputToConsole>();
Lumix::g_log_warning.getCallback().bind<outputToConsole>();
Lumix::g_log_error.getCallback().bind<outputToConsole>();
Lumix::enableCrashReporting(false);
m_engine = Lumix::Engine::create(NULL, m_allocator);
m_engine->getPluginManager().load("renderer.dll");
m_engine->getPluginManager().load("animation.dll");
m_engine->getPluginManager().load("audio.dll");
m_engine->getPluginManager().load("lua_script.dll");
m_engine->getPluginManager().load("physics.dll");
Lumix::Pipeline* pipeline_object =
static_cast<Lumix::Pipeline*>(m_engine->getResourceManager()
.get(Lumix::ResourceManager::PIPELINE)
->load(Lumix::Path("pipelines/render_test.lua")));
ASSERT(pipeline_object);
if (pipeline_object)
{
m_pipeline =
Lumix::PipelineInstance::create(*pipeline_object, m_engine->getAllocator());
}
m_universe_context = &m_engine->createUniverse();
m_pipeline->setScene(
(Lumix::RenderScene*)m_universe_context->getScene(Lumix::crc32("renderer")));
m_pipeline->setViewport(0, 0, 600, 400);
Lumix::Renderer* renderer =
static_cast<Lumix::Renderer*>(m_engine->getPluginManager().getPlugin("renderer"));
renderer->resize(600, 400);
enumerateTests();
}
void shutdown()
{
m_engine->destroyUniverse(*m_universe_context);
Lumix::PipelineInstance::destroy(m_pipeline);
Lumix::Engine::destroy(m_engine, m_allocator);
m_engine = nullptr;
m_pipeline = nullptr;
m_universe_context = nullptr;
}
void handleEvents()
{
MSG msg;
while (PeekMessage(&msg, 0, 0, 0, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
if (msg.message == WM_QUIT)
{
m_finished = true;
}
}
}
static void outputToVS(const char* system, const char* message)
{
char tmp[2048];
Lumix::copyString(tmp, system);
Lumix::catString(tmp, " : ");
Lumix::catString(tmp, message);
Lumix::catString(tmp, "\r");
OutputDebugString(tmp);
}
static void outputToConsole(const char* system, const char* message)
{
printf("%s: %s\n", system, message);
}
void enumerateTests()
{
WIN32_FIND_DATAA data;
char buf[100];
GetCurrentDirectory(100, buf);
auto handle = FindFirstFile(".\\render_tests\\*.unv", &data);
auto push_test = [&](const char* name) {
char basename[Lumix::MAX_PATH_LENGTH];
Lumix::PathUtils::getBasename(basename, Lumix::lengthOf(basename), name);
auto& test = m_tests.pushEmpty();
Lumix::copyString(test.path, "render_tests/");
Lumix::catString(test.path, basename);
test.failed = false;
};
if (handle != INVALID_HANDLE_VALUE)
{
push_test(data.cFileName);
while (FindNextFile(handle, &data))
{
push_test(data.cFileName);
}
FindClose(handle);
}
Lumix::g_log_info.log("render_test") << "Found " << m_tests.size() << " tests";
}
bool nextTest()
{
Lumix::FS::FileSystem& fs = m_engine->getFileSystem();
bool can_do_next_test = m_current_test == -1 ||
(!m_engine->getFileSystem().hasWork() && m_is_test_universe_loaded);
if (can_do_next_test)
{
char path[Lumix::MAX_PATH_LENGTH];
if (m_current_test >= 0)
{
Lumix::Renderer* renderer = static_cast<Lumix::Renderer*>(
m_engine->getPluginManager().getPlugin("renderer"));
Lumix::copyString(path, sizeof(path), m_tests[m_current_test].path);
Lumix::catString(path, sizeof(path), "_res.tga");
m_pipeline->setViewport(0, 0, 600, 400);
m_pipeline->render();
renderer->makeScreenshot(Lumix::Path(path));
renderer->frame();
m_pipeline->setViewport(0, 0, 600, 400);
m_pipeline->render();
renderer->frame();
char path_preimage[Lumix::MAX_PATH_LENGTH];
Lumix::copyString(path_preimage, sizeof(path), m_tests[m_current_test].path);
Lumix::catString(path_preimage, sizeof(path), ".tga");
auto file1 = fs.open(fs.getDefaultDevice(),
Lumix::Path(path),
Lumix::FS::Mode::OPEN | Lumix::FS::Mode::READ);
auto file2 = fs.open(fs.getDefaultDevice(),
Lumix::Path(path_preimage),
Lumix::FS::Mode::OPEN | Lumix::FS::Mode::READ);
if(!file1)
{
if (file2) fs.close(*file2);
Lumix::g_log_error.log("render_test") << "Failed to open " << path;
}
else if(!file2)
{
fs.close(*file1);
Lumix::g_log_error.log("render_test") << "Failed to open " << path_preimage;
}
else
{
unsigned int difference = Lumix::Texture::compareTGA(m_allocator, file1, file2, 10);
Lumix::g_log_info.log("render_test") << "Difference between " << path << " and "
<< path_preimage << " is " << difference;
fs.close(*file1);
fs.close(*file2);
m_tests[m_current_test].failed = difference > 100;
}
}
++m_current_test;
if (m_current_test < m_tests.size())
{
Lumix::copyString(path, sizeof(path), m_tests[m_current_test].path);
Lumix::catString(path, sizeof(path), ".unv");
Lumix::g_log_info.log("render_test") << "Loading " << path << "...";
Lumix::FS::ReadCallback file_read_cb;
file_read_cb.bind<App, &App::universeFileLoaded>(this);
fs.openAsync(fs.getDefaultDevice(),
Lumix::Path(path),
Lumix::FS::Mode::OPEN | Lumix::FS::Mode::READ,
file_read_cb);
m_is_test_universe_loaded = false;
return true;
}
return false;
}
return true;
}
void run()
{
m_finished = false;
while (!m_finished)
{
m_engine->update(*m_universe_context);
m_pipeline->setViewport(0, 0, 600, 400);
m_pipeline->render();
auto* renderer = m_engine->getPluginManager().getPlugin("renderer");
static_cast<Lumix::Renderer*>(renderer)->frame();
if (!m_engine->getFileSystem().hasWork())
{
if (!nextTest()) return;
}
m_engine->getFileSystem().updateAsyncTransactions();
handleEvents();
}
int failed_count = getFailedCount();
if (failed_count)
{
Lumix::g_log_info.log("render_test") << failed_count << " tests failed";
}
}
int getFailedCount() const
{
int count = 0;
for (auto& test : m_tests)
{
if (test.failed) ++count;
}
return count;
}
private:
struct Test
{
char path[Lumix::MAX_PATH_LENGTH];
bool failed;
};
Lumix::DefaultAllocator m_allocator;
Lumix::Engine* m_engine;
Lumix::UniverseContext* m_universe_context;
Lumix::PipelineInstance* m_pipeline;
Lumix::Array<Test> m_tests;
int m_current_test;
bool m_is_test_universe_loaded;
bool m_finished;
HWND m_hwnd;
};
INT WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, INT)
{
App app;
app.init();
app.run();
int failed_count = app.getFailedCount();
app.shutdown();
return failed_count;
}
<|endoftext|>
|
<commit_before>#include "OpenGLContext.hpp"
#include <glbinding-aux/ContextInfo.h>
#include <glbinding-aux/types_to_string.h>
#include <glbinding/Binding.h>
// Do not import namespace to prevent glbinding/QTOpenGL collision
#include <glbinding/gl/gl.h>
#include <globjects/globjects.h>
#include <GLFW/glfw3.h>
#include <iostream>
static void error( int errnum, const char* errmsg ) {
globjects::critical() << errnum << ": " << errmsg << std::endl;
}
OpenGLContext::OpenGLContext( const std::array<int, 2>& size ) {
// initialize openGL
if ( glfwInit() )
{
glfwSetErrorCallback( error );
glfwDefaultWindowHints();
glfwWindowHint( GLFW_VISIBLE, false );
glfwWindowHint( GLFW_CONTEXT_VERSION_MAJOR, 4 );
glfwWindowHint( GLFW_CONTEXT_VERSION_MINOR, 1 );
glfwWindowHint( GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE );
glfwWindowHint( GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE );
m_offscreenContext =
glfwCreateWindow( size[0], size[1], "Radium CommandLine Context", nullptr, nullptr );
}
if ( m_offscreenContext == nullptr )
{
globjects::critical() << "Context creation failed. Terminate execution.";
glfwTerminate();
}
else
{
// Initialize globjects (internally initializes glbinding, and registers the current
// context)
glfwMakeContextCurrent( m_offscreenContext );
globjects::init( []( const char* name ) { return glfwGetProcAddress( name ); } );
}
}
OpenGLContext::~OpenGLContext() {
glfwTerminate();
}
void OpenGLContext::makeCurrent() const {
if ( m_offscreenContext ) { glfwMakeContextCurrent( m_offscreenContext ); }
}
void OpenGLContext::doneCurrent() const {
if ( m_offscreenContext ) { glfwMakeContextCurrent( nullptr ); }
}
bool OpenGLContext::isValid() const {
return m_offscreenContext != nullptr;
}
std::string OpenGLContext::getInfo() const {
std::stringstream infoText;
makeCurrent();
infoText << "*** OffScreen OpenGL context ***" << std::endl;
infoText << "Renderer (glbinding) : " << glbinding::aux::ContextInfo::renderer() << std::endl;
infoText << "Vendor (glbinding) : " << glbinding::aux::ContextInfo::vendor() << std::endl;
infoText << "OpenGL (glbinding) : " << glbinding::aux::ContextInfo::version().toString()
<< std::endl;
infoText << "GLSL : "
<< gl::glGetString( gl::GLenum( GL_SHADING_LANGUAGE_VERSION ) ) << std::endl;
doneCurrent();
return infoText.str();
}
void OpenGLContext::show() {
glfwShowWindow( m_offscreenContext );
}
void OpenGLContext::hide() {
glfwHideWindow( m_offscreenContext );
}
void OpenGLContext::resize( const std::array<int, 2>& size ) {
glfwSetWindowSize( m_offscreenContext, size[0], size[1] );
}
void OpenGLContext::swapbuffers() {
glfwSwapBuffers( m_offscreenContext );
glfwPollEvents();
}
void OpenGLContext::waitForClose() {
while ( !glfwWindowShouldClose( m_offscreenContext ) )
{
glfwPollEvents();
}
}
<commit_msg>[tests] use gl:: to access OpenGL defines<commit_after>#include "OpenGLContext.hpp"
#include <glbinding-aux/ContextInfo.h>
#include <glbinding-aux/types_to_string.h>
#include <glbinding/Binding.h>
// Do not import namespace to prevent glbinding/QTOpenGL collision
#include <glbinding/gl/gl.h>
#include <globjects/globjects.h>
#include <GLFW/glfw3.h>
#include <iostream>
static void error( int errnum, const char* errmsg ) {
globjects::critical() << errnum << ": " << errmsg << std::endl;
}
OpenGLContext::OpenGLContext( const std::array<int, 2>& size ) {
// initialize openGL
if ( glfwInit() )
{
glfwSetErrorCallback( error );
glfwDefaultWindowHints();
glfwWindowHint( GLFW_VISIBLE, false );
glfwWindowHint( GLFW_CONTEXT_VERSION_MAJOR, 4 );
glfwWindowHint( GLFW_CONTEXT_VERSION_MINOR, 1 );
glfwWindowHint( GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE );
glfwWindowHint( GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE );
m_offscreenContext =
glfwCreateWindow( size[0], size[1], "Radium CommandLine Context", nullptr, nullptr );
}
if ( m_offscreenContext == nullptr )
{
globjects::critical() << "Context creation failed. Terminate execution.";
glfwTerminate();
}
else
{
// Initialize globjects (internally initializes glbinding, and registers the current
// context)
glfwMakeContextCurrent( m_offscreenContext );
globjects::init( []( const char* name ) { return glfwGetProcAddress( name ); } );
}
}
OpenGLContext::~OpenGLContext() {
glfwTerminate();
}
void OpenGLContext::makeCurrent() const {
if ( m_offscreenContext ) { glfwMakeContextCurrent( m_offscreenContext ); }
}
void OpenGLContext::doneCurrent() const {
if ( m_offscreenContext ) { glfwMakeContextCurrent( nullptr ); }
}
bool OpenGLContext::isValid() const {
return m_offscreenContext != nullptr;
}
std::string OpenGLContext::getInfo() const {
std::stringstream infoText;
makeCurrent();
infoText << "*** OffScreen OpenGL context ***" << std::endl;
infoText << "Renderer (glbinding) : " << glbinding::aux::ContextInfo::renderer() << std::endl;
infoText << "Vendor (glbinding) : " << glbinding::aux::ContextInfo::vendor() << std::endl;
infoText << "OpenGL (glbinding) : " << glbinding::aux::ContextInfo::version().toString()
<< std::endl;
infoText << "GLSL : "
<< gl::glGetString( gl::GLenum( gl::GL_SHADING_LANGUAGE_VERSION ) ) << std::endl;
doneCurrent();
return infoText.str();
}
void OpenGLContext::show() {
glfwShowWindow( m_offscreenContext );
}
void OpenGLContext::hide() {
glfwHideWindow( m_offscreenContext );
}
void OpenGLContext::resize( const std::array<int, 2>& size ) {
glfwSetWindowSize( m_offscreenContext, size[0], size[1] );
}
void OpenGLContext::swapbuffers() {
glfwSwapBuffers( m_offscreenContext );
glfwPollEvents();
}
void OpenGLContext::waitForClose() {
while ( !glfwWindowShouldClose( m_offscreenContext ) )
{
glfwPollEvents();
}
}
<|endoftext|>
|
<commit_before>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2017 Couchbase, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <memcached/rbac.h>
#include <cJSON_utils.h>
#include <platform/memorymap.h>
#include <platform/rwlock.h>
#include <strings.h>
#include <atomic>
#include <fstream>
#include <iostream>
#include <mutex>
#include <streambuf>
#include <string>
namespace cb {
namespace rbac {
// Every time we create a new PrivilegeDatabase we bump the generation.
// The PrivilegeContext contains the generation number it was generated
// from so that we can easily detect if the PrivilegeContext is stale.
static std::atomic<uint32_t> generation{0};
// The read write lock needed when you want to build a context
cb::RWLock rwlock;
std::unique_ptr<PrivilegeDatabase> db;
UserEntry::UserEntry(const cJSON& root) {
auto* json = const_cast<cJSON*>(&root);
const auto* it = cJSON_GetObjectItem(json, "privileges");
if (it != nullptr) {
privileges = parsePrivileges(it, false);
}
it = cJSON_GetObjectItem(json, "buckets");
if (it != nullptr) {
if (it->type != cJSON_Object) {
throw std::invalid_argument(
"UserEntry::UserEntry::"
" \"buckets\" should be an object");
}
for (it = it->child; it != nullptr; it = it->next) {
buckets[it->string] = parsePrivileges(it, true);
}
}
it = cJSON_GetObjectItem(json, "type");
if (it == nullptr) {
domain = Domain::Builtin;
} else if (it->type == cJSON_String) {
if (strcasecmp("builtin", it->valuestring) == 0) {
domain = Domain::Builtin;
} else if (strcasecmp("saslauthd", it->valuestring) == 0) {
domain = Domain::Saslauthd;
} else {
throw std::invalid_argument(
"UserEntry::UserEntry::"
" \"type\" should be \"builtin\" "
"or \"saslauthd\"");
}
} else {
throw std::invalid_argument(
"UserEntry::UserEntry::"
" \"type\" should be a string");
}
}
PrivilegeMask UserEntry::parsePrivileges(const cJSON* priv, bool buckets) {
PrivilegeMask ret;
for (const auto* it = priv->child; it != nullptr; it = it->next) {
if (it->type != cJSON_String) {
throw std::runtime_error(
"UserEntry::parsePrivileges: privileges must be specified "
"as strings");
}
const std::string str(it->valuestring);
if (str == "all") {
ret.set();
} else {
ret[int(to_privilege(str))] = true;
}
}
if (buckets) {
ret[int(Privilege::BucketManagement)] = false;
ret[int(Privilege::NodeManagement)] = false;
ret[int(Privilege::SessionManagement)] = false;
ret[int(Privilege::Audit)] = false;
ret[int(Privilege::AuditManagement)] = false;
ret[int(Privilege::IdleConnection)] = false;
ret[int(Privilege::CollectionManagement)] = false;
ret[int(Privilege::Impersonate)] = false;
} else {
ret[int(Privilege::Read)] = false;
ret[int(Privilege::Write)] = false;
ret[int(Privilege::DcpConsumer)] = false;
ret[int(Privilege::DcpProducer)] = false;
ret[int(Privilege::TapProducer)] = false;
ret[int(Privilege::TapConsumer)] = false;
ret[int(Privilege::MetaRead)] = false;
ret[int(Privilege::MetaWrite)] = false;
ret[int(Privilege::XattrRead)] = false;
ret[int(Privilege::XattrWrite)] = false;
}
return ret;
}
PrivilegeDatabase::PrivilegeDatabase(const cJSON* json)
: generation(cb::rbac::generation.operator++()) {
if (json != nullptr) {
for (auto it = json->child; it != nullptr; it = it->next) {
userdb.emplace(it->string, UserEntry(*it));
}
}
}
PrivilegeContext PrivilegeDatabase::createContext(
const std::string& user, const std::string& bucket) const {
PrivilegeMask mask;
const auto& ue = lookup(user);
if (!bucket.empty()) {
// Add the bucket specific privileges
auto iter = ue.getBuckets().find(bucket);
if (iter == ue.getBuckets().cend()) {
throw NoSuchBucketException(bucket.c_str());
}
mask |= iter->second;
}
// Add the rest of the privileges
mask |= ue.getPrivileges();
return PrivilegeContext(generation, mask);
}
PrivilegeAccess PrivilegeContext::check(Privilege privilege) const {
if (generation != cb::rbac::generation) {
return PrivilegeAccess::Stale;
}
const auto idx = size_t(privilege);
#ifndef NDEBUG
if (idx >= mask.size()) {
throw std::invalid_argument("Invalid privilege passed for the check)");
}
#endif
if (mask.test(idx)) {
return PrivilegeAccess::Ok;
}
return PrivilegeAccess::Fail;
}
std::string PrivilegeContext::to_string() const {
if (mask.all()) {
return "[all]";
} else if (mask.none()) {
return "[none]";
}
std::string ret;
ret.reserve(80);
ret.append("[");
for (size_t ii = 0; ii < mask.size(); ++ii) {
if (mask.test(ii)) {
ret.append(cb::rbac::to_string(Privilege(ii)));
ret.append(",");
}
}
ret.back() = ']';
return ret;
}
void PrivilegeContext::clearBucketPrivileges() {
mask[int(Privilege::Read)] = false;
mask[int(Privilege::Write)] = false;
mask[int(Privilege::SimpleStats)] = false;
mask[int(Privilege::DcpConsumer)] = false;
mask[int(Privilege::DcpProducer)] = false;
mask[int(Privilege::TapProducer)] = false;
mask[int(Privilege::TapConsumer)] = false;
mask[int(Privilege::MetaRead)] = false;
mask[int(Privilege::MetaWrite)] = false;
mask[int(Privilege::XattrRead)] = false;
mask[int(Privilege::XattrWrite)] = false;
}
void PrivilegeContext::setBucketPrivileges() {
mask[int(Privilege::Read)] = true;
mask[int(Privilege::Write)] = true;
mask[int(Privilege::SimpleStats)] = true;
mask[int(Privilege::DcpConsumer)] = true;
mask[int(Privilege::DcpProducer)] = true;
mask[int(Privilege::TapProducer)] = true;
mask[int(Privilege::TapConsumer)] = true;
mask[int(Privilege::MetaRead)] = true;
mask[int(Privilege::MetaWrite)] = true;
mask[int(Privilege::XattrRead)] = true;
mask[int(Privilege::XattrWrite)] = true;
}
PrivilegeContext createContext(const std::string& user,
const std::string& bucket) {
std::lock_guard<cb::ReaderLock> guard(rwlock.reader());
return db->createContext(user, bucket);
}
void loadPrivilegeDatabase(const std::string& filename) {
cb::MemoryMappedFile map(filename.c_str(),
cb::MemoryMappedFile::Mode::RDONLY);
map.open();
std::string content(reinterpret_cast<char*>(map.getRoot()), map.getSize());
map.close();
unique_cJSON_ptr json(cJSON_Parse(content.c_str()));
if (json.get() == nullptr) {
throw std::runtime_error(
"PrivilegeDatabaseManager::load: Failed to parse json");
}
std::unique_ptr<PrivilegeDatabase> database;
// Guess what, MSVC wasn't happy with std::make_unique :P
database.reset(new PrivilegeDatabase(json.get()));
std::lock_guard<cb::WriterLock> guard(rwlock.writer());
// Handle race conditions
if (db->generation < database->generation) {
db.swap(database);
}
}
void initialize() {
// Create an empty database to avoid having to add checks
// if it exists or not... Guess what, MSVC wasn't happy with
// std::make_unique :P
db.reset(new PrivilegeDatabase(nullptr));
}
void destroy() {
db.reset();
}
} // namespace rbac
} // namespace cb
<commit_msg>MB-19339: Ignore bucket with empty privilege set<commit_after>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2017 Couchbase, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <memcached/rbac.h>
#include <cJSON_utils.h>
#include <platform/memorymap.h>
#include <platform/rwlock.h>
#include <strings.h>
#include <atomic>
#include <fstream>
#include <iostream>
#include <mutex>
#include <streambuf>
#include <string>
namespace cb {
namespace rbac {
// Every time we create a new PrivilegeDatabase we bump the generation.
// The PrivilegeContext contains the generation number it was generated
// from so that we can easily detect if the PrivilegeContext is stale.
static std::atomic<uint32_t> generation{0};
// The read write lock needed when you want to build a context
cb::RWLock rwlock;
std::unique_ptr<PrivilegeDatabase> db;
UserEntry::UserEntry(const cJSON& root) {
auto* json = const_cast<cJSON*>(&root);
const auto* it = cJSON_GetObjectItem(json, "privileges");
if (it != nullptr) {
privileges = parsePrivileges(it, false);
}
it = cJSON_GetObjectItem(json, "buckets");
if (it != nullptr) {
if (it->type != cJSON_Object) {
throw std::invalid_argument(
"UserEntry::UserEntry::"
" \"buckets\" should be an object");
}
for (it = it->child; it != nullptr; it = it->next) {
auto privileges = parsePrivileges(it, true);
if (privileges.any()) {
buckets[it->string] = privileges;
}
}
}
it = cJSON_GetObjectItem(json, "type");
if (it == nullptr) {
domain = Domain::Builtin;
} else if (it->type == cJSON_String) {
if (strcasecmp("builtin", it->valuestring) == 0) {
domain = Domain::Builtin;
} else if (strcasecmp("saslauthd", it->valuestring) == 0) {
domain = Domain::Saslauthd;
} else {
throw std::invalid_argument(
"UserEntry::UserEntry::"
" \"type\" should be \"builtin\" "
"or \"saslauthd\"");
}
} else {
throw std::invalid_argument(
"UserEntry::UserEntry::"
" \"type\" should be a string");
}
}
PrivilegeMask UserEntry::parsePrivileges(const cJSON* priv, bool buckets) {
PrivilegeMask ret;
for (const auto* it = priv->child; it != nullptr; it = it->next) {
if (it->type != cJSON_String) {
throw std::runtime_error(
"UserEntry::parsePrivileges: privileges must be specified "
"as strings");
}
const std::string str(it->valuestring);
if (str == "all") {
ret.set();
} else {
ret[int(to_privilege(str))] = true;
}
}
if (buckets) {
ret[int(Privilege::BucketManagement)] = false;
ret[int(Privilege::NodeManagement)] = false;
ret[int(Privilege::SessionManagement)] = false;
ret[int(Privilege::Audit)] = false;
ret[int(Privilege::AuditManagement)] = false;
ret[int(Privilege::IdleConnection)] = false;
ret[int(Privilege::CollectionManagement)] = false;
ret[int(Privilege::Impersonate)] = false;
} else {
ret[int(Privilege::Read)] = false;
ret[int(Privilege::Write)] = false;
ret[int(Privilege::DcpConsumer)] = false;
ret[int(Privilege::DcpProducer)] = false;
ret[int(Privilege::TapProducer)] = false;
ret[int(Privilege::TapConsumer)] = false;
ret[int(Privilege::MetaRead)] = false;
ret[int(Privilege::MetaWrite)] = false;
ret[int(Privilege::XattrRead)] = false;
ret[int(Privilege::XattrWrite)] = false;
}
return ret;
}
PrivilegeDatabase::PrivilegeDatabase(const cJSON* json)
: generation(cb::rbac::generation.operator++()) {
if (json != nullptr) {
for (auto it = json->child; it != nullptr; it = it->next) {
userdb.emplace(it->string, UserEntry(*it));
}
}
}
PrivilegeContext PrivilegeDatabase::createContext(
const std::string& user, const std::string& bucket) const {
PrivilegeMask mask;
const auto& ue = lookup(user);
if (!bucket.empty()) {
// Add the bucket specific privileges
auto iter = ue.getBuckets().find(bucket);
if (iter == ue.getBuckets().cend()) {
throw NoSuchBucketException(bucket.c_str());
}
mask |= iter->second;
}
// Add the rest of the privileges
mask |= ue.getPrivileges();
return PrivilegeContext(generation, mask);
}
PrivilegeAccess PrivilegeContext::check(Privilege privilege) const {
if (generation != cb::rbac::generation) {
return PrivilegeAccess::Stale;
}
const auto idx = size_t(privilege);
#ifndef NDEBUG
if (idx >= mask.size()) {
throw std::invalid_argument("Invalid privilege passed for the check)");
}
#endif
if (mask.test(idx)) {
return PrivilegeAccess::Ok;
}
return PrivilegeAccess::Fail;
}
std::string PrivilegeContext::to_string() const {
if (mask.all()) {
return "[all]";
} else if (mask.none()) {
return "[none]";
}
std::string ret;
ret.reserve(80);
ret.append("[");
for (size_t ii = 0; ii < mask.size(); ++ii) {
if (mask.test(ii)) {
ret.append(cb::rbac::to_string(Privilege(ii)));
ret.append(",");
}
}
ret.back() = ']';
return ret;
}
void PrivilegeContext::clearBucketPrivileges() {
mask[int(Privilege::Read)] = false;
mask[int(Privilege::Write)] = false;
mask[int(Privilege::SimpleStats)] = false;
mask[int(Privilege::DcpConsumer)] = false;
mask[int(Privilege::DcpProducer)] = false;
mask[int(Privilege::TapProducer)] = false;
mask[int(Privilege::TapConsumer)] = false;
mask[int(Privilege::MetaRead)] = false;
mask[int(Privilege::MetaWrite)] = false;
mask[int(Privilege::XattrRead)] = false;
mask[int(Privilege::XattrWrite)] = false;
}
void PrivilegeContext::setBucketPrivileges() {
mask[int(Privilege::Read)] = true;
mask[int(Privilege::Write)] = true;
mask[int(Privilege::SimpleStats)] = true;
mask[int(Privilege::DcpConsumer)] = true;
mask[int(Privilege::DcpProducer)] = true;
mask[int(Privilege::TapProducer)] = true;
mask[int(Privilege::TapConsumer)] = true;
mask[int(Privilege::MetaRead)] = true;
mask[int(Privilege::MetaWrite)] = true;
mask[int(Privilege::XattrRead)] = true;
mask[int(Privilege::XattrWrite)] = true;
}
PrivilegeContext createContext(const std::string& user,
const std::string& bucket) {
std::lock_guard<cb::ReaderLock> guard(rwlock.reader());
return db->createContext(user, bucket);
}
void loadPrivilegeDatabase(const std::string& filename) {
cb::MemoryMappedFile map(filename.c_str(),
cb::MemoryMappedFile::Mode::RDONLY);
map.open();
std::string content(reinterpret_cast<char*>(map.getRoot()), map.getSize());
map.close();
unique_cJSON_ptr json(cJSON_Parse(content.c_str()));
if (json.get() == nullptr) {
throw std::runtime_error(
"PrivilegeDatabaseManager::load: Failed to parse json");
}
std::unique_ptr<PrivilegeDatabase> database;
// Guess what, MSVC wasn't happy with std::make_unique :P
database.reset(new PrivilegeDatabase(json.get()));
std::lock_guard<cb::WriterLock> guard(rwlock.writer());
// Handle race conditions
if (db->generation < database->generation) {
db.swap(database);
}
}
void initialize() {
// Create an empty database to avoid having to add checks
// if it exists or not... Guess what, MSVC wasn't happy with
// std::make_unique :P
db.reset(new PrivilegeDatabase(nullptr));
}
void destroy() {
db.reset();
}
} // namespace rbac
} // namespace cb
<|endoftext|>
|
<commit_before>/*
* (C) Copyright 2010
* Steve Chang
*
* 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
*
*/
extern "C" {
#include <stdio.h>
#include <stdlib.h>
#include <libavutil/opt.h>
#include <libavcodec/avcodec.h>
#include <libavutil/channel_layout.h>
#include <libavutil/common.h>
#include <libavutil/imgutils.h>
#include <libavutil/mathematics.h>
#include <libavutil/samplefmt.h>
#include <libswscale/swscale.h>
}
#include "opencv2/opencv.hpp"
#include "H264Decoder.h"
using namespace cv;
bool H264Decoder::getStatus()
{
return mEnable;
}
H264Decoder::H264Decoder():bStop(0), context(NULL), codec(NULL), frame(NULL), mEnable(false), swsContext(NULL), picture(NULL)
{
/* register all the codecs */
avcodec_register_all();
codec = avcodec_find_decoder(AV_CODEC_ID_H264);
if (!codec) {
printf("[%s]find decoder failed!\n", __func__);
return;
}
context = avcodec_alloc_context3(codec);
if (!context) {
printf("[%s]alloc context failed!\n", __func__);
return;
}
/* open it */
if(avcodec_open2(context, codec, NULL) < 0) {
fprintf(stderr, "could not open codec\n");
return;
}
mEnable = true;
#if 0
/* the codec gives us the frame size, in samples */
Mp4mux_Init();
Mp4mux_Open("/tmp/scv.mp4");
#endif
}
H264Decoder::~H264Decoder()
{
#if 0
Mp4mux_Close();
#endif
avcodec_close(context);
av_free(context);
}
void H264Decoder::stop()
{
bStop = 1;
}
int H264Decoder::decode(unsigned char *buffer, int size)
{
int ret = -1;
int len;
int got_picture;
AVFrame *pFrameRGB = NULL;
uint8_t *out_bufferRGB = NULL;
IplImage* pCVFrame = NULL;
picture = av_frame_alloc();
if (!picture) {
printf("alloc frame failed!\n");
return -1;
}
av_init_packet(&avpkt);
avpkt.size = size;
avpkt.data = buffer;
if (avpkt.size > 0) {
printf("prepare to decode video, size:%d\n", avpkt.size);
len = avcodec_decode_video2(context, picture, &got_picture, &avpkt);
if(len < 0) {
fprintf(stderr, "Error while decoding frame\n");
av_init_packet(&avpkt);
ret = -1;
goto cleanup;
}
if(got_picture) {
/* the picture is allocated by the decoder. no need to free it */
printf("size:%d, width:%d, height:%d\n", picture->linesize[0], context->width, context->height);
pFrameRGB = av_frame_alloc();
if (!pFrameRGB) {
printf("alloc rgb frame failed!\n");
ret = -1;
goto cleanup;
}
out_bufferRGB = new uint8_t[avpicture_get_size(PIX_FMT_BGR24, context->width, context->height)];
if (!out_bufferRGB) {
printf("alloc out_bufferRGB failed!\n");
ret = -1;
goto cleanup;
}
avpicture_fill((AVPicture *)pFrameRGB, out_bufferRGB, PIX_FMT_BGR24, context->width, context->height);
swsContext = sws_getContext(context->width, context->height, context->pix_fmt, context->width, context->height, PIX_FMT_BGR24, SWS_BICUBIC, NULL, NULL, NULL);
if(swsContext == NULL)
{
ret = -1;
printf("swsContext is null!\n");
goto cleanup;
}
sws_scale(swsContext, (const uint8_t* const*)picture->data, picture->linesize, 0, context->height, pFrameRGB->data, pFrameRGB->linesize);
pCVFrame = cvCreateImage(cvSize(context->width, context->height),8,3);
memcpy(pCVFrame->imageData,out_bufferRGB,context->width * context->height * 24 / 8);
pCVFrame->widthStep=context->width*3; //4096
pCVFrame->origin=0;
cvShowImage("decode",pCVFrame);//显示
cvWaitKey(20);
}
av_init_packet(&avpkt);
ret = 0;
}
cleanup:
if (pCVFrame) {
cvReleaseImage(&pCVFrame);
}
if (picture){
av_free(picture);
picture = NULL;
}
if (out_bufferRGB) {
delete[] out_bufferRGB;
}
if (pFrameRGB) {
av_free(pFrameRGB);
}
return ret;
}
<commit_msg>RTP:Receiver:modified printings<commit_after>/*
* (C) Copyright 2010
* Steve Chang
*
* 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
*
*/
extern "C" {
#include <stdio.h>
#include <stdlib.h>
#include <libavutil/opt.h>
#include <libavcodec/avcodec.h>
#include <libavutil/channel_layout.h>
#include <libavutil/common.h>
#include <libavutil/imgutils.h>
#include <libavutil/mathematics.h>
#include <libavutil/samplefmt.h>
#include <libswscale/swscale.h>
}
#include "opencv2/opencv.hpp"
#include "H264Decoder.h"
using namespace cv;
bool H264Decoder::getStatus()
{
return mEnable;
}
H264Decoder::H264Decoder():bStop(0), context(NULL), codec(NULL), frame(NULL), mEnable(false), swsContext(NULL), picture(NULL)
{
/* register all the codecs */
avcodec_register_all();
codec = avcodec_find_decoder(AV_CODEC_ID_H264);
if (!codec) {
printf("[%s]find decoder failed!\n", __func__);
return;
}
context = avcodec_alloc_context3(codec);
if (!context) {
printf("[%s]alloc context failed!\n", __func__);
return;
}
/* open it */
if(avcodec_open2(context, codec, NULL) < 0) {
fprintf(stderr, "could not open codec\n");
return;
}
mEnable = true;
#if 0
/* the codec gives us the frame size, in samples */
Mp4mux_Init();
Mp4mux_Open("/tmp/scv.mp4");
#endif
}
H264Decoder::~H264Decoder()
{
#if 0
Mp4mux_Close();
#endif
avcodec_close(context);
av_free(context);
}
void H264Decoder::stop()
{
bStop = 1;
}
int H264Decoder::decode(unsigned char *buffer, int size)
{
int ret = -1;
int len;
int got_picture;
AVFrame *pFrameRGB = NULL;
uint8_t *out_bufferRGB = NULL;
IplImage* pCVFrame = NULL;
picture = av_frame_alloc();
if (!picture) {
printf("alloc frame failed!\n");
return -1;
}
av_init_packet(&avpkt);
avpkt.size = size;
avpkt.data = buffer;
if (avpkt.size > 0) {
printf("prepare to decode video, size:%d\n", avpkt.size);
len = avcodec_decode_video2(context, picture, &got_picture, &avpkt);
if(len < 0) {
fprintf(stderr, "Error while decoding frame\n");
av_init_packet(&avpkt);
ret = -1;
goto cleanup;
}
if(got_picture) {
/* the picture is allocated by the decoder. no need to free it */
printf("line size:%d, width:%d, height:%d\n", picture->linesize[0], context->width, context->height);
pFrameRGB = av_frame_alloc();
if (!pFrameRGB) {
printf("alloc rgb frame failed!\n");
ret = -1;
goto cleanup;
}
out_bufferRGB = new uint8_t[avpicture_get_size(PIX_FMT_BGR24, context->width, context->height)];
if (!out_bufferRGB) {
printf("alloc out_bufferRGB failed!\n");
ret = -1;
goto cleanup;
}
avpicture_fill((AVPicture *)pFrameRGB, out_bufferRGB, PIX_FMT_BGR24, context->width, context->height);
swsContext = sws_getContext(context->width, context->height, context->pix_fmt, context->width, context->height, PIX_FMT_BGR24, SWS_BICUBIC, NULL, NULL, NULL);
if(swsContext == NULL)
{
ret = -1;
printf("swsContext is null!\n");
goto cleanup;
}
sws_scale(swsContext, (const uint8_t* const*)picture->data, picture->linesize, 0, context->height, pFrameRGB->data, pFrameRGB->linesize);
pCVFrame = cvCreateImage(cvSize(context->width, context->height),8,3);
memcpy(pCVFrame->imageData,out_bufferRGB,context->width * context->height * 24 / 8);
pCVFrame->widthStep=context->width*3; //4096
pCVFrame->origin=0;
cvShowImage("decode",pCVFrame);//显示
cvWaitKey(20);
}
av_init_packet(&avpkt);
ret = 0;
}
cleanup:
if (pCVFrame) {
cvReleaseImage(&pCVFrame);
}
if (picture){
av_free(picture);
picture = NULL;
}
if (out_bufferRGB) {
delete[] out_bufferRGB;
}
if (pFrameRGB) {
av_free(pFrameRGB);
}
return ret;
}
<|endoftext|>
|
<commit_before>#ifndef _FILSTR_HXX_
#include "filstr.hxx"
#endif
#ifndef _SHELL_HXX_
#include "shell.hxx"
#endif
#ifndef _PROV_HXX_
#include "prov.hxx"
#endif
using namespace fileaccess;
using namespace com::sun::star;
using namespace com::sun::star::ucb;
/******************************************************************************/
/* */
/* XStream_impl implementation */
/* */
/******************************************************************************/
uno::Any SAL_CALL
XStream_impl::queryInterface(
const uno::Type& rType )
throw( uno::RuntimeException)
{
uno::Any aRet = cppu::queryInterface( rType,
SAL_STATIC_CAST( lang::XTypeProvider*,this ),
SAL_STATIC_CAST( io::XStream*,this ),
SAL_STATIC_CAST( io::XInputStream*,this ),
SAL_STATIC_CAST( io::XOutputStream*,this ),
SAL_STATIC_CAST( io::XSeekable*,this ),
SAL_STATIC_CAST( io::XTruncate*,this ) );
return aRet.hasValue() ? aRet : OWeakObject::queryInterface( rType );
}
void SAL_CALL
XStream_impl::acquire(
void )
throw()
{
OWeakObject::acquire();
}
void SAL_CALL
XStream_impl::release(
void )
throw()
{
OWeakObject::release();
}
//////////////////////////////////////////////////////////////////////////////////////////
// XTypeProvider
//////////////////////////////////////////////////////////////////////////////////////////
XTYPEPROVIDER_IMPL_6( XStream_impl,
lang::XTypeProvider,
io::XStream,
io::XSeekable,
io::XInputStream,
io::XOutputStream,
io::XTruncate )
XStream_impl::XStream_impl( shell* pMyShell,const rtl::OUString& aUncPath )
: m_pMyShell( pMyShell ),
m_aFile( aUncPath ),
m_xProvider( m_pMyShell->m_pProvider ),
m_nErrorCode( TASKHANDLER_NO_ERROR ),
m_nMinorErrorCode( TASKHANDLER_NO_ERROR ),
m_bInputStreamCalled( false ),
m_bOutputStreamCalled( false )
{
osl::FileBase::RC err = m_aFile.open( OpenFlag_Read | OpenFlag_Write );
if( err != osl::FileBase::E_None )
{
m_nIsOpen = false;
m_aFile.close();
m_nErrorCode = TASKHANDLING_OPEN_FOR_STREAM;
m_nMinorErrorCode = err;
}
else
m_nIsOpen = true;
}
XStream_impl::~XStream_impl()
{
closeStream();
}
sal_Int32 SAL_CALL XStream_impl::CtorSuccess()
{
return m_nErrorCode;
}
sal_Int32 SAL_CALL XStream_impl::getMinorError()
{
return m_nMinorErrorCode;
}
uno::Reference< io::XInputStream > SAL_CALL
XStream_impl::getInputStream( )
throw( uno::RuntimeException)
{
{
osl::MutexGuard aGuard( m_aMutex );
m_bInputStreamCalled = true;
}
return uno::Reference< io::XInputStream >( this );
}
uno::Reference< io::XOutputStream > SAL_CALL
XStream_impl::getOutputStream( )
throw( uno::RuntimeException )
{
{
osl::MutexGuard aGuard( m_aMutex );
m_bOutputStreamCalled = true;
}
return uno::Reference< io::XOutputStream >( this );
}
void SAL_CALL XStream_impl::truncate(void)
throw( io::IOException, uno::RuntimeException )
{
if( osl::FileBase::E_None != m_aFile.setSize(0) )
throw io::IOException();
}
//===========================================================================
// XStream_impl private non interface methods
//===========================================================================
sal_Int32 SAL_CALL
XStream_impl::readBytes(
uno::Sequence< sal_Int8 >& aData,
sal_Int32 nBytesToRead )
throw( io::NotConnectedException,
io::BufferSizeExceededException,
io::IOException,
uno::RuntimeException)
{
if( ! m_nIsOpen )
throw io::IOException();
sal_Int8 * buffer;
try
{
buffer = new sal_Int8[nBytesToRead];
}
catch( std::bad_alloc )
{
if( m_nIsOpen ) m_aFile.close();
throw io::BufferSizeExceededException();
}
sal_uInt64 nrc;
m_aFile.read( (void* )buffer,sal_uInt64(nBytesToRead),nrc );
aData = uno::Sequence< sal_Int8 > ( buffer, (sal_uInt32)nrc );
delete[] buffer;
return ( sal_Int32 ) nrc;
}
sal_Int32 SAL_CALL
XStream_impl::readSomeBytes(
uno::Sequence< sal_Int8 >& aData,
sal_Int32 nMaxBytesToRead )
throw( io::NotConnectedException,
io::BufferSizeExceededException,
io::IOException,
uno::RuntimeException)
{
return readBytes( aData,nMaxBytesToRead );
}
void SAL_CALL
XStream_impl::skipBytes(
sal_Int32 nBytesToSkip )
throw( io::NotConnectedException,
io::BufferSizeExceededException,
io::IOException,
uno::RuntimeException )
{
m_aFile.setPos( osl_Pos_Current, sal_uInt64( nBytesToSkip ) );
}
sal_Int32 SAL_CALL
XStream_impl::available(
void )
throw( io::NotConnectedException,
io::IOException,
uno::RuntimeException)
{
return 0;
}
void SAL_CALL
XStream_impl::writeBytes( const uno::Sequence< sal_Int8 >& aData )
throw( io::NotConnectedException,
io::BufferSizeExceededException,
io::IOException,
uno::RuntimeException)
{
sal_Int32 length = aData.getLength();
sal_uInt64 nWrittenBytes;
if( length )
{
const sal_Int8* p = aData.getConstArray();
m_aFile.write( ((void*)(p)),
sal_uInt64( length ),
nWrittenBytes );
if( nWrittenBytes != length )
{
// DBG_ASSERT( "Write Operation not successful" );
throw io::IOException();
}
}
}
void SAL_CALL
XStream_impl::closeStream(
void )
throw( io::NotConnectedException,
io::IOException,
uno::RuntimeException )
{
if( m_nIsOpen )
{
if( osl::FileBase::E_None != m_aFile.close() )
throw io::IOException();
m_nIsOpen = false;
}
}
void SAL_CALL
XStream_impl::closeInput(
void )
throw( io::NotConnectedException,
io::IOException,
uno::RuntimeException )
{
osl::MutexGuard aGuard( m_aMutex );
m_bInputStreamCalled = false;
if( ! m_bOutputStreamCalled )
closeStream();
}
void SAL_CALL
XStream_impl::closeOutput(
void )
throw( io::NotConnectedException,
io::IOException,
uno::RuntimeException )
{
osl::MutexGuard aGuard( m_aMutex );
m_bOutputStreamCalled = false;
if( ! m_bInputStreamCalled )
closeStream();
}
void SAL_CALL
XStream_impl::seek(
sal_Int64 location )
throw( lang::IllegalArgumentException,
io::IOException,
uno::RuntimeException )
{
if( location < 0 )
throw lang::IllegalArgumentException();
if( osl::FileBase::E_None != m_aFile.setPos( Pos_Absolut, sal_uInt64( location ) ) )
throw io::IOException();
}
sal_Int64 SAL_CALL
XStream_impl::getPosition(
void )
throw( io::IOException,
uno::RuntimeException )
{
sal_uInt64 uPos;
if( osl::FileBase::E_None != m_aFile.getPos( uPos ) )
throw io::IOException();
return sal_Int64( uPos );
}
sal_Int64 SAL_CALL
XStream_impl::getLength(
void )
throw( io::IOException,
uno::RuntimeException )
{
osl::FileBase::RC err;
sal_uInt64 uCurrentPos, uEndPos;
err = m_aFile.getPos( uCurrentPos );
if( err != osl::FileBase::E_None )
throw io::IOException();
err = m_aFile.setPos( Pos_End, 0 );
if( err != osl::FileBase::E_None )
throw io::IOException();
err = m_aFile.getPos( uEndPos );
if( err != osl::FileBase::E_None )
throw io::IOException();
err = m_aFile.setPos( Pos_Absolut, uCurrentPos );
if( err != osl::FileBase::E_None )
throw io::IOException();
else
return sal_Int64( uEndPos );
}
void SAL_CALL
XStream_impl::flush()
throw( io::NotConnectedException,
io::BufferSizeExceededException,
io::IOException,
uno::RuntimeException )
{
return;
}
<commit_msg>#93494# Merged in 1.5.6.1.<commit_after>#ifndef _COM_SUN_STAR_IO_IOEXCEPTION_HPP_
#include "com/sun/star/io/IOException.hpp"
#endif
#ifndef _COM_SUN_STAR_UNO_RUNTIMEEXCEPTION_HPP_
#include "com/sun/star/uno/RuntimeException.hpp"
#endif
#ifndef _OSL_DIAGNOSE_H_
#include "osl/diagnose.h"
#endif
#ifndef _FILSTR_HXX_
#include "filstr.hxx"
#endif
#ifndef _SHELL_HXX_
#include "shell.hxx"
#endif
#ifndef _PROV_HXX_
#include "prov.hxx"
#endif
using namespace fileaccess;
using namespace com::sun::star;
using namespace com::sun::star::ucb;
/******************************************************************************/
/* */
/* XStream_impl implementation */
/* */
/******************************************************************************/
uno::Any SAL_CALL
XStream_impl::queryInterface(
const uno::Type& rType )
throw( uno::RuntimeException)
{
uno::Any aRet = cppu::queryInterface( rType,
SAL_STATIC_CAST( lang::XTypeProvider*,this ),
SAL_STATIC_CAST( io::XStream*,this ),
SAL_STATIC_CAST( io::XInputStream*,this ),
SAL_STATIC_CAST( io::XOutputStream*,this ),
SAL_STATIC_CAST( io::XSeekable*,this ),
SAL_STATIC_CAST( io::XTruncate*,this ) );
return aRet.hasValue() ? aRet : OWeakObject::queryInterface( rType );
}
void SAL_CALL
XStream_impl::acquire(
void )
throw()
{
OWeakObject::acquire();
}
void SAL_CALL
XStream_impl::release(
void )
throw()
{
OWeakObject::release();
}
//////////////////////////////////////////////////////////////////////////////////////////
// XTypeProvider
//////////////////////////////////////////////////////////////////////////////////////////
XTYPEPROVIDER_IMPL_6( XStream_impl,
lang::XTypeProvider,
io::XStream,
io::XSeekable,
io::XInputStream,
io::XOutputStream,
io::XTruncate )
XStream_impl::XStream_impl( shell* pMyShell,const rtl::OUString& aUncPath )
: m_pMyShell( pMyShell ),
m_aFile( aUncPath ),
m_xProvider( m_pMyShell->m_pProvider ),
m_nErrorCode( TASKHANDLER_NO_ERROR ),
m_nMinorErrorCode( TASKHANDLER_NO_ERROR ),
m_bInputStreamCalled( false ),
m_bOutputStreamCalled( false )
{
osl::FileBase::RC err = m_aFile.open( OpenFlag_Read | OpenFlag_Write );
if( err != osl::FileBase::E_None )
{
m_nIsOpen = false;
m_aFile.close();
m_nErrorCode = TASKHANDLING_OPEN_FOR_STREAM;
m_nMinorErrorCode = err;
}
else
m_nIsOpen = true;
}
XStream_impl::~XStream_impl()
{
try
{
closeStream();
}
catch (io::IOException const &)
{
OSL_ENSURE(false, "unexpected situation");
}
catch (uno::RuntimeException const &)
{
OSL_ENSURE(false, "unexpected situation");
}
}
sal_Int32 SAL_CALL XStream_impl::CtorSuccess()
{
return m_nErrorCode;
}
sal_Int32 SAL_CALL XStream_impl::getMinorError()
{
return m_nMinorErrorCode;
}
uno::Reference< io::XInputStream > SAL_CALL
XStream_impl::getInputStream( )
throw( uno::RuntimeException)
{
{
osl::MutexGuard aGuard( m_aMutex );
m_bInputStreamCalled = true;
}
return uno::Reference< io::XInputStream >( this );
}
uno::Reference< io::XOutputStream > SAL_CALL
XStream_impl::getOutputStream( )
throw( uno::RuntimeException )
{
{
osl::MutexGuard aGuard( m_aMutex );
m_bOutputStreamCalled = true;
}
return uno::Reference< io::XOutputStream >( this );
}
void SAL_CALL XStream_impl::truncate(void)
throw( io::IOException, uno::RuntimeException )
{
if( osl::FileBase::E_None != m_aFile.setSize(0) )
throw io::IOException();
}
//===========================================================================
// XStream_impl private non interface methods
//===========================================================================
sal_Int32 SAL_CALL
XStream_impl::readBytes(
uno::Sequence< sal_Int8 >& aData,
sal_Int32 nBytesToRead )
throw( io::NotConnectedException,
io::BufferSizeExceededException,
io::IOException,
uno::RuntimeException)
{
if( ! m_nIsOpen )
throw io::IOException();
sal_Int8 * buffer;
try
{
buffer = new sal_Int8[nBytesToRead];
}
catch( std::bad_alloc )
{
if( m_nIsOpen ) m_aFile.close();
throw io::BufferSizeExceededException();
}
sal_uInt64 nrc;
m_aFile.read( (void* )buffer,sal_uInt64(nBytesToRead),nrc );
aData = uno::Sequence< sal_Int8 > ( buffer, (sal_uInt32)nrc );
delete[] buffer;
return ( sal_Int32 ) nrc;
}
sal_Int32 SAL_CALL
XStream_impl::readSomeBytes(
uno::Sequence< sal_Int8 >& aData,
sal_Int32 nMaxBytesToRead )
throw( io::NotConnectedException,
io::BufferSizeExceededException,
io::IOException,
uno::RuntimeException)
{
return readBytes( aData,nMaxBytesToRead );
}
void SAL_CALL
XStream_impl::skipBytes(
sal_Int32 nBytesToSkip )
throw( io::NotConnectedException,
io::BufferSizeExceededException,
io::IOException,
uno::RuntimeException )
{
m_aFile.setPos( osl_Pos_Current, sal_uInt64( nBytesToSkip ) );
}
sal_Int32 SAL_CALL
XStream_impl::available(
void )
throw( io::NotConnectedException,
io::IOException,
uno::RuntimeException)
{
return 0;
}
void SAL_CALL
XStream_impl::writeBytes( const uno::Sequence< sal_Int8 >& aData )
throw( io::NotConnectedException,
io::BufferSizeExceededException,
io::IOException,
uno::RuntimeException)
{
sal_Int32 length = aData.getLength();
sal_uInt64 nWrittenBytes;
if( length )
{
const sal_Int8* p = aData.getConstArray();
m_aFile.write( ((void*)(p)),
sal_uInt64( length ),
nWrittenBytes );
if( nWrittenBytes != length )
{
// DBG_ASSERT( "Write Operation not successful" );
throw io::IOException();
}
}
}
void SAL_CALL
XStream_impl::closeStream(
void )
throw( io::NotConnectedException,
io::IOException,
uno::RuntimeException )
{
if( m_nIsOpen )
{
if( osl::FileBase::E_None != m_aFile.close() )
throw io::IOException();
m_nIsOpen = false;
}
}
void SAL_CALL
XStream_impl::closeInput(
void )
throw( io::NotConnectedException,
io::IOException,
uno::RuntimeException )
{
osl::MutexGuard aGuard( m_aMutex );
m_bInputStreamCalled = false;
if( ! m_bOutputStreamCalled )
closeStream();
}
void SAL_CALL
XStream_impl::closeOutput(
void )
throw( io::NotConnectedException,
io::IOException,
uno::RuntimeException )
{
osl::MutexGuard aGuard( m_aMutex );
m_bOutputStreamCalled = false;
if( ! m_bInputStreamCalled )
closeStream();
}
void SAL_CALL
XStream_impl::seek(
sal_Int64 location )
throw( lang::IllegalArgumentException,
io::IOException,
uno::RuntimeException )
{
if( location < 0 )
throw lang::IllegalArgumentException();
if( osl::FileBase::E_None != m_aFile.setPos( Pos_Absolut, sal_uInt64( location ) ) )
throw io::IOException();
}
sal_Int64 SAL_CALL
XStream_impl::getPosition(
void )
throw( io::IOException,
uno::RuntimeException )
{
sal_uInt64 uPos;
if( osl::FileBase::E_None != m_aFile.getPos( uPos ) )
throw io::IOException();
return sal_Int64( uPos );
}
sal_Int64 SAL_CALL
XStream_impl::getLength(
void )
throw( io::IOException,
uno::RuntimeException )
{
osl::FileBase::RC err;
sal_uInt64 uCurrentPos, uEndPos;
err = m_aFile.getPos( uCurrentPos );
if( err != osl::FileBase::E_None )
throw io::IOException();
err = m_aFile.setPos( Pos_End, 0 );
if( err != osl::FileBase::E_None )
throw io::IOException();
err = m_aFile.getPos( uEndPos );
if( err != osl::FileBase::E_None )
throw io::IOException();
err = m_aFile.setPos( Pos_Absolut, uCurrentPos );
if( err != osl::FileBase::E_None )
throw io::IOException();
else
return sal_Int64( uEndPos );
}
void SAL_CALL
XStream_impl::flush()
throw( io::NotConnectedException,
io::BufferSizeExceededException,
io::IOException,
uno::RuntimeException )
{
return;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: stream.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: hr $ $Date: 2006-06-20 05:28:09 $
*
* 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 _GVFSSTREAM_HXX_
#define _GVFSSTREAM_HXX_
#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#ifndef _CPPUHELPER_WEAK_HXX_
#include <cppuhelper/weak.hxx>
#endif
#ifndef _COM_SUN_STAR_IO_XSTREAM_HPP_
#include <com/sun/star/io/XStream.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XINPUTSTREAM_HPP_
#include <com/sun/star/io/XInputStream.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XOUTPUTSTREAM_HPP_
#include <com/sun/star/io/XOutputStream.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XTRUNCATE_HPP_
#include <com/sun/star/io/XTruncate.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XSEEKABLE_HPP_
#include <com/sun/star/io/XSeekable.hpp>
#endif
#include <libgnomevfs/gnome-vfs-handle.h>
namespace gvfs
{
class Stream : public ::com::sun::star::io::XStream,
public ::com::sun::star::io::XInputStream,
public ::com::sun::star::io::XOutputStream,
public ::com::sun::star::io::XTruncate,
public ::com::sun::star::io::XSeekable,
public ::cppu::OWeakObject
{
private:
GnomeVFSHandle *m_handle;
GnomeVFSFileInfo m_info;
osl::Mutex m_aMutex;
sal_Bool m_eof;
sal_Bool m_bInputStreamCalled;
sal_Bool m_bOutputStreamCalled;
void throwOnError( GnomeVFSResult result )
throw( ::com::sun::star::io::NotConnectedException,
::com::sun::star::io::BufferSizeExceededException,
::com::sun::star::io::IOException,
::com::sun::star::uno::RuntimeException );
void closeStream( void )
throw( ::com::sun::star::io::NotConnectedException,
::com::sun::star::io::IOException,
::com::sun::star::uno::RuntimeException );
public:
Stream ( GnomeVFSHandle *handle,
const GnomeVFSFileInfo *aInfo );
virtual ~Stream();
// XInterface
virtual com::sun::star::uno::Any SAL_CALL queryInterface(const ::com::sun::star::uno::Type & type )
throw( ::com::sun::star::uno::RuntimeException );
virtual void SAL_CALL acquire( void )
throw ()
{ OWeakObject::acquire(); }
virtual void SAL_CALL release( void )
throw()
{ OWeakObject::release(); }
// XStream
virtual com::sun::star::uno::Reference< com::sun::star::io::XInputStream > SAL_CALL getInputStream( )
throw( com::sun::star::uno::RuntimeException );
virtual com::sun::star::uno::Reference< com::sun::star::io::XOutputStream > SAL_CALL getOutputStream( )
throw( com::sun::star::uno::RuntimeException );
// XInputStream
virtual sal_Int32 SAL_CALL readBytes(
::com::sun::star::uno::Sequence< sal_Int8 > & aData,
sal_Int32 nBytesToRead )
throw( ::com::sun::star::io::NotConnectedException,
::com::sun::star::io::BufferSizeExceededException,
::com::sun::star::io::IOException,
::com::sun::star::uno::RuntimeException );
virtual sal_Int32 SAL_CALL readSomeBytes(
::com::sun::star::uno::Sequence< sal_Int8 > & aData,
sal_Int32 nMaxBytesToRead )
throw( ::com::sun::star::io::NotConnectedException,
::com::sun::star::io::BufferSizeExceededException,
::com::sun::star::io::IOException,
::com::sun::star::uno::RuntimeException );
virtual void SAL_CALL skipBytes( sal_Int32 nBytesToSkip )
throw( ::com::sun::star::io::NotConnectedException,
::com::sun::star::io::BufferSizeExceededException,
::com::sun::star::io::IOException,
::com::sun::star::uno::RuntimeException );
virtual sal_Int32 SAL_CALL available( void )
throw( ::com::sun::star::io::NotConnectedException,
::com::sun::star::io::IOException,
::com::sun::star::uno::RuntimeException );
virtual void SAL_CALL closeInput( void )
throw( ::com::sun::star::io::NotConnectedException,
::com::sun::star::io::IOException,
::com::sun::star::uno::RuntimeException );
// XSeekable
virtual void SAL_CALL seek( sal_Int64 location )
throw( ::com::sun::star::lang::IllegalArgumentException,
::com::sun::star::io::IOException,
::com::sun::star::uno::RuntimeException );
virtual sal_Int64 SAL_CALL getPosition()
throw( ::com::sun::star::io::IOException,
::com::sun::star::uno::RuntimeException );
virtual sal_Int64 SAL_CALL getLength()
throw( ::com::sun::star::io::IOException,
::com::sun::star::uno::RuntimeException );
// XOutputStream
virtual void SAL_CALL writeBytes( const com::sun::star::uno::Sequence< sal_Int8 >& aData )
throw( com::sun::star::io::NotConnectedException,
com::sun::star::io::BufferSizeExceededException,
com::sun::star::io::IOException,
com::sun::star::uno::RuntimeException);
virtual void SAL_CALL flush( void )
throw( com::sun::star::io::NotConnectedException,
com::sun::star::io::BufferSizeExceededException,
com::sun::star::io::IOException,
com::sun::star::uno::RuntimeException);
virtual void SAL_CALL closeOutput( void )
throw( com::sun::star::io::NotConnectedException,
com::sun::star::io::IOException,
com::sun::star::uno::RuntimeException );
// XTruncate
virtual void SAL_CALL truncate( void )
throw( com::sun::star::io::IOException,
com::sun::star::uno::RuntimeException );
};
} // namespace gvfs
#endif // _GVFSSTREAM_HXX_
<commit_msg>INTEGRATION: CWS changefileheader (1.4.138); FILE MERGED 2008/04/01 16:02:19 thb 1.4.138.3: #i85898# Stripping all external header guards 2008/04/01 12:58:14 thb 1.4.138.2: #i85898# Stripping all external header guards 2008/03/31 15:30:23 rt 1.4.138.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: stream.hxx,v $
* $Revision: 1.5 $
*
* 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 _GVFSSTREAM_HXX_
#define _GVFSSTREAM_HXX_
#include <sal/types.h>
#include <rtl/ustring.hxx>
#include <cppuhelper/weak.hxx>
#include <com/sun/star/io/XStream.hpp>
#include <com/sun/star/io/XInputStream.hpp>
#include <com/sun/star/io/XOutputStream.hpp>
#include <com/sun/star/io/XTruncate.hpp>
#include <com/sun/star/io/XSeekable.hpp>
#include <libgnomevfs/gnome-vfs-handle.h>
namespace gvfs
{
class Stream : public ::com::sun::star::io::XStream,
public ::com::sun::star::io::XInputStream,
public ::com::sun::star::io::XOutputStream,
public ::com::sun::star::io::XTruncate,
public ::com::sun::star::io::XSeekable,
public ::cppu::OWeakObject
{
private:
GnomeVFSHandle *m_handle;
GnomeVFSFileInfo m_info;
osl::Mutex m_aMutex;
sal_Bool m_eof;
sal_Bool m_bInputStreamCalled;
sal_Bool m_bOutputStreamCalled;
void throwOnError( GnomeVFSResult result )
throw( ::com::sun::star::io::NotConnectedException,
::com::sun::star::io::BufferSizeExceededException,
::com::sun::star::io::IOException,
::com::sun::star::uno::RuntimeException );
void closeStream( void )
throw( ::com::sun::star::io::NotConnectedException,
::com::sun::star::io::IOException,
::com::sun::star::uno::RuntimeException );
public:
Stream ( GnomeVFSHandle *handle,
const GnomeVFSFileInfo *aInfo );
virtual ~Stream();
// XInterface
virtual com::sun::star::uno::Any SAL_CALL queryInterface(const ::com::sun::star::uno::Type & type )
throw( ::com::sun::star::uno::RuntimeException );
virtual void SAL_CALL acquire( void )
throw ()
{ OWeakObject::acquire(); }
virtual void SAL_CALL release( void )
throw()
{ OWeakObject::release(); }
// XStream
virtual com::sun::star::uno::Reference< com::sun::star::io::XInputStream > SAL_CALL getInputStream( )
throw( com::sun::star::uno::RuntimeException );
virtual com::sun::star::uno::Reference< com::sun::star::io::XOutputStream > SAL_CALL getOutputStream( )
throw( com::sun::star::uno::RuntimeException );
// XInputStream
virtual sal_Int32 SAL_CALL readBytes(
::com::sun::star::uno::Sequence< sal_Int8 > & aData,
sal_Int32 nBytesToRead )
throw( ::com::sun::star::io::NotConnectedException,
::com::sun::star::io::BufferSizeExceededException,
::com::sun::star::io::IOException,
::com::sun::star::uno::RuntimeException );
virtual sal_Int32 SAL_CALL readSomeBytes(
::com::sun::star::uno::Sequence< sal_Int8 > & aData,
sal_Int32 nMaxBytesToRead )
throw( ::com::sun::star::io::NotConnectedException,
::com::sun::star::io::BufferSizeExceededException,
::com::sun::star::io::IOException,
::com::sun::star::uno::RuntimeException );
virtual void SAL_CALL skipBytes( sal_Int32 nBytesToSkip )
throw( ::com::sun::star::io::NotConnectedException,
::com::sun::star::io::BufferSizeExceededException,
::com::sun::star::io::IOException,
::com::sun::star::uno::RuntimeException );
virtual sal_Int32 SAL_CALL available( void )
throw( ::com::sun::star::io::NotConnectedException,
::com::sun::star::io::IOException,
::com::sun::star::uno::RuntimeException );
virtual void SAL_CALL closeInput( void )
throw( ::com::sun::star::io::NotConnectedException,
::com::sun::star::io::IOException,
::com::sun::star::uno::RuntimeException );
// XSeekable
virtual void SAL_CALL seek( sal_Int64 location )
throw( ::com::sun::star::lang::IllegalArgumentException,
::com::sun::star::io::IOException,
::com::sun::star::uno::RuntimeException );
virtual sal_Int64 SAL_CALL getPosition()
throw( ::com::sun::star::io::IOException,
::com::sun::star::uno::RuntimeException );
virtual sal_Int64 SAL_CALL getLength()
throw( ::com::sun::star::io::IOException,
::com::sun::star::uno::RuntimeException );
// XOutputStream
virtual void SAL_CALL writeBytes( const com::sun::star::uno::Sequence< sal_Int8 >& aData )
throw( com::sun::star::io::NotConnectedException,
com::sun::star::io::BufferSizeExceededException,
com::sun::star::io::IOException,
com::sun::star::uno::RuntimeException);
virtual void SAL_CALL flush( void )
throw( com::sun::star::io::NotConnectedException,
com::sun::star::io::BufferSizeExceededException,
com::sun::star::io::IOException,
com::sun::star::uno::RuntimeException);
virtual void SAL_CALL closeOutput( void )
throw( com::sun::star::io::NotConnectedException,
com::sun::star::io::IOException,
com::sun::star::uno::RuntimeException );
// XTruncate
virtual void SAL_CALL truncate( void )
throw( com::sun::star::io::IOException,
com::sun::star::uno::RuntimeException );
};
} // namespace gvfs
#endif // _GVFSSTREAM_HXX_
<|endoftext|>
|
<commit_before>/**
* @file configuration.cpp
*
* @date Nov 26, 2012
* @author partio
*/
#include "configuration.h"
#include "logger_factory.h"
using namespace himan;
configuration::configuration()
{
Init();
itsLogger = std::unique_ptr<logger> (logger_factory::Instance()->GetLog("configuration"));
}
configuration::configuration(const configuration& other)
{
itsOutputFileType = other.itsOutputFileType;
itsConfigurationFile = other.itsConfigurationFile;
itsAuxiliaryFiles = other.itsAuxiliaryFiles;
itsOriginTime = other.itsOriginTime;
itsFileWriteOption = other.itsFileWriteOption;
itsReadDataFromDatabase = other.itsReadDataFromDatabase;
itsFileWaitTimeout = other.itsFileWaitTimeout;
itsUseCuda = other.itsUseCuda;
itsLeadingDimension = other.itsLeadingDimension;
itsThreadCount = other.itsThreadCount;
itsGeomName = other.itsGeomName;
itsTargetProducer = other.itsTargetProducer;
itsSourceProducers = other.itsSourceProducers;
itsStatisticsLabel = other.itsStatisticsLabel;
itsLogger = std::unique_ptr<logger> (logger_factory::Instance()->GetLog("configuration"));
}
std::ostream& configuration::Write(std::ostream& file) const
{
file << "<" << ClassName() << " " << Version() << ">" << std::endl;
// file << "__itsSourceProducer__ " << itsSourceProducer << std::endl;
file << itsTargetProducer;
file << "__itsOutputFileType__ " << itsOutputFileType << std::endl;
file << "__itsFileWriteOption__ " << itsFileWriteOption << std::endl;
file << "__itsUseCuda__ " << itsUseCuda << std::endl;
file << "__itsFileWaitTimeout__ " << itsFileWaitTimeout << std::endl;
file << "__itsReadDataFromDatabase__ " << itsReadDataFromDatabase << std::endl;
file << "__itsLeadingDimension__ " << itsLeadingDimension << std::endl;
file << "__itsThreadCount__ " << itsThreadCount << std::endl;
file << "__itsGeomName__ " << itsGeomName << std::endl;
file << "__itsStatisticsLabel__ " << itsStatisticsLabel << std::endl;
file << "__itsConfigurationFile__ " << itsConfigurationFile << std::endl;
for (size_t i = 0; i < itsAuxiliaryFiles.size(); i++)
{
file << "__itsAuxiliaryFiles__ " << i << " " << itsAuxiliaryFiles[i] << std::endl;
}
return file;
}
std::vector<std::string> configuration::AuxiliaryFiles() const
{
return itsAuxiliaryFiles;
}
void configuration::AuxiliaryFiles(const std::vector<std::string>& theAuxiliaryFiles)
{
itsAuxiliaryFiles = theAuxiliaryFiles;
}
void configuration::Init()
{
itsOutputFileType = kQueryData;
itsFileWriteOption = kSingleFile;
itsReadDataFromDatabase = true;
itsUseCuda = true;
itsFileWaitTimeout = 0;
itsLeadingDimension = kTimeDimension;
itsThreadCount = -1;
itsGeomName = "";
}
HPFileType configuration::OutputFileType() const
{
return itsOutputFileType;
}
void configuration::OutputFileType(HPFileType theOutputFileType)
{
itsOutputFileType = theOutputFileType;
}
HPFileWriteOption configuration::FileWriteOption() const
{
return itsFileWriteOption;
}
void configuration::FileWriteOption(HPFileWriteOption theFileWriteOption)
{
itsFileWriteOption = theFileWriteOption;
}
bool configuration::ReadDataFromDatabase() const
{
return itsReadDataFromDatabase;
}
void configuration::ReadDataFromDatabase(bool theReadDataFromDatabase)
{
itsReadDataFromDatabase = theReadDataFromDatabase;
}
unsigned short configuration::FileWaitTimeout() const
{
return itsFileWaitTimeout;
}
void configuration::FileWaitTimeout(unsigned short theFileWaitTimeout)
{
itsFileWaitTimeout = theFileWaitTimeout;
}
bool configuration::UseCuda() const
{
return itsUseCuda;
}
void configuration::UseCuda(bool theUseCuda)
{
itsUseCuda = theUseCuda;
}
HPDimensionType configuration::LeadingDimension() const
{
return itsLeadingDimension;
}
short configuration::ThreadCount() const
{
return itsThreadCount;
}
void configuration::ThreadCount(short theThreadCount)
{
itsThreadCount = theThreadCount;
}
std::string configuration::ConfigurationFile() const
{
return itsConfigurationFile;
};
void configuration::ConfigurationFile(const std::string& theConfigurationFile)
{
itsConfigurationFile = theConfigurationFile;
}
void configuration::SourceProducers(const std::vector<producer> theSourceProducers)
{
itsSourceProducers = theSourceProducers;
}
void configuration::SourceProducer(const producer& theSourceProducer)
{
itsSourceProducers[0] = theSourceProducer;
}
std::vector<producer> configuration::SourceProducers() const
{
return itsSourceProducers;
}
producer configuration::TargetProducer() const
{
return itsTargetProducer;
}
void configuration::StatisticsLabel(const std::string& theStatisticsLabel)
{
itsStatisticsLabel = theStatisticsLabel;
}
std::string configuration::StatisticsLabel() const
{
return itsStatisticsLabel;
}
<commit_msg>Initialize configuration file name<commit_after>/**
* @file configuration.cpp
*
* @date Nov 26, 2012
* @author partio
*/
#include "configuration.h"
#include "logger_factory.h"
using namespace himan;
configuration::configuration()
{
Init();
itsLogger = std::unique_ptr<logger> (logger_factory::Instance()->GetLog("configuration"));
}
configuration::configuration(const configuration& other)
{
itsOutputFileType = other.itsOutputFileType;
itsConfigurationFile = other.itsConfigurationFile;
itsAuxiliaryFiles = other.itsAuxiliaryFiles;
itsOriginTime = other.itsOriginTime;
itsFileWriteOption = other.itsFileWriteOption;
itsReadDataFromDatabase = other.itsReadDataFromDatabase;
itsFileWaitTimeout = other.itsFileWaitTimeout;
itsUseCuda = other.itsUseCuda;
itsLeadingDimension = other.itsLeadingDimension;
itsThreadCount = other.itsThreadCount;
itsGeomName = other.itsGeomName;
itsTargetProducer = other.itsTargetProducer;
itsSourceProducers = other.itsSourceProducers;
itsStatisticsLabel = other.itsStatisticsLabel;
itsLogger = std::unique_ptr<logger> (logger_factory::Instance()->GetLog("configuration"));
}
std::ostream& configuration::Write(std::ostream& file) const
{
file << "<" << ClassName() << " " << Version() << ">" << std::endl;
// file << "__itsSourceProducer__ " << itsSourceProducer << std::endl;
file << itsTargetProducer;
file << "__itsOutputFileType__ " << itsOutputFileType << std::endl;
file << "__itsFileWriteOption__ " << itsFileWriteOption << std::endl;
file << "__itsUseCuda__ " << itsUseCuda << std::endl;
file << "__itsFileWaitTimeout__ " << itsFileWaitTimeout << std::endl;
file << "__itsReadDataFromDatabase__ " << itsReadDataFromDatabase << std::endl;
file << "__itsLeadingDimension__ " << itsLeadingDimension << std::endl;
file << "__itsThreadCount__ " << itsThreadCount << std::endl;
file << "__itsGeomName__ " << itsGeomName << std::endl;
file << "__itsStatisticsLabel__ " << itsStatisticsLabel << std::endl;
file << "__itsConfigurationFile__ " << itsConfigurationFile << std::endl;
for (size_t i = 0; i < itsAuxiliaryFiles.size(); i++)
{
file << "__itsAuxiliaryFiles__ " << i << " " << itsAuxiliaryFiles[i] << std::endl;
}
return file;
}
std::vector<std::string> configuration::AuxiliaryFiles() const
{
return itsAuxiliaryFiles;
}
void configuration::AuxiliaryFiles(const std::vector<std::string>& theAuxiliaryFiles)
{
itsAuxiliaryFiles = theAuxiliaryFiles;
}
void configuration::Init()
{
itsOutputFileType = kQueryData;
itsFileWriteOption = kSingleFile;
itsReadDataFromDatabase = true;
itsUseCuda = true;
itsFileWaitTimeout = 0;
itsLeadingDimension = kTimeDimension;
itsThreadCount = -1;
itsGeomName = "";
itsConfigurationFile = "";
}
HPFileType configuration::OutputFileType() const
{
return itsOutputFileType;
}
void configuration::OutputFileType(HPFileType theOutputFileType)
{
itsOutputFileType = theOutputFileType;
}
HPFileWriteOption configuration::FileWriteOption() const
{
return itsFileWriteOption;
}
void configuration::FileWriteOption(HPFileWriteOption theFileWriteOption)
{
itsFileWriteOption = theFileWriteOption;
}
bool configuration::ReadDataFromDatabase() const
{
return itsReadDataFromDatabase;
}
void configuration::ReadDataFromDatabase(bool theReadDataFromDatabase)
{
itsReadDataFromDatabase = theReadDataFromDatabase;
}
unsigned short configuration::FileWaitTimeout() const
{
return itsFileWaitTimeout;
}
void configuration::FileWaitTimeout(unsigned short theFileWaitTimeout)
{
itsFileWaitTimeout = theFileWaitTimeout;
}
bool configuration::UseCuda() const
{
return itsUseCuda;
}
void configuration::UseCuda(bool theUseCuda)
{
itsUseCuda = theUseCuda;
}
HPDimensionType configuration::LeadingDimension() const
{
return itsLeadingDimension;
}
short configuration::ThreadCount() const
{
return itsThreadCount;
}
void configuration::ThreadCount(short theThreadCount)
{
itsThreadCount = theThreadCount;
}
std::string configuration::ConfigurationFile() const
{
return itsConfigurationFile;
};
void configuration::ConfigurationFile(const std::string& theConfigurationFile)
{
itsConfigurationFile = theConfigurationFile;
}
void configuration::SourceProducers(const std::vector<producer> theSourceProducers)
{
itsSourceProducers = theSourceProducers;
}
void configuration::SourceProducer(const producer& theSourceProducer)
{
itsSourceProducers[0] = theSourceProducer;
}
std::vector<producer> configuration::SourceProducers() const
{
return itsSourceProducers;
}
producer configuration::TargetProducer() const
{
return itsTargetProducer;
}
void configuration::StatisticsLabel(const std::string& theStatisticsLabel)
{
itsStatisticsLabel = theStatisticsLabel;
}
std::string configuration::StatisticsLabel() const
{
return itsStatisticsLabel;
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2007, P.F.Peterson <petersonpf@ornl.gov>
* Spallation Neutron Source at Oak Ridge National Laboratory
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "nxsummary.hpp"
#include "string_util.hpp"
#include <algorithm>
#include <cctype>
#include <iostream>
#include <sstream>
#include <napi.h>
#include <stdexcept>
#include <string>
#include <vector>
#include "nxconfig.h"
#include "data_util.hpp"
// use STDINT if possible, otherwise define the types here
#ifdef HAVE_STDINT_H
#include <stdint.h>
#else
typedef signed char int8_t;
typedef short int int16_t;
typedef int int32_t;
typedef unsigned char uint8_t;
typedef unsigned short int uint16_t;
typedef unsigned int uint32_t;
#endif
using std::runtime_error;
using std::string;
using std::stringstream;
using std::vector;
namespace nxsum {
template <typename NumT>
string toString(const NumT thing) {
stringstream s;
s << thing;
return s.str();
}
// explicit instantiations so they get compiled in
template string toString<uint32_t>(const uint32_t thing);
template <typename NumT>
string toString(const NumT *data, const int dims[], const int rank) {
int num_ele = 1;
for (size_t i = 0; i < rank; ++i ) {
num_ele *= dims[i];
}
if (num_ele == 1)
{
return toString(data[0]);
}
else
{
throw runtime_error("Do not know how to work with arrays");
}
}
string toString(const void *data, const int dims[], const int rank,
const int type) {
if (type == NX_CHAR)
{
return (char *) data;
}
else if (type == NX_FLOAT32)
{
return toString((float *)data, dims, rank);
}
else if (type == NX_FLOAT64)
{
return toString((double *)data, dims, rank);
}
else
{
std::ostringstream s;
s << "Do not know how to work with type=" << nxtypeAsString(type);
throw runtime_error(s.str());
}
}
string toString(const void *data, const int length, const int type) {
int dims[1] = {length};
return toString(data, dims, 1, type);
}
string toUpperCase(const string &orig) {
string result = orig;
std::transform(orig.begin(), orig.end(), result.begin(), (int(*)(int))std::toupper);
return result;
}
}
<commit_msg>Added DIMS and COUNT operations. Refs #30.<commit_after>/*
* Copyright (c) 2007, P.F.Peterson <petersonpf@ornl.gov>
* Spallation Neutron Source at Oak Ridge National Laboratory
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "nxsummary.hpp"
#include "string_util.hpp"
#include <algorithm>
#include <cctype>
#include <iostream>
#include <sstream>
#include <napi.h>
#include <stdexcept>
#include <string>
#include <vector>
#include "nxconfig.h"
#include "data_util.hpp"
// use STDINT if possible, otherwise define the types here
#ifdef HAVE_STDINT_H
#include <stdint.h>
#else
typedef signed char int8_t;
typedef short int int16_t;
typedef int int32_t;
typedef unsigned char uint8_t;
typedef unsigned short int uint16_t;
typedef unsigned int uint32_t;
#endif
using std::runtime_error;
using std::string;
using std::ostringstream;
using std::vector;
static const size_t NX_MAX_RANK = 25;
namespace nxsum {
template <typename NumT>
string toString(const NumT thing) {
ostringstream s;
s << thing;
return s.str();
}
// explicit instantiations so they get compiled in
template string toString<uint32_t>(const uint32_t thing);
template string toString<int>(const int thing);
template <typename NumT>
string toString(const NumT *data, const int dims[], const int rank) {
int num_ele = 1;
for (size_t i = 0; i < rank; ++i ) {
num_ele *= dims[i];
}
if (num_ele == 1)
{
return toString(data[0]);
}
if ((rank == 1) && (num_ele < NX_MAX_RANK))
{
ostringstream s;
s << '[';
size_t length = dims[0];
for (size_t i = 0; i < length; ++i) {
s << toString(data[i]);
if (i+1 < length)
{
s << ',';
}
}
s << ']';
return s.str();
}
else
{
throw runtime_error("Do not know how to work with arrays");
}
}
string toString(const void *data, const int dims[], const int rank,
const int type) {
if (type == NX_CHAR)
{
return (char *) data;
}
else if (type == NX_FLOAT32)
{
return toString((float *)data, dims, rank);
}
else if (type == NX_FLOAT64)
{
return toString((double *)data, dims, rank);
}
else if (type == NX_INT32)
{
return toString((int32_t *)data, dims, rank);
}
else
{
ostringstream s;
s << "Do not know how to work with type=" << nxtypeAsString(type);
throw runtime_error(s.str());
}
}
string toString(const void *data, const int length, const int type) {
int dims[1] = {length};
return toString(data, dims, 1, type);
}
string toUpperCase(const string &orig) {
string result = orig;
std::transform(orig.begin(), orig.end(), result.begin(), (int(*)(int))std::toupper);
return result;
}
}
<|endoftext|>
|
<commit_before>/*
* Copyright 2011 Esrille Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "HTTPRequest.h"
#include <iostream>
#include <string>
#include "utf.h"
#include "url/URI.h"
#include "http/HTTPCache.h"
#include "http/HTTPConnection.h"
namespace org { namespace w3c { namespace dom { namespace bootstrap {
int HttpRequest::getContentDescriptor()
{
return fdContent; // TODO: call dup internally?
}
std::FILE* HttpRequest::openFile()
{
if (fdContent == -1)
return 0;
std::FILE* file = fdopen(dup(fdContent), "rb");
if (!file)
return 0;
rewind(file);
return file;
}
std::fstream& HttpRequest::getContent()
{
if (content.is_open())
return content;
char filename[] = "/tmp/esXXXXXX";
fdContent = mkstemp(filename);
if (fdContent == -1)
return content;
content.open(filename, std::ios_base::trunc | std::ios_base::in | std::ios_base::out | std::ios::binary);
remove(filename);
return content;
}
void HttpRequest::notify(bool error)
{
readyState = DONE;
errorFlag = error;
if (!cache)
return;
cache->notify(this, error);
if (handler)
handler();
}
void HttpRequest::open(const std::u16string& method, const std::u16string& urlString)
{
URL url(base, urlString);
request.open(utfconv(method), url);
readyState = OPENED;
}
void HttpRequest::setRequestHeader(const std::u16string& header, const std::u16string& value)
{
request.setHeader(utfconv(header), utfconv(value));
}
void HttpRequest::constructResponseFromCache()
{
readyState = DONE;
errorFlag = false;
response.update(cache->getResponseMessage());
// TODO: deal with partial...
int fd = cache->getContentDescriptor();
if (0 <= fd)
fdContent = dup(fd);
if (handler)
handler();
}
void HttpRequest::send()
{
if (request.getURL().isEmpty()) {
abort();
return;
}
cache = HttpCacheManager::getInstance().send(this);
if (!cache || cache->isBusy())
return;
constructResponseFromCache();
}
void HttpRequest::abort()
{
// TODO: implement more details.
clearHanndler();
if (cache)
cache->abort(this);
else {
HttpConnectionManager& manager = HttpConnectionManager::getInstance();
manager.abort(this);
}
readyState = UNSENT;
errorFlag = false;
request.clear();
response.clear();
if (content.is_open())
content.close();
if (0 <= fdContent) {
close(fdContent);
fdContent = -1;
}
}
unsigned short HttpRequest::getStatus() const
{
return response.getStatus();
}
const std::string& HttpRequest::getStatusText() const
{
return response.getStatusText();
}
const std::string HttpRequest::getResponseHeader(std::u16string header) const
{
return response.getResponseHeader(utfconv(header));
}
const std::string& HttpRequest::getAllResponseHeaders() const
{
return response.getAllResponseHeaders();
}
HttpRequest::HttpRequest(const std::u16string& base) :
base(base),
readyState(UNSENT),
errorFlag(false),
fdContent(-1),
cache(0)
{
}
HttpRequest::~HttpRequest()
{
abort();
}
}}}} // org::w3c::dom::bootstrap
<commit_msg>(HttpRequest) : Refine.<commit_after>/*
* Copyright 2011 Esrille Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "HTTPRequest.h"
#include <iostream>
#include <string>
#include "utf.h"
#include "url/URI.h"
#include "http/HTTPCache.h"
#include "http/HTTPConnection.h"
namespace org { namespace w3c { namespace dom { namespace bootstrap {
int HttpRequest::getContentDescriptor()
{
return fdContent; // TODO: call dup internally?
}
std::FILE* HttpRequest::openFile()
{
if (fdContent == -1)
return 0;
std::FILE* file = fdopen(dup(fdContent), "rb");
if (!file)
return 0;
rewind(file);
return file;
}
std::fstream& HttpRequest::getContent()
{
if (content.is_open())
return content;
char filename[] = "/tmp/esXXXXXX";
fdContent = mkstemp(filename);
if (fdContent == -1)
return content;
content.open(filename, std::ios_base::trunc | std::ios_base::in | std::ios_base::out | std::ios::binary);
remove(filename);
return content;
}
void HttpRequest::notify(bool error)
{
readyState = DONE;
errorFlag = error;
if (cache)
cache->notify(this, error);
if (handler)
handler();
}
void HttpRequest::open(const std::u16string& method, const std::u16string& urlString)
{
URL url(base, urlString);
request.open(utfconv(method), url);
readyState = OPENED;
}
void HttpRequest::setRequestHeader(const std::u16string& header, const std::u16string& value)
{
request.setHeader(utfconv(header), utfconv(value));
}
void HttpRequest::constructResponseFromCache()
{
readyState = DONE;
errorFlag = false;
response.update(cache->getResponseMessage());
// TODO: deal with partial...
int fd = cache->getContentDescriptor();
if (0 <= fd)
fdContent = dup(fd);
if (handler)
handler();
}
void HttpRequest::send()
{
if (request.getURL().isEmpty()) {
readyState = DONE;
if (handler)
handler();
return;
}
cache = HttpCacheManager::getInstance().send(this);
if (!cache || cache->isBusy())
return;
constructResponseFromCache();
}
void HttpRequest::abort()
{
if (readyState == UNSENT)
return;
// TODO: implement more details.
clearHanndler();
if (cache)
cache->abort(this);
else {
HttpConnectionManager& manager = HttpConnectionManager::getInstance();
manager.abort(this);
}
readyState = UNSENT;
errorFlag = false;
request.clear();
response.clear();
if (content.is_open())
content.close();
if (0 <= fdContent) {
close(fdContent);
fdContent = -1;
}
}
unsigned short HttpRequest::getStatus() const
{
return response.getStatus();
}
const std::string& HttpRequest::getStatusText() const
{
return response.getStatusText();
}
const std::string HttpRequest::getResponseHeader(std::u16string header) const
{
return response.getResponseHeader(utfconv(header));
}
const std::string& HttpRequest::getAllResponseHeaders() const
{
return response.getAllResponseHeaders();
}
HttpRequest::HttpRequest(const std::u16string& base) :
base(base),
readyState(UNSENT),
errorFlag(false),
fdContent(-1),
cache(0)
{
}
HttpRequest::~HttpRequest()
{
abort();
}
}}}} // org::w3c::dom::bootstrap
<|endoftext|>
|
<commit_before>/*
* InteractionVote.cpp
* Render
*
* Created by Todd Vanderlin on 3/6/11.
* Copyright 2011 Interactive Design. All rights reserved.
*
*/
#include "InteractionVote.h"
#include "testApp.h"
#include "InteractionPerformance.h"
#include "QuestionData.h"
void InteractionVote::setup() {
voteBubbles[0] = NULL;
voteBubbles[1] = NULL;
bMadeVoteBubbles = false;
pctA = 0;
pctB = 0;
for (int i=0; i<100; i++) {
voteIds[i] = 0;
}
}
//--------------------------------------------------------
void InteractionVote::setVoteBubble(int i, string choice) {
float radius = 190;
ofVec3f center(interactiveRect.width/2, 0, 0);
ofVec3f startPos(center.x + ofRandom(-300, 300), interactiveRect.height, ofRandom(-100, 100));
ofVec3f target(i==0?center.x-300:center.x+500, interactiveRect.height/2, 0);
if(voteBubbles[i] == NULL) {
voteBubbles[i] = new VoteBubble();
voteBubbles[i]->data = NULL;
voteBubbles[i]->radius = radius;
voteBubbles[i]->startRadius = radius;
voteBubbles[i]->maxRadius = radius;
voteBubbles[i]->rigidBody = bullet->createSphere(startPos, radius, 1);
voteBubbles[i]->createContentBubble();
voteBubbles[i]->setTarget(target.x, target.y, target.z);
voteBubbles[i]->setOptionString(choice);
}
voteBubbles[i]->setOptionString(choice);
if(voteBubbles[0] != NULL && voteBubbles[1] != NULL) {
bMadeVoteBubbles = true;
}
}
//--------------------------------------------------------
ContentBubble * InteractionVote::addBubbleToVote(int voteID) {
float radius = ofRandom(20, 40);
ofVec3f center(interactiveRect.width/2, 0, 0);
ofVec3f startPos;
startPos.x = (int)ofRandom(0,2) ? -ofRandom(-300, -200) : interactiveRect.width+ofRandom(-300, -200);
startPos.y = (int)ofRandom(0,2) ? -ofRandom(-300, -200) : interactiveRect.height+ofRandom(-300, -200);
startPos.z = ofRandom(-300, 300);
ContentBubble * bubble = new ContentBubble();
bubble->voteBubbleID = voteID;
bubble->data = NULL;
bubble->radius = radius;
bubble->rigidBody = bullet->createSphere(startPos, radius, 1);
bubble->bVoteEnabled = false;
bubble->voteTimer = 0;
bubble->voteDelay = 0;
bubble->bVoteNeedsUpdate = false;
bubble->createContentBubble();
//bubble->setTarget( voteBubbles[voteID]->getPosition() );
bubbles.push_back(bubble);
return bubbles.back();
// voteBubbles[voteID]->totalVotes ++;
}
//--------------------------------------------------------
void InteractionVote::newBubbleRecieved(Donk::BubbleData * data) {
}
//--------------------------------------------------------
void InteractionVote::setVoteCount(int totalA, int totalB) {
if(bAnimateOut) return;
///int totalA = Donk::QuestionData::all[data->questionID].tag_counts[0];
///int totalB = Donk::QuestionData::all[data->questionID].tag_counts[1];
///string optA = Donk::QuestionData::all[data->questionID].tags[0];
///string optB = Donk::QuestionData::all[data->questionID].tags[1];
int total = totalA + totalB;
pctA = round( ((float)totalA / (float)total) * 100.0);
pctB = round( ((float)totalB / (float)total) * 100.0);
if(pctA == voteBubbles[0]->pct && pctB == voteBubbles[1]->pct) {
printf("no need to update\n");
return;
}
// Option A
if(voteBubbles[0] != NULL) voteBubbles[0]->pctDes = pctA;
// Option B
if(voteBubbles[1] != NULL) voteBubbles[1]->pctDes = pctB;
// the first time we are going to make the
// bubbles they will not be active...
if(bubbles.size() < 100) {
InteractionPerformance * interaction = (InteractionPerformance*)testApp::instance->projection->getInteraction(MODE_PERFORMANCE);
for (int i=0; i<100; i++) {
ContentBubble * bubble = addBubbleToVote(0); // 0 for initial setting
if(interaction != NULL) bubble->voteImageID = MIN(i, interaction->images.size()-1);
else bubble->voteImageID = -1;
}
printf("just made %i bubbles!\n", (int)bubbles.size());
}
printf("A:%i\nB:%i\nT:%i\n", pctA, pctB, pctA+pctB);
// now loop through all the bubbles and set them to
// the vote bubble that they should be on...
int incA = 0;
int incB = 0;
for (int i=0; i<100; i++) {
ContentBubble * bubble = bubbles[i];
if(incA < pctA) {
bubble->setTarget( voteBubbles[0]->getPosition() );
bubble->bVoteEnabled = true;
//bubble->voteBubbleID = 0;
incA ++;
voteIds[i] = 0;
}
if(incA == pctA && incB < pctB) {
bubble->setTarget( voteBubbles[1]->getPosition() );
bubble->bVoteEnabled = true;
//bubble->voteBubbleID = 1;
incB ++;
voteIds[i] = 1;
}
bubble->voteDelay = ofRandom(0.5, 2.0);
bubble->voteTimer = ofGetElapsedTimeMillis();
bubble->bVoteNeedsUpdate = true;
}
printf("pctA:%i - %i\n", pctA, incA);
printf("pctB:%i - %i\n", pctB, incB);
};
//--------------------------------------------------------
void InteractionVote::update() {
if(bAnimateOut) {
bool bAllOffscreen = true;
for(int i=0; i<bubbles.size(); i++) {
if(bubbles[i]->getPosition().y > 0) {
bAllOffscreen = false;
}
}
// we are down and ready tp remove all the bubbles...
float time = (ofGetElapsedTimeMillis() - animatedOutTimer) / 1000.0;
if(bAllOffscreen && !bDoneAnimatingOut || time > MAX_ANIMATION_TIME) {
killallBubbles();
for (int i=0; i<2; i++) {
if(voteBubbles[i]) {
voteBubbles[i]->rigidBody->destroy();
delete voteBubbles[i];
voteBubbles[i] = NULL;
}
}
bDoneAnimatingOut = true;
printf("all done in vote remove it all\n");
}
}
for(int i=0; i<bubbles.size(); i++) {
if(bAnimateOut) {
bubbles[i]->gotoTarget();
bubbles[i]->update();
}
else {
float time = (ofGetElapsedTimeMillis() - bubbles[i]->voteTimer) / 1000.0;
if(time > bubbles[i]->voteDelay && bubbles[i]->bVoteNeedsUpdate) {
bubbles[i]->voteBubbleID = voteIds[i];
bubbles[i]->bVoteNeedsUpdate = false;
}
if(bubbles[i]->bVoteEnabled) {
int voteID = bubbles[i]->voteBubbleID;
if(voteID != -1) {
ofVec3f pos = voteBubbles[ voteID ]->getPosition();
pos.z -= 130;
bubbles[i]->setTarget( pos );
}
bubbles[i]->rigidBody->body->setDamping(0.999, 0.999); // <-- add some crazy damping
bubbles[i]->gotoTarget(1.0);
bubbles[i]->update();
}
}
}
for (int i=0; i<2; i++) {
if(!voteBubbles[i]) continue;
if(bAnimateOut) {
voteBubbles[i]->gotoTarget();
voteBubbles[i]->update();
}
else {
voteBubbles[i]->rigidBody->body->setDamping(0.999, 0.999); // <-- add some crazy damping
voteBubbles[i]->gotoTarget(50.0);
voteBubbles[i]->bobMe();
voteBubbles[i]->update();
}
}
}
//--------------------------------------------------------
void InteractionVote::drawContent() {
ofEnableAlphaBlending();
for(int i=0; i<2; i++) {
if(voteBubbles[i]) voteBubbles[i]->drawInsideContent();
}
InteractionPerformance * interaction = (InteractionPerformance*)testApp::instance->projection->getInteraction(MODE_PERFORMANCE);
ofSetColor(255, 255, 255);
for(int i=0; i<bubbles.size(); i++) {
if(bubbles[i]->bVoteEnabled) {
ofEnableAlphaBlending();
// bubbles[i]->drawHighLight();
// bubbles[i]->drawTwitterData();
if( bubbles[i]->voteImageID != -1) {
bubbles[i]->pushBillboard();
int w = bubbles[i]->radius * 2;
ofSetRectMode(OF_RECTMODE_CENTER);
interaction->images[ bubbles[i]->voteImageID ].draw(0, 0, w, w);
ofSetRectMode(OF_RECTMODE_CORNER);
bubbles[i]->popBillboard();
}
}
}
}
//--------------------------------------------------------
void InteractionVote::drawSphere(BubbleShader * shader) {
for (int i=0; i<2; i++) {
if(!voteBubbles[i]) continue;
voteBubbles[i]->pushBubble();
shader->begin();
voteBubbles[i]->draw();
shader->end();
voteBubbles[i]->popBubble();
}
for(int i=0; i<bubbles.size(); i++) {
bubbles[i]->pushBubble();
shader->begin();
bubbles[i]->draw();
shader->end();
bubbles[i]->popBubble();
}
}
//--------------------------------------------------------
void InteractionVote::animatedOut() {
for(int i=0; i<bubbles.size(); i++) {
ofVec3f offScreenPos;
offScreenPos.x = bubbles[i]->getPosition().x;
offScreenPos.y = ofRandom(-400, -500);
offScreenPos.z = ofRandom(-100, -400);
bubbles[i]->setTarget(offScreenPos);
}
if(voteBubbles[0]) voteBubbles[0]->setTarget(-500, voteBubbles[0]->getPosition().y);
if(voteBubbles[1]) voteBubbles[1]->setTarget(interactiveRect.width+500, voteBubbles[1]->getPosition().y);
bAnimateOut = true;
bDoneAnimatingOut = false;
animatedOutTimer = ofGetElapsedTimeMillis();
}
//--------------------------------------------------------
void InteractionVote::animatedIn() {
bAnimateOut = false;
bDoneAnimatingOut = false;
printf("--- Vote Animate In ---\n");
}
<commit_msg>fixed the Vote Funky Alpha Bug!<commit_after>/*
* InteractionVote.cpp
* Render
*
* Created by Todd Vanderlin on 3/6/11.
* Copyright 2011 Interactive Design. All rights reserved.
*
*/
#include "InteractionVote.h"
#include "testApp.h"
#include "InteractionPerformance.h"
#include "QuestionData.h"
void InteractionVote::setup() {
voteBubbles[0] = NULL;
voteBubbles[1] = NULL;
bMadeVoteBubbles = false;
pctA = 0;
pctB = 0;
for (int i=0; i<100; i++) {
voteIds[i] = 0;
}
}
//--------------------------------------------------------
void InteractionVote::setVoteBubble(int i, string choice) {
float radius = 190;
ofVec3f center(interactiveRect.width/2, 0, 0);
ofVec3f startPos(center.x + ofRandom(-300, 300), interactiveRect.height, ofRandom(-100, 100));
ofVec3f target(i==0?center.x-300:center.x+500, interactiveRect.height/2, 0);
if(voteBubbles[i] == NULL) {
voteBubbles[i] = new VoteBubble();
voteBubbles[i]->data = NULL;
voteBubbles[i]->radius = radius;
voteBubbles[i]->startRadius = radius;
voteBubbles[i]->maxRadius = radius;
voteBubbles[i]->rigidBody = bullet->createSphere(startPos, radius, 1);
voteBubbles[i]->createContentBubble();
voteBubbles[i]->setTarget(target.x, target.y, target.z);
voteBubbles[i]->setOptionString(choice);
}
voteBubbles[i]->setOptionString(choice);
if(voteBubbles[0] != NULL && voteBubbles[1] != NULL) {
bMadeVoteBubbles = true;
}
}
//--------------------------------------------------------
ContentBubble * InteractionVote::addBubbleToVote(int voteID) {
float radius = ofRandom(20, 40);
ofVec3f center(interactiveRect.width/2, 0, 0);
ofVec3f startPos;
startPos.x = (int)ofRandom(0,2) ? -ofRandom(-300, -200) : interactiveRect.width+ofRandom(-300, -200);
startPos.y = (int)ofRandom(0,2) ? -ofRandom(-300, -200) : interactiveRect.height+ofRandom(-300, -200);
startPos.z = ofRandom(-300, 300);
ContentBubble * bubble = new ContentBubble();
bubble->voteBubbleID = voteID;
bubble->data = NULL;
bubble->radius = radius;
bubble->rigidBody = bullet->createSphere(startPos, radius, 1);
bubble->bVoteEnabled = false;
bubble->voteTimer = 0;
bubble->voteDelay = 0;
bubble->bVoteNeedsUpdate = false;
bubble->createContentBubble();
//bubble->setTarget( voteBubbles[voteID]->getPosition() );
bubbles.push_back(bubble);
return bubbles.back();
// voteBubbles[voteID]->totalVotes ++;
}
//--------------------------------------------------------
void InteractionVote::newBubbleRecieved(Donk::BubbleData * data) {
}
//--------------------------------------------------------
void InteractionVote::setVoteCount(int totalA, int totalB) {
if(bAnimateOut) return;
///int totalA = Donk::QuestionData::all[data->questionID].tag_counts[0];
///int totalB = Donk::QuestionData::all[data->questionID].tag_counts[1];
///string optA = Donk::QuestionData::all[data->questionID].tags[0];
///string optB = Donk::QuestionData::all[data->questionID].tags[1];
int total = totalA + totalB;
pctA = round( ((float)totalA / (float)total) * 100.0);
pctB = round( ((float)totalB / (float)total) * 100.0);
if(pctA == voteBubbles[0]->pct && pctB == voteBubbles[1]->pct) {
printf("no need to update\n");
return;
}
// Option A
if(voteBubbles[0] != NULL) voteBubbles[0]->pctDes = pctA;
// Option B
if(voteBubbles[1] != NULL) voteBubbles[1]->pctDes = pctB;
// the first time we are going to make the
// bubbles they will not be active...
if(bubbles.size() < 100) {
InteractionPerformance * interaction = (InteractionPerformance*)testApp::instance->projection->getInteraction(MODE_PERFORMANCE);
for (int i=0; i<100; i++) {
ContentBubble * bubble = addBubbleToVote(0); // 0 for initial setting
if(interaction != NULL) bubble->voteImageID = MIN(i, interaction->images.size()-1);
else bubble->voteImageID = -1;
}
printf("just made %i bubbles!\n", (int)bubbles.size());
}
printf("A:%i\nB:%i\nT:%i\n", pctA, pctB, pctA+pctB);
// now loop through all the bubbles and set them to
// the vote bubble that they should be on...
int incA = 0;
int incB = 0;
for (int i=0; i<100; i++) {
ContentBubble * bubble = bubbles[i];
if(incA < pctA) {
bubble->setTarget( voteBubbles[0]->getPosition() );
bubble->bVoteEnabled = true;
//bubble->voteBubbleID = 0;
incA ++;
voteIds[i] = 0;
}
if(incA == pctA && incB < pctB) {
bubble->setTarget( voteBubbles[1]->getPosition() );
bubble->bVoteEnabled = true;
//bubble->voteBubbleID = 1;
incB ++;
voteIds[i] = 1;
}
bubble->voteDelay = ofRandom(0.5, 2.0);
bubble->voteTimer = ofGetElapsedTimeMillis();
bubble->bVoteNeedsUpdate = true;
}
printf("pctA:%i - %i\n", pctA, incA);
printf("pctB:%i - %i\n", pctB, incB);
};
//--------------------------------------------------------
void InteractionVote::update() {
if(bAnimateOut) {
bool bAllOffscreen = true;
for(int i=0; i<bubbles.size(); i++) {
if(bubbles[i]->getPosition().y > 0) {
bAllOffscreen = false;
}
}
// we are down and ready tp remove all the bubbles...
float time = (ofGetElapsedTimeMillis() - animatedOutTimer) / 1000.0;
if(bAllOffscreen && !bDoneAnimatingOut || time > MAX_ANIMATION_TIME) {
killallBubbles();
for (int i=0; i<2; i++) {
if(voteBubbles[i]) {
voteBubbles[i]->rigidBody->destroy();
delete voteBubbles[i];
voteBubbles[i] = NULL;
}
}
bDoneAnimatingOut = true;
printf("all done in vote remove it all\n");
}
}
for(int i=0; i<bubbles.size(); i++) {
if(bAnimateOut) {
bubbles[i]->gotoTarget();
bubbles[i]->update();
}
else {
float time = (ofGetElapsedTimeMillis() - bubbles[i]->voteTimer) / 1000.0;
if(time > bubbles[i]->voteDelay && bubbles[i]->bVoteNeedsUpdate) {
bubbles[i]->voteBubbleID = voteIds[i];
bubbles[i]->bVoteNeedsUpdate = false;
}
if(bubbles[i]->bVoteEnabled) {
int voteID = bubbles[i]->voteBubbleID;
if(voteID != -1) {
ofVec3f pos = voteBubbles[ voteID ]->getPosition();
pos.z -= 130;
bubbles[i]->setTarget( pos );
}
bubbles[i]->rigidBody->body->setDamping(0.999, 0.999); // <-- add some crazy damping
bubbles[i]->gotoTarget(1.0);
bubbles[i]->update();
}
}
}
for (int i=0; i<2; i++) {
if(!voteBubbles[i]) continue;
if(bAnimateOut) {
voteBubbles[i]->gotoTarget();
voteBubbles[i]->update();
}
else {
voteBubbles[i]->rigidBody->body->setDamping(0.999, 0.999); // <-- add some crazy damping
voteBubbles[i]->gotoTarget(50.0);
voteBubbles[i]->bobMe();
voteBubbles[i]->update();
}
}
}
//--------------------------------------------------------
void InteractionVote::drawContent() {
ofEnableAlphaBlending();
InteractionPerformance * interaction = (InteractionPerformance*)testApp::instance->projection->getInteraction(MODE_PERFORMANCE);
ofSetColor(255, 255, 255);
for(int i=0; i<bubbles.size(); i++) {
if(bubbles[i]->bVoteEnabled) {
ofEnableAlphaBlending();
// bubbles[i]->drawHighLight();
// bubbles[i]->drawTwitterData();
if( bubbles[i]->voteImageID != -1) {
bubbles[i]->pushBillboard();
int w = bubbles[i]->radius * 2;
ofSetRectMode(OF_RECTMODE_CENTER);
interaction->images[ bubbles[i]->voteImageID ].draw(0, 0, w, w);
ofSetRectMode(OF_RECTMODE_CORNER);
bubbles[i]->popBillboard();
}
}
}
for(int i=0; i<2; i++) {
if(voteBubbles[i]) {
voteBubbles[i]->drawInsideContent();
}
}
}
//--------------------------------------------------------
void InteractionVote::drawSphere(BubbleShader * shader) {
for (int i=0; i<2; i++) {
if(!voteBubbles[i]) continue;
voteBubbles[i]->pushBubble();
shader->begin();
voteBubbles[i]->draw();
shader->end();
voteBubbles[i]->popBubble();
}
for(int i=0; i<bubbles.size(); i++) {
bubbles[i]->pushBubble();
shader->begin();
bubbles[i]->draw();
shader->end();
bubbles[i]->popBubble();
}
}
//--------------------------------------------------------
void InteractionVote::animatedOut() {
for(int i=0; i<bubbles.size(); i++) {
ofVec3f offScreenPos;
offScreenPos.x = bubbles[i]->getPosition().x;
offScreenPos.y = ofRandom(-400, -500);
offScreenPos.z = ofRandom(-100, -400);
bubbles[i]->setTarget(offScreenPos);
}
if(voteBubbles[0]) voteBubbles[0]->setTarget(-500, voteBubbles[0]->getPosition().y);
if(voteBubbles[1]) voteBubbles[1]->setTarget(interactiveRect.width+500, voteBubbles[1]->getPosition().y);
bAnimateOut = true;
bDoneAnimatingOut = false;
animatedOutTimer = ofGetElapsedTimeMillis();
}
//--------------------------------------------------------
void InteractionVote::animatedIn() {
bAnimateOut = false;
bDoneAnimatingOut = false;
printf("--- Vote Animate In ---\n");
}
<|endoftext|>
|
<commit_before>
//
// This source file is part of appleseed.
// Visit https://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2018 Esteban Tovagliari, The appleseedhq Organization
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// appleseed.foundation headers.
#include "foundation/array/algorithm.h"
#include "foundation/array/arraytraits.h"
#include "foundation/platform/types.h"
// Standard headers.
#include <algorithm>
namespace foundation
{
namespace
{
template <typename SrcType, typename DstType>
void convert_array(Array& array)
{
Array tmp(ArrayTraits<DstType>::array_type());
tmp.reserve(array.size());
ArrayView<SrcType> src(array);
ArrayRef<DstType> dst(tmp);
std::copy(src.begin(), src.end(), std::back_inserter(dst));
array = std::move(tmp);
}
}
void convert_to_smallest_type(Array& array)
{
if (array.empty())
return;
switch (array.type())
{
case UInt16Type:
{
const ArrayView<uint16> view(array);
const uint16 max_element = *std::max_element(view.begin(), view.end());
if (max_element <= std::numeric_limits<uint8>::max())
convert_array<uint16, uint8>(array);
}
break;
case UInt32Type:
{
const ArrayView<uint32> view(array);
const uint32 max_element = *std::max_element(view.begin(), view.end());
if (max_element <= std::numeric_limits<uint8>::max())
convert_array<uint32, uint8>(array);
else if (max_element <= std::numeric_limits<uint16>::max())
convert_array<uint32, uint16>(array);
}
break;
default:
break;
}
}
} // namespace foundation
<commit_msg>Fix VC++ warning<commit_after>
//
// This source file is part of appleseed.
// Visit https://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2018 Esteban Tovagliari, The appleseedhq Organization
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// appleseed.foundation headers.
#include "foundation/array/algorithm.h"
#include "foundation/array/arraytraits.h"
#include "foundation/platform/types.h"
// Standard headers.
#include <algorithm>
namespace foundation
{
namespace
{
template <typename SrcType, typename DstType>
void convert_array(Array& array)
{
Array tmp(ArrayTraits<DstType>::array_type());
tmp.reserve(array.size());
ArrayView<SrcType> src(array);
ArrayRef<DstType> dst(tmp);
for (const auto value : src)
dst.push_back(static_cast<DstType>(value));
array = std::move(tmp);
}
}
void convert_to_smallest_type(Array& array)
{
if (array.empty())
return;
switch (array.type())
{
case UInt16Type:
{
const ArrayView<uint16> view(array);
const uint16 max_element = *std::max_element(view.begin(), view.end());
if (max_element <= std::numeric_limits<uint8>::max())
convert_array<uint16, uint8>(array);
}
break;
case UInt32Type:
{
const ArrayView<uint32> view(array);
const uint32 max_element = *std::max_element(view.begin(), view.end());
if (max_element <= std::numeric_limits<uint8>::max())
convert_array<uint32, uint8>(array);
else if (max_element <= std::numeric_limits<uint16>::max())
convert_array<uint32, uint16>(array);
}
break;
default:
break;
}
}
} // namespace foundation
<|endoftext|>
|
<commit_before>//===--- CommentBriefParser.cpp - Dumb comment parser ---------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "clang/AST/CommentBriefParser.h"
#include "llvm/ADT/StringSwitch.h"
namespace clang {
namespace comments {
namespace {
/// Convert all whitespace into spaces, remove leading and trailing spaces,
/// compress multiple spaces into one.
void cleanupBrief(std::string &S) {
bool PrevWasSpace = true;
std::string::iterator O = S.begin();
for (std::string::iterator I = S.begin(), E = S.end();
I != E; ++I) {
const char C = *I;
if (C == ' ' || C == '\n' || C == '\r' ||
C == '\t' || C == '\v' || C == '\f') {
if (!PrevWasSpace) {
*O++ = ' ';
PrevWasSpace = true;
}
continue;
} else {
*O++ = C;
PrevWasSpace = false;
}
}
if (O != S.begin() && *(O - 1) == ' ')
--O;
S.resize(O - S.begin());
}
bool isBlockCommand(StringRef Name) {
return llvm::StringSwitch<bool>(Name)
.Case("brief", true)
.Case("result", true)
.Case("return", true)
.Case("returns", true)
.Case("author", true)
.Case("authors", true)
.Case("pre", true)
.Case("post", true)
.Case("param", true)
.Case("arg", true)
.Default(false);
}
} // unnamed namespace
std::string BriefParser::Parse() {
std::string Paragraph;
bool InFirstParagraph = true;
bool InBrief = false;
while (Tok.isNot(tok::eof)) {
if (Tok.is(tok::text)) {
if (InFirstParagraph || InBrief)
Paragraph += Tok.getText();
ConsumeToken();
continue;
}
if (Tok.is(tok::command)) {
StringRef Name = Tok.getCommandName();
if (Name == "brief") {
Paragraph.clear();
InBrief = true;
ConsumeToken();
continue;
}
// Block commands implicitly start a new paragraph.
if (isBlockCommand(Name)) {
// We found an implicit paragraph end.
InFirstParagraph = false;
if (InBrief) {
InBrief = false;
break;
}
}
}
if (Tok.is(tok::newline)) {
if (InFirstParagraph || InBrief)
Paragraph += ' ';
ConsumeToken();
if (Tok.is(tok::newline)) {
ConsumeToken();
// We found a paragraph end.
InFirstParagraph = false;
if (InBrief) {
InBrief = false;
break;
}
}
continue;
}
// We didn't handle this token, so just drop it.
ConsumeToken();
}
cleanupBrief(Paragraph);
return Paragraph;
}
BriefParser::BriefParser(Lexer &L) : L(L)
{
// Get lookahead token.
ConsumeToken();
}
} // end namespace comments
} // end namespace clang
<commit_msg>CommentBriefParser: remove dead store. Found by Clang Analyzer.<commit_after>//===--- CommentBriefParser.cpp - Dumb comment parser ---------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "clang/AST/CommentBriefParser.h"
#include "llvm/ADT/StringSwitch.h"
namespace clang {
namespace comments {
namespace {
/// Convert all whitespace into spaces, remove leading and trailing spaces,
/// compress multiple spaces into one.
void cleanupBrief(std::string &S) {
bool PrevWasSpace = true;
std::string::iterator O = S.begin();
for (std::string::iterator I = S.begin(), E = S.end();
I != E; ++I) {
const char C = *I;
if (C == ' ' || C == '\n' || C == '\r' ||
C == '\t' || C == '\v' || C == '\f') {
if (!PrevWasSpace) {
*O++ = ' ';
PrevWasSpace = true;
}
continue;
} else {
*O++ = C;
PrevWasSpace = false;
}
}
if (O != S.begin() && *(O - 1) == ' ')
--O;
S.resize(O - S.begin());
}
bool isBlockCommand(StringRef Name) {
return llvm::StringSwitch<bool>(Name)
.Case("brief", true)
.Case("result", true)
.Case("return", true)
.Case("returns", true)
.Case("author", true)
.Case("authors", true)
.Case("pre", true)
.Case("post", true)
.Case("param", true)
.Case("arg", true)
.Default(false);
}
} // unnamed namespace
std::string BriefParser::Parse() {
std::string Paragraph;
bool InFirstParagraph = true;
bool InBrief = false;
while (Tok.isNot(tok::eof)) {
if (Tok.is(tok::text)) {
if (InFirstParagraph || InBrief)
Paragraph += Tok.getText();
ConsumeToken();
continue;
}
if (Tok.is(tok::command)) {
StringRef Name = Tok.getCommandName();
if (Name == "brief") {
Paragraph.clear();
InBrief = true;
ConsumeToken();
continue;
}
// Block commands implicitly start a new paragraph.
if (isBlockCommand(Name)) {
// We found an implicit paragraph end.
InFirstParagraph = false;
if (InBrief)
break;
}
}
if (Tok.is(tok::newline)) {
if (InFirstParagraph || InBrief)
Paragraph += ' ';
ConsumeToken();
if (Tok.is(tok::newline)) {
ConsumeToken();
// We found a paragraph end.
InFirstParagraph = false;
if (InBrief)
break;
}
continue;
}
// We didn't handle this token, so just drop it.
ConsumeToken();
}
cleanupBrief(Paragraph);
return Paragraph;
}
BriefParser::BriefParser(Lexer &L) : L(L)
{
// Get lookahead token.
ConsumeToken();
}
} // end namespace comments
} // end namespace clang
<|endoftext|>
|
<commit_before>/******************************************************************************
* SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1 *
* (c) 2006-2011 INRIA, USTL, UJF, CNRS, MGH *
* *
* 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. *
*******************************************************************************
* SOFA :: Framework *
* *
* Authors: The SOFA Team (see Authors.txt) *
* *
* Contact information: contact@sofa-framework.org *
******************************************************************************/
#include <sofa/helper/system/PluginManager.h>
#include <sofa/helper/system/FileRepository.h>
#include <sofa/helper/system/SetDirectory.h>
#include <fstream>
namespace sofa
{
namespace helper
{
namespace system
{
namespace
{
#ifdef NDEBUG
const std::string pluginsIniFile = "share/config/sofaplugins_release.ini";
#else
const std::string pluginsIniFile = "share/config/sofaplugins_debug.ini";
#endif
template <class LibraryEntry>
bool getPluginEntry(LibraryEntry& entry, DynamicLibrary::Handle handle)
{
typedef typename LibraryEntry::FuncPtr FuncPtr;
entry.func = (FuncPtr)DynamicLibrary::getSymbolAddress(handle, entry.symbol);
if( entry.func == 0 )
{
return false;
}
else
{
return true;
}
}
} // namespace
const char* Plugin::GetModuleComponentList::symbol = "getModuleComponentList";
const char* Plugin::InitExternalModule::symbol = "initExternalModule";
const char* Plugin::GetModuleDescription::symbol = "getModuleDescription";
const char* Plugin::GetModuleLicense::symbol = "getModuleLicense";
const char* Plugin::GetModuleName::symbol = "getModuleName";
const char* Plugin::GetModuleVersion::symbol = "getModuleVersion";
PluginManager & PluginManager::getInstance()
{
static PluginManager instance;
return instance;
}
PluginManager::~PluginManager()
{
// BUGFIX: writeToIniFile should not be called here as it will erase the file in case it was not loaded
// Instead we write the file each time a change have been made in the GUI and should be saved
//writeToIniFile();
}
void PluginManager::readFromIniFile()
{
std::string path= pluginsIniFile;
if ( !DataRepository.findFile(path) )
{
path = DataRepository.getFirstPath() + "/" + pluginsIniFile;
std::ofstream ofile(path.c_str());
ofile << "";
ofile.close();
}
else path = DataRepository.getFile( pluginsIniFile );
std::ifstream instream(path.c_str());
std::string pluginPath;
while(std::getline(instream,pluginPath))
{
if(loadPlugin(pluginPath))
m_pluginMap[pluginPath].initExternalModule();
}
instream.close();
}
void PluginManager::writeToIniFile()
{
std::string path= pluginsIniFile;
if ( !DataRepository.findFile(path) )
{
path = DataRepository.getFirstPath() + "/" + pluginsIniFile;
std::ofstream ofile(path.c_str(),std::ios::out);
ofile << "";
ofile.close();
}
else path = DataRepository.getFile( pluginsIniFile );
std::ofstream outstream(path.c_str());
PluginIterator iter;
for( iter = m_pluginMap.begin(); iter!=m_pluginMap.end(); ++iter)
{
const std::string& pluginPath = (iter->first);
outstream << pluginPath << "\n";
}
outstream.close();
}
bool PluginManager::loadPlugin(std::string& pluginPath, std::ostream* errlog)
{
if (sofa::helper::system::SetDirectory::GetParentDir(pluginPath.c_str()).empty() &&
sofa::helper::system::SetDirectory::GetExtension(pluginPath.c_str()).empty())
{
// no path and extension -> automatically add suffix and OS-specific extension
#ifdef SOFA_LIBSUFFIX
pluginPath += sofa_tostring(SOFA_LIBSUFFIX);
#endif
#if defined (WIN32)
pluginPath = pluginPath + std::string(".dll");
#elif defined (__APPLE__)
pluginPath = std::string("lib") + pluginPath + std::string(".dylib");
#else
pluginPath = std::string("lib") + pluginPath + std::string(".so");
#endif
//std::cout << "System-specific plugin filename: " << pluginPath << std::endl;
}
if( !PluginRepository.findFile(pluginPath,"",errlog) )
{
if (errlog) (*errlog) << "Plugin " << pluginPath << " NOT FOUND in: " << PluginRepository << std::endl;
return false;
}
if(m_pluginMap.find(pluginPath) != m_pluginMap.end() )
{
if(errlog) (*errlog) << "Plugin " << pluginPath << " already in PluginManager" << std::endl;
return false;
}
DynamicLibrary::Handle d = DynamicLibrary::load(pluginPath);
Plugin p;
if( ! d.isValid() )
{
if (errlog) (*errlog) << "Plugin " << pluginPath << " loading FAILED" << std::endl;
return false;
}
else
{
if(! getPluginEntry(p.initExternalModule,d))
{
if (errlog) (*errlog) << "Plugin " << pluginPath << " method initExternalModule() NOT FOUND" << std::endl;
return false;
}
getPluginEntry(p.getModuleName,d);
getPluginEntry(p.getModuleDescription,d);
getPluginEntry(p.getModuleLicense,d);
getPluginEntry(p.getModuleComponentList,d);
getPluginEntry(p.getModuleVersion,d);
}
p.dynamicLibrary = d;
m_pluginMap[pluginPath] = p;
return true;
}
bool PluginManager::unloadPlugin(std::string &pluginPath, std::ostream *errlog)
{
PluginMap::iterator iter;
iter = m_pluginMap.find(pluginPath);
if( iter == m_pluginMap.end() )
{
if (sofa::helper::system::SetDirectory::GetParentDir(pluginPath.c_str()).empty() &&
sofa::helper::system::SetDirectory::GetExtension(pluginPath.c_str()).empty())
{
// no path and extension -> automatically add suffix and OS-specific extension
#ifdef SOFA_LIBSUFFIX
pluginPath += sofa_tostring(SOFA_LIBSUFFIX);
#endif
#if defined (WIN32)
pluginPath = pluginPath + std::string(".dll");
#elif defined (__APPLE__)
pluginPath = std::string("lib") + pluginPath + std::string(".dylib");
#else
pluginPath = std::string("lib") + pluginPath + std::string(".so");
#endif
}
PluginRepository.findFile(pluginPath,"",errlog);
iter = m_pluginMap.find(pluginPath);
}
if( iter == m_pluginMap.end() )
{
if(errlog) (*errlog) << "Plugin " << pluginPath << "not in PluginManager" << std::endl;
return false;
}
else
{
m_pluginMap.erase(iter);
return true;
}
}
void PluginManager::initRecentlyOpened()
{
readFromIniFile();
}
std::istream& PluginManager::readFromStream(std::istream & in)
{
while(!in.eof())
{
std::string pluginPath;
in >> pluginPath;
loadPlugin(pluginPath);
}
return in;
}
std::ostream& PluginManager::writeToStream(std::ostream & os) const
{
PluginMap::const_iterator iter;
for(iter= m_pluginMap.begin(); iter!=m_pluginMap.end(); ++iter)
{
os << iter->first;
}
return os;
}
void PluginManager::init()
{
PluginMap::iterator iter;
for( iter = m_pluginMap.begin(); iter!= m_pluginMap.end(); ++iter)
{
Plugin& plugin = iter->second;
plugin.initExternalModule();
}
}
void PluginManager::init(const std::string& pluginName)
{
PluginMap::iterator iter = m_pluginMap.find(pluginName);
if(m_pluginMap.end() != iter)
{
Plugin& plugin = iter->second;
plugin.initExternalModule();
}
}
}
}
}
<commit_msg>r10891/sofa : UPDATE: if plugin load failed display the loader handler error message... to understand what is going on.<commit_after>/******************************************************************************
* SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1 *
* (c) 2006-2011 INRIA, USTL, UJF, CNRS, MGH *
* *
* 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. *
*******************************************************************************
* SOFA :: Framework *
* *
* Authors: The SOFA Team (see Authors.txt) *
* *
* Contact information: contact@sofa-framework.org *
******************************************************************************/
#include <sofa/helper/system/PluginManager.h>
#include <sofa/helper/system/FileRepository.h>
#include <sofa/helper/system/SetDirectory.h>
#include <fstream>
namespace sofa
{
namespace helper
{
namespace system
{
namespace
{
#ifdef NDEBUG
const std::string pluginsIniFile = "share/config/sofaplugins_release.ini";
#else
const std::string pluginsIniFile = "share/config/sofaplugins_debug.ini";
#endif
template <class LibraryEntry>
bool getPluginEntry(LibraryEntry& entry, DynamicLibrary::Handle handle)
{
typedef typename LibraryEntry::FuncPtr FuncPtr;
entry.func = (FuncPtr)DynamicLibrary::getSymbolAddress(handle, entry.symbol);
if( entry.func == 0 )
{
return false;
}
else
{
return true;
}
}
} // namespace
const char* Plugin::GetModuleComponentList::symbol = "getModuleComponentList";
const char* Plugin::InitExternalModule::symbol = "initExternalModule";
const char* Plugin::GetModuleDescription::symbol = "getModuleDescription";
const char* Plugin::GetModuleLicense::symbol = "getModuleLicense";
const char* Plugin::GetModuleName::symbol = "getModuleName";
const char* Plugin::GetModuleVersion::symbol = "getModuleVersion";
PluginManager & PluginManager::getInstance()
{
static PluginManager instance;
return instance;
}
PluginManager::~PluginManager()
{
// BUGFIX: writeToIniFile should not be called here as it will erase the file in case it was not loaded
// Instead we write the file each time a change have been made in the GUI and should be saved
//writeToIniFile();
}
void PluginManager::readFromIniFile()
{
std::string path= pluginsIniFile;
if ( !DataRepository.findFile(path) )
{
path = DataRepository.getFirstPath() + "/" + pluginsIniFile;
std::ofstream ofile(path.c_str());
ofile << "";
ofile.close();
}
else path = DataRepository.getFile( pluginsIniFile );
std::ifstream instream(path.c_str());
std::string pluginPath;
while(std::getline(instream,pluginPath))
{
if(loadPlugin(pluginPath))
m_pluginMap[pluginPath].initExternalModule();
}
instream.close();
}
void PluginManager::writeToIniFile()
{
std::string path= pluginsIniFile;
if ( !DataRepository.findFile(path) )
{
path = DataRepository.getFirstPath() + "/" + pluginsIniFile;
std::ofstream ofile(path.c_str(),std::ios::out);
ofile << "";
ofile.close();
}
else path = DataRepository.getFile( pluginsIniFile );
std::ofstream outstream(path.c_str());
PluginIterator iter;
for( iter = m_pluginMap.begin(); iter!=m_pluginMap.end(); ++iter)
{
const std::string& pluginPath = (iter->first);
outstream << pluginPath << "\n";
}
outstream.close();
}
bool PluginManager::loadPlugin(std::string& pluginPath, std::ostream* errlog)
{
if (sofa::helper::system::SetDirectory::GetParentDir(pluginPath.c_str()).empty() &&
sofa::helper::system::SetDirectory::GetExtension(pluginPath.c_str()).empty())
{
// no path and extension -> automatically add suffix and OS-specific extension
#ifdef SOFA_LIBSUFFIX
pluginPath += sofa_tostring(SOFA_LIBSUFFIX);
#endif
#if defined (WIN32)
pluginPath = pluginPath + std::string(".dll");
#elif defined (__APPLE__)
pluginPath = std::string("lib") + pluginPath + std::string(".dylib");
#else
pluginPath = std::string("lib") + pluginPath + std::string(".so");
#endif
//std::cout << "System-specific plugin filename: " << pluginPath << std::endl;
}
if( !PluginRepository.findFile(pluginPath,"",errlog) )
{
if (errlog) (*errlog) << "Plugin " << pluginPath << " NOT FOUND in: " << PluginRepository << std::endl;
return false;
}
if(m_pluginMap.find(pluginPath) != m_pluginMap.end() )
{
if(errlog) (*errlog) << "Plugin " << pluginPath << " already in PluginManager" << std::endl;
return false;
}
DynamicLibrary::Handle d = DynamicLibrary::load(pluginPath);
Plugin p;
if( ! d.isValid() )
{
if (errlog) (*errlog) << "Plugin " << pluginPath << " loading FAILED with error: " << DynamicLibrary::getLastError() << std::endl;
return false;
}
else
{
if(! getPluginEntry(p.initExternalModule,d))
{
if (errlog) (*errlog) << "Plugin " << pluginPath << " method initExternalModule() NOT FOUND" << std::endl;
return false;
}
getPluginEntry(p.getModuleName,d);
getPluginEntry(p.getModuleDescription,d);
getPluginEntry(p.getModuleLicense,d);
getPluginEntry(p.getModuleComponentList,d);
getPluginEntry(p.getModuleVersion,d);
}
p.dynamicLibrary = d;
m_pluginMap[pluginPath] = p;
return true;
}
bool PluginManager::unloadPlugin(std::string &pluginPath, std::ostream *errlog)
{
PluginMap::iterator iter;
iter = m_pluginMap.find(pluginPath);
if( iter == m_pluginMap.end() )
{
if (sofa::helper::system::SetDirectory::GetParentDir(pluginPath.c_str()).empty() &&
sofa::helper::system::SetDirectory::GetExtension(pluginPath.c_str()).empty())
{
// no path and extension -> automatically add suffix and OS-specific extension
#ifdef SOFA_LIBSUFFIX
pluginPath += sofa_tostring(SOFA_LIBSUFFIX);
#endif
#if defined (WIN32)
pluginPath = pluginPath + std::string(".dll");
#elif defined (__APPLE__)
pluginPath = std::string("lib") + pluginPath + std::string(".dylib");
#else
pluginPath = std::string("lib") + pluginPath + std::string(".so");
#endif
}
PluginRepository.findFile(pluginPath,"",errlog);
iter = m_pluginMap.find(pluginPath);
}
if( iter == m_pluginMap.end() )
{
if(errlog) (*errlog) << "Plugin " << pluginPath << "not in PluginManager" << std::endl;
return false;
}
else
{
m_pluginMap.erase(iter);
return true;
}
}
void PluginManager::initRecentlyOpened()
{
readFromIniFile();
}
std::istream& PluginManager::readFromStream(std::istream & in)
{
while(!in.eof())
{
std::string pluginPath;
in >> pluginPath;
loadPlugin(pluginPath);
}
return in;
}
std::ostream& PluginManager::writeToStream(std::ostream & os) const
{
PluginMap::const_iterator iter;
for(iter= m_pluginMap.begin(); iter!=m_pluginMap.end(); ++iter)
{
os << iter->first;
}
return os;
}
void PluginManager::init()
{
PluginMap::iterator iter;
for( iter = m_pluginMap.begin(); iter!= m_pluginMap.end(); ++iter)
{
Plugin& plugin = iter->second;
plugin.initExternalModule();
}
}
void PluginManager::init(const std::string& pluginName)
{
PluginMap::iterator iter = m_pluginMap.find(pluginName);
if(m_pluginMap.end() != iter)
{
Plugin& plugin = iter->second;
plugin.initExternalModule();
}
}
}
}
}
<|endoftext|>
|
<commit_before>//===--- RequirementMachine.cpp - Generics with term rewriting --*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#include "swift/AST/RequirementMachine.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/Decl.h"
#include "swift/AST/GenericSignature.h"
#include "swift/AST/PrettyStackTrace.h"
#include "swift/AST/ProtocolGraph.h"
#include "swift/AST/Requirement.h"
#include "swift/AST/RewriteSystem.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/TinyPtrVector.h"
#include <vector>
using namespace swift;
using namespace rewriting;
namespace {
/// A utility class for bulding a rewrite system from the top-level requirements
/// of a generic signature, and all protocol requirement signatures from all
/// transitively-referenced protocols.
struct RewriteSystemBuilder {
RewriteContext &Context;
bool Debug;
ProtocolGraph Protocols;
std::vector<std::pair<Term, Term>> Rules;
RewriteSystemBuilder(RewriteContext &ctx, bool debug)
: Context(ctx), Debug(debug) {}
void addGenericSignature(CanGenericSignature sig);
void addAssociatedType(const AssociatedTypeDecl *type,
const ProtocolDecl *proto);
void addInheritedAssociatedType(const AssociatedTypeDecl *type,
const ProtocolDecl *inherited,
const ProtocolDecl *proto);
void addRequirement(const Requirement &req,
const ProtocolDecl *proto);
};
} // end namespace
void RewriteSystemBuilder::addGenericSignature(CanGenericSignature sig) {
// Collect all protocols transitively referenced from the generic signature's
// requirements.
Protocols.visitRequirements(sig->getRequirements());
Protocols.computeTransitiveClosure();
Protocols.computeLinearOrder();
Protocols.computeInheritedAssociatedTypes();
// Add rewrite rules for each protocol.
for (auto *proto : Protocols.Protocols) {
if (Debug) {
llvm::dbgs() << "protocol " << proto->getName() << " {\n";
}
const auto &info = Protocols.getProtocolInfo(proto);
for (auto *type : info.AssociatedTypes)
addAssociatedType(type, proto);
for (auto *inherited : info.Inherited) {
auto inheritedTypes = Protocols.getProtocolInfo(inherited).AssociatedTypes;
for (auto *inheritedType : inheritedTypes) {
addInheritedAssociatedType(inheritedType, inherited, proto);
}
}
for (auto req : info.Requirements)
addRequirement(req.getCanonical(), proto);
if (Debug) {
llvm::dbgs() << "}\n";
}
}
// Add rewrite rules for all requirements in the top-level signature.
for (const auto &req : sig->getRequirements())
addRequirement(req, /*proto=*/nullptr);
}
/// For an associated type T in a protocol P, we add a rewrite rule:
///
/// [P].T => [P:T]
///
/// Intuitively, this means "if a type conforms to P, it has a nested type
/// named T".
void RewriteSystemBuilder::addAssociatedType(const AssociatedTypeDecl *type,
const ProtocolDecl *proto) {
Term lhs;
lhs.add(Atom::forProtocol(proto, Context));
lhs.add(Atom::forName(type->getName(), Context));
Term rhs;
rhs.add(Atom::forAssociatedType(proto, type->getName(), Context));
Rules.emplace_back(lhs, rhs);
}
/// For an associated type T in a protocol Q that is inherited by another
/// protocol P, we add a rewrite rule:
///
/// [P].[Q:T] => [P:T]
///
/// Intuitively this means, "if a type conforms to P, then the associated type
/// T of Q is inherited by P".
void RewriteSystemBuilder::addInheritedAssociatedType(
const AssociatedTypeDecl *type,
const ProtocolDecl *inherited,
const ProtocolDecl *proto) {
assert(inherited != proto);
Term lhs;
lhs.add(Atom::forProtocol(proto, Context));
lhs.add(Atom::forAssociatedType(inherited, type->getName(), Context));
Term rhs;
rhs.add(Atom::forAssociatedType(proto, type->getName(), Context));
Rules.emplace_back(lhs, rhs);
}
/// Lowers a generic requirement to a rewrite rule.
///
/// If \p proto is null, this is a generic requirement from the top-level
/// generic signature. The added rewrite rule will be rooted in a generic
/// parameter atom.
///
/// If \p proto is non-null, this is a generic requirement in the protocol's
/// requirement signature. The added rewrite rule will be rooted in a
/// protocol atom.
void RewriteSystemBuilder::addRequirement(const Requirement &req,
const ProtocolDecl *proto) {
if (Debug) {
llvm::dbgs() << "+ ";
req.dump(llvm::dbgs());
llvm::dbgs() << "\n";
}
auto subjectType = CanType(req.getFirstType());
auto subjectTerm = Context.getTermForType(subjectType, proto);
switch (req.getKind()) {
case RequirementKind::Conformance: {
// A conformance requirement T : P becomes a rewrite rule
//
// T.[P] == T
//
// Intuitively, this means "any type ending with T conforms to P".
auto *proto = req.getProtocolDecl();
auto constraintTerm = subjectTerm;
constraintTerm.add(Atom::forProtocol(proto, Context));
Rules.emplace_back(subjectTerm, constraintTerm);
break;
}
case RequirementKind::Superclass:
// FIXME: Implement
break;
case RequirementKind::Layout: {
// A layout requirement T : L becomes a rewrite rule
//
// T.[L] == T
auto constraintTerm = subjectTerm;
constraintTerm.add(Atom::forLayout(req.getLayoutConstraint(),
Context));
Rules.emplace_back(subjectTerm, constraintTerm);
break;
}
case RequirementKind::SameType: {
// A same-type requirement T == U becomes a rewrite rule
//
// T == U
auto otherType = CanType(req.getSecondType());
// FIXME: Handle concrete types
if (!otherType->isTypeParameter())
break;
auto otherTerm = Context.getTermForType(otherType, proto);
Rules.emplace_back(subjectTerm, otherTerm);
break;
}
}
}
/// We use the PIMPL pattern to avoid creeping header dependencies.
struct RequirementMachine::Implementation {
RewriteContext Context;
RewriteSystem System;
bool Complete = false;
Implementation(ASTContext &ctx)
: Context(ctx.Stats), System(Context) {}
};
RequirementMachine::RequirementMachine(ASTContext &ctx) : Context(ctx) {
Impl = new Implementation(ctx);
}
RequirementMachine::~RequirementMachine() {
delete Impl;
}
void RequirementMachine::addGenericSignature(CanGenericSignature sig) {
PrettyStackTraceGenericSignature debugStack("building rewrite system for", sig);
auto *Stats = Context.Stats;
if (Stats)
++Stats->getFrontendCounters().NumRequirementMachines;
FrontendStatsTracer tracer(Stats, "build-rewrite-system");
if (Context.LangOpts.DebugRequirementMachine) {
llvm::dbgs() << "Adding generic signature " << sig << " {\n";
}
// Collect the top-level requirements, and all transtively-referenced
// protocol requirement signatures.
RewriteSystemBuilder builder(Impl->Context,
Context.LangOpts.DebugRequirementMachine);
builder.addGenericSignature(sig);
// Add the initial set of rewrite rules to the rewrite system, also
// providing the protocol graph to use for the linear order on terms.
Impl->System.initialize(std::move(builder.Rules),
std::move(builder.Protocols));
// Attempt to obtain a confluent rewrite system using the completion
// procedure.
auto result = Impl->System.computeConfluentCompletion(
Context.LangOpts.RequirementMachineStepLimit,
Context.LangOpts.RequirementMachineDepthLimit);
// Check for failure.
switch (result) {
case RewriteSystem::CompletionResult::Success:
break;
case RewriteSystem::CompletionResult::MaxIterations:
llvm::errs() << "Generic signature " << sig
<< " exceeds maximum completion step count\n";
Impl->System.dump(llvm::errs());
abort();
case RewriteSystem::CompletionResult::MaxDepth:
llvm::errs() << "Generic signature " << sig
<< " exceeds maximum completion depth\n";
Impl->System.dump(llvm::errs());
abort();
}
markComplete();
if (Context.LangOpts.DebugRequirementMachine) {
llvm::dbgs() << "}\n";
}
}
bool RequirementMachine::isComplete() const {
return Impl->Complete;
}
void RequirementMachine::markComplete() {
if (Context.LangOpts.DebugRequirementMachine) {
Impl->System.dump(llvm::dbgs());
}
assert(!Impl->Complete);
Impl->Complete = true;
}<commit_msg>RequirementMachine: Don't introduce rules for inherited associated types<commit_after>//===--- RequirementMachine.cpp - Generics with term rewriting --*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#include "swift/AST/RequirementMachine.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/Decl.h"
#include "swift/AST/GenericSignature.h"
#include "swift/AST/PrettyStackTrace.h"
#include "swift/AST/ProtocolGraph.h"
#include "swift/AST/Requirement.h"
#include "swift/AST/RewriteSystem.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/TinyPtrVector.h"
#include <vector>
using namespace swift;
using namespace rewriting;
namespace {
/// A utility class for bulding a rewrite system from the top-level requirements
/// of a generic signature, and all protocol requirement signatures from all
/// transitively-referenced protocols.
struct RewriteSystemBuilder {
RewriteContext &Context;
bool Debug;
ProtocolGraph Protocols;
std::vector<std::pair<Term, Term>> Rules;
RewriteSystemBuilder(RewriteContext &ctx, bool debug)
: Context(ctx), Debug(debug) {}
void addGenericSignature(CanGenericSignature sig);
void addAssociatedType(const AssociatedTypeDecl *type,
const ProtocolDecl *proto);
void addRequirement(const Requirement &req,
const ProtocolDecl *proto);
};
} // end namespace
void RewriteSystemBuilder::addGenericSignature(CanGenericSignature sig) {
// Collect all protocols transitively referenced from the generic signature's
// requirements.
Protocols.visitRequirements(sig->getRequirements());
Protocols.computeTransitiveClosure();
Protocols.computeLinearOrder();
Protocols.computeInheritedAssociatedTypes();
// Add rewrite rules for each protocol.
for (auto *proto : Protocols.Protocols) {
if (Debug) {
llvm::dbgs() << "protocol " << proto->getName() << " {\n";
}
const auto &info = Protocols.getProtocolInfo(proto);
for (auto *type : info.AssociatedTypes)
addAssociatedType(type, proto);
for (auto req : info.Requirements)
addRequirement(req.getCanonical(), proto);
if (Debug) {
llvm::dbgs() << "}\n";
}
}
// Add rewrite rules for all requirements in the top-level signature.
for (const auto &req : sig->getRequirements())
addRequirement(req, /*proto=*/nullptr);
}
/// For an associated type T in a protocol P, we add a rewrite rule:
///
/// [P].T => [P:T]
///
/// Intuitively, this means "if a type conforms to P, it has a nested type
/// named T".
void RewriteSystemBuilder::addAssociatedType(const AssociatedTypeDecl *type,
const ProtocolDecl *proto) {
Term lhs;
lhs.add(Atom::forProtocol(proto, Context));
lhs.add(Atom::forName(type->getName(), Context));
Term rhs;
rhs.add(Atom::forAssociatedType(proto, type->getName(), Context));
Rules.emplace_back(lhs, rhs);
}
/// Lowers a generic requirement to a rewrite rule.
///
/// If \p proto is null, this is a generic requirement from the top-level
/// generic signature. The added rewrite rule will be rooted in a generic
/// parameter atom.
///
/// If \p proto is non-null, this is a generic requirement in the protocol's
/// requirement signature. The added rewrite rule will be rooted in a
/// protocol atom.
void RewriteSystemBuilder::addRequirement(const Requirement &req,
const ProtocolDecl *proto) {
if (Debug) {
llvm::dbgs() << "+ ";
req.dump(llvm::dbgs());
llvm::dbgs() << "\n";
}
auto subjectType = CanType(req.getFirstType());
auto subjectTerm = Context.getTermForType(subjectType, proto);
switch (req.getKind()) {
case RequirementKind::Conformance: {
// A conformance requirement T : P becomes a rewrite rule
//
// T.[P] == T
//
// Intuitively, this means "any type ending with T conforms to P".
auto *proto = req.getProtocolDecl();
auto constraintTerm = subjectTerm;
constraintTerm.add(Atom::forProtocol(proto, Context));
Rules.emplace_back(subjectTerm, constraintTerm);
break;
}
case RequirementKind::Superclass:
// FIXME: Implement
break;
case RequirementKind::Layout: {
// A layout requirement T : L becomes a rewrite rule
//
// T.[L] == T
auto constraintTerm = subjectTerm;
constraintTerm.add(Atom::forLayout(req.getLayoutConstraint(),
Context));
Rules.emplace_back(subjectTerm, constraintTerm);
break;
}
case RequirementKind::SameType: {
// A same-type requirement T == U becomes a rewrite rule
//
// T == U
auto otherType = CanType(req.getSecondType());
// FIXME: Handle concrete types
if (!otherType->isTypeParameter())
break;
auto otherTerm = Context.getTermForType(otherType, proto);
Rules.emplace_back(subjectTerm, otherTerm);
break;
}
}
}
/// We use the PIMPL pattern to avoid creeping header dependencies.
struct RequirementMachine::Implementation {
RewriteContext Context;
RewriteSystem System;
bool Complete = false;
Implementation(ASTContext &ctx)
: Context(ctx.Stats), System(Context) {}
};
RequirementMachine::RequirementMachine(ASTContext &ctx) : Context(ctx) {
Impl = new Implementation(ctx);
}
RequirementMachine::~RequirementMachine() {
delete Impl;
}
void RequirementMachine::addGenericSignature(CanGenericSignature sig) {
PrettyStackTraceGenericSignature debugStack("building rewrite system for", sig);
auto *Stats = Context.Stats;
if (Stats)
++Stats->getFrontendCounters().NumRequirementMachines;
FrontendStatsTracer tracer(Stats, "build-rewrite-system");
if (Context.LangOpts.DebugRequirementMachine) {
llvm::dbgs() << "Adding generic signature " << sig << " {\n";
}
// Collect the top-level requirements, and all transtively-referenced
// protocol requirement signatures.
RewriteSystemBuilder builder(Impl->Context,
Context.LangOpts.DebugRequirementMachine);
builder.addGenericSignature(sig);
// Add the initial set of rewrite rules to the rewrite system, also
// providing the protocol graph to use for the linear order on terms.
Impl->System.initialize(std::move(builder.Rules),
std::move(builder.Protocols));
// Attempt to obtain a confluent rewrite system using the completion
// procedure.
auto result = Impl->System.computeConfluentCompletion(
Context.LangOpts.RequirementMachineStepLimit,
Context.LangOpts.RequirementMachineDepthLimit);
// Check for failure.
switch (result) {
case RewriteSystem::CompletionResult::Success:
break;
case RewriteSystem::CompletionResult::MaxIterations:
llvm::errs() << "Generic signature " << sig
<< " exceeds maximum completion step count\n";
Impl->System.dump(llvm::errs());
abort();
case RewriteSystem::CompletionResult::MaxDepth:
llvm::errs() << "Generic signature " << sig
<< " exceeds maximum completion depth\n";
Impl->System.dump(llvm::errs());
abort();
}
markComplete();
if (Context.LangOpts.DebugRequirementMachine) {
llvm::dbgs() << "}\n";
}
}
bool RequirementMachine::isComplete() const {
return Impl->Complete;
}
void RequirementMachine::markComplete() {
if (Context.LangOpts.DebugRequirementMachine) {
Impl->System.dump(llvm::dbgs());
}
assert(!Impl->Complete);
Impl->Complete = true;
}<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: propertysethelper.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: obo $ $Date: 2006-09-16 13:48:38 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_framework.hxx"
//_________________________________________________________________________________________________________________
// my own includes
#include <classes/propertysethelper.hxx>
#include <threadhelp/transactionguard.hxx>
#include <threadhelp/readguard.hxx>
#include <threadhelp/writeguard.hxx>
//_________________________________________________________________________________________________________________
// interface includes
//_________________________________________________________________________________________________________________
// other includes
//_________________________________________________________________________________________________________________
// namespace
namespace framework{
//_________________________________________________________________________________________________________________
// non exported definitions
//-----------------------------------------------------------------------------
PropertySetHelper::PropertySetHelper(const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR ,
LockHelper* pExternalLock ,
TransactionManager* pExternalTransactionManager ,
sal_Bool bReleaseLockOnCall )
: m_xSMGR (xSMGR )
, m_lSimpleChangeListener(pExternalLock->getShareableOslMutex())
, m_lVetoChangeListener (pExternalLock->getShareableOslMutex())
, m_bReleaseLockOnCall (bReleaseLockOnCall )
, m_rLock (*pExternalLock )
, m_rTransactionManager (*pExternalTransactionManager )
{
}
//-----------------------------------------------------------------------------
PropertySetHelper::~PropertySetHelper()
{
}
//-----------------------------------------------------------------------------
void PropertySetHelper::impl_setPropertyChangeBroadcaster(const css::uno::Reference< css::uno::XInterface >& xBroadcaster)
{
TransactionGuard aTransaction(m_rTransactionManager, E_SOFTEXCEPTIONS);
// SAFE ->
WriteGuard aWriteLock(m_rLock);
m_xBroadcaster = xBroadcaster;
aWriteLock.unlock();
// <- SAFE
}
//-----------------------------------------------------------------------------
void SAL_CALL PropertySetHelper::impl_addPropertyInfo(const css::beans::Property& aProperty)
throw(css::beans::PropertyExistException,
css::uno::Exception )
{
TransactionGuard aTransaction(m_rTransactionManager, E_SOFTEXCEPTIONS);
// SAFE ->
WriteGuard aWriteLock(m_rLock);
PropertySetHelper::TPropInfoHash::const_iterator pIt = m_lProps.find(aProperty.Name);
if (pIt != m_lProps.end())
throw css::beans::PropertyExistException();
m_lProps[aProperty.Name] = aProperty;
// <- SAFE
}
//-----------------------------------------------------------------------------
void SAL_CALL PropertySetHelper::impl_removePropertyInfo(const ::rtl::OUString& sProperty)
throw(css::beans::UnknownPropertyException,
css::uno::Exception )
{
TransactionGuard aTransaction(m_rTransactionManager, E_SOFTEXCEPTIONS);
// SAFE ->
WriteGuard aWriteLock(m_rLock);
PropertySetHelper::TPropInfoHash::iterator pIt = m_lProps.find(sProperty);
if (pIt == m_lProps.end())
throw css::beans::UnknownPropertyException();
m_lProps.erase(pIt);
// <- SAFE
}
//-----------------------------------------------------------------------------
void SAL_CALL PropertySetHelper::impl_enablePropertySet()
{
}
//-----------------------------------------------------------------------------
void SAL_CALL PropertySetHelper::impl_disablePropertySet()
{
TransactionGuard aTransaction(m_rTransactionManager, E_SOFTEXCEPTIONS);
// SAFE ->
WriteGuard aWriteLock(m_rLock);
css::uno::Reference< css::uno::XInterface > xThis(static_cast< css::beans::XPropertySet* >(this), css::uno::UNO_QUERY);
css::lang::EventObject aEvent(xThis);
m_lSimpleChangeListener.disposeAndClear(aEvent);
m_lVetoChangeListener.disposeAndClear(aEvent);
m_lProps.free();
aWriteLock.unlock();
// <- SAFE
}
//-----------------------------------------------------------------------------
sal_Bool PropertySetHelper::impl_existsVeto(const css::beans::PropertyChangeEvent& aEvent)
{
/* Dont use the lock here!
The used helper is threadsafe and it lives for the whole lifetime of
our own object.
*/
::cppu::OInterfaceContainerHelper* pVetoListener = m_lVetoChangeListener.getContainer(aEvent.PropertyName);
if (! pVetoListener)
return sal_False;
::cppu::OInterfaceIteratorHelper pListener(*pVetoListener);
while (pListener.hasMoreElements())
{
try
{
css::uno::Reference< css::beans::XVetoableChangeListener > xListener(
((css::beans::XVetoableChangeListener*)pListener.next()),
css::uno::UNO_QUERY_THROW);
xListener->vetoableChange(aEvent);
}
catch(const css::uno::RuntimeException&)
{ pListener.remove(); }
catch(const css::beans::PropertyVetoException&)
{ return sal_True; }
}
return sal_False;
}
//-----------------------------------------------------------------------------
void PropertySetHelper::impl_notifyChangeListener(const css::beans::PropertyChangeEvent& aEvent)
{
/* Dont use the lock here!
The used helper is threadsafe and it lives for the whole lifetime of
our own object.
*/
::cppu::OInterfaceContainerHelper* pSimpleListener = m_lSimpleChangeListener.getContainer(aEvent.PropertyName);
if (! pSimpleListener)
return;
::cppu::OInterfaceIteratorHelper pListener(*pSimpleListener);
while (pListener.hasMoreElements())
{
try
{
css::uno::Reference< css::beans::XPropertyChangeListener > xListener(
((css::beans::XVetoableChangeListener*)pListener.next()),
css::uno::UNO_QUERY_THROW);
xListener->propertyChange(aEvent);
}
catch(const css::uno::RuntimeException&)
{ pListener.remove(); }
}
}
//-----------------------------------------------------------------------------
css::uno::Reference< css::beans::XPropertySetInfo > SAL_CALL PropertySetHelper::getPropertySetInfo()
throw(css::uno::RuntimeException)
{
TransactionGuard aTransaction(m_rTransactionManager, E_HARDEXCEPTIONS);
css::uno::Reference< css::beans::XPropertySetInfo > xInfo(static_cast< css::beans::XPropertySetInfo* >(this), css::uno::UNO_QUERY_THROW);
return xInfo;
}
//-----------------------------------------------------------------------------
void SAL_CALL PropertySetHelper::setPropertyValue(const ::rtl::OUString& sProperty,
const css::uno::Any& aValue )
throw(css::beans::UnknownPropertyException,
css::beans::PropertyVetoException ,
css::lang::IllegalArgumentException ,
css::lang::WrappedTargetException ,
css::uno::RuntimeException )
{
// TODO look for e.g. readonly props and reject setProp() call!
TransactionGuard aTransaction(m_rTransactionManager, E_HARDEXCEPTIONS);
// SAFE ->
WriteGuard aWriteLock(m_rLock);
PropertySetHelper::TPropInfoHash::const_iterator pIt = m_lProps.find(sProperty);
if (pIt == m_lProps.end())
throw css::beans::UnknownPropertyException();
css::beans::Property aPropInfo = pIt->second;
sal_Bool bLocked = sal_True;
if (m_bReleaseLockOnCall)
{
aWriteLock.unlock();
bLocked = sal_False;
// <- SAFE
}
css::uno::Any aCurrentValue = impl_getPropertyValue(aPropInfo.Name, aPropInfo.Handle);
if (! bLocked)
{
// SAFE ->
aWriteLock.lock();
bLocked = sal_True;
}
sal_Bool bWillBeChanged = (aCurrentValue != aValue);
if (! bWillBeChanged)
return;
css::beans::PropertyChangeEvent aEvent;
aEvent.PropertyName = aPropInfo.Name;
aEvent.Further = sal_False;
aEvent.PropertyHandle = aPropInfo.Handle;
aEvent.OldValue = aCurrentValue;
aEvent.NewValue = aValue;
aEvent.Source = css::uno::Reference< css::uno::XInterface >(m_xBroadcaster.get(), css::uno::UNO_QUERY);
if (m_bReleaseLockOnCall)
{
aWriteLock.unlock();
bLocked = sal_False;
// <- SAFE
}
if (impl_existsVeto(aEvent))
throw css::beans::PropertyVetoException();
impl_setPropertyValue(aPropInfo.Name, aPropInfo.Handle, aValue);
impl_notifyChangeListener(aEvent);
}
//-----------------------------------------------------------------------------
css::uno::Any SAL_CALL PropertySetHelper::getPropertyValue(const ::rtl::OUString& sProperty)
throw(css::beans::UnknownPropertyException,
css::lang::WrappedTargetException ,
css::uno::RuntimeException )
{
TransactionGuard aTransaction(m_rTransactionManager, E_HARDEXCEPTIONS);
// SAFE ->
ReadGuard aReadLock(m_rLock);
PropertySetHelper::TPropInfoHash::const_iterator pIt = m_lProps.find(sProperty);
if (pIt == m_lProps.end())
throw css::beans::UnknownPropertyException();
css::beans::Property aPropInfo = pIt->second;
sal_Bool bLocked = sal_True;
if (m_bReleaseLockOnCall)
{
aReadLock.unlock();
bLocked = sal_False;
// <- SAFE
}
css::uno::Any aValue = impl_getPropertyValue(aPropInfo.Name, aPropInfo.Handle);
return aValue;
}
//-----------------------------------------------------------------------------
void SAL_CALL PropertySetHelper::addPropertyChangeListener(const ::rtl::OUString& sProperty,
const css::uno::Reference< css::beans::XPropertyChangeListener >& xListener)
throw(css::beans::UnknownPropertyException,
css::lang::WrappedTargetException ,
css::uno::RuntimeException )
{
TransactionGuard aTransaction(m_rTransactionManager, E_HARDEXCEPTIONS);
// SAFE ->
ReadGuard aReadLock(m_rLock);
PropertySetHelper::TPropInfoHash::const_iterator pIt = m_lProps.find(sProperty);
if (pIt == m_lProps.end())
throw css::beans::UnknownPropertyException();
aReadLock.unlock();
// <- SAFE
m_lSimpleChangeListener.addInterface(sProperty, xListener);
}
//-----------------------------------------------------------------------------
void SAL_CALL PropertySetHelper::removePropertyChangeListener(const ::rtl::OUString& sProperty,
const css::uno::Reference< css::beans::XPropertyChangeListener >& xListener)
throw(css::beans::UnknownPropertyException,
css::lang::WrappedTargetException ,
css::uno::RuntimeException )
{
TransactionGuard aTransaction(m_rTransactionManager, E_SOFTEXCEPTIONS);
// SAFE ->
ReadGuard aReadLock(m_rLock);
PropertySetHelper::TPropInfoHash::const_iterator pIt = m_lProps.find(sProperty);
if (pIt == m_lProps.end())
throw css::beans::UnknownPropertyException();
aReadLock.unlock();
// <- SAFE
m_lSimpleChangeListener.removeInterface(sProperty, xListener);
}
//-----------------------------------------------------------------------------
void SAL_CALL PropertySetHelper::addVetoableChangeListener(const ::rtl::OUString& sProperty,
const css::uno::Reference< css::beans::XVetoableChangeListener >& xListener)
throw(css::beans::UnknownPropertyException,
css::lang::WrappedTargetException ,
css::uno::RuntimeException )
{
TransactionGuard aTransaction(m_rTransactionManager, E_HARDEXCEPTIONS);
// SAFE ->
ReadGuard aReadLock(m_rLock);
PropertySetHelper::TPropInfoHash::const_iterator pIt = m_lProps.find(sProperty);
if (pIt == m_lProps.end())
throw css::beans::UnknownPropertyException();
aReadLock.unlock();
// <- SAFE
m_lVetoChangeListener.addInterface(sProperty, xListener);
}
//-----------------------------------------------------------------------------
void SAL_CALL PropertySetHelper::removeVetoableChangeListener(const ::rtl::OUString& sProperty,
const css::uno::Reference< css::beans::XVetoableChangeListener >& xListener)
throw(css::beans::UnknownPropertyException,
css::lang::WrappedTargetException ,
css::uno::RuntimeException )
{
TransactionGuard aTransaction(m_rTransactionManager, E_SOFTEXCEPTIONS);
// SAFE ->
ReadGuard aReadLock(m_rLock);
PropertySetHelper::TPropInfoHash::const_iterator pIt = m_lProps.find(sProperty);
if (pIt == m_lProps.end())
throw css::beans::UnknownPropertyException();
aReadLock.unlock();
// <- SAFE
m_lVetoChangeListener.removeInterface(sProperty, xListener);
}
//-----------------------------------------------------------------------------
css::uno::Sequence< css::beans::Property > SAL_CALL PropertySetHelper::getProperties()
throw(css::uno::RuntimeException)
{
TransactionGuard aTransaction(m_rTransactionManager, E_HARDEXCEPTIONS);
// SAFE ->
ReadGuard aReadLock(m_rLock);
sal_Int32 c = (sal_Int32)m_lProps.size();
css::uno::Sequence< css::beans::Property > lProps(c);
PropertySetHelper::TPropInfoHash::const_iterator pIt ;
for ( pIt = m_lProps.begin();
pIt != m_lProps.end() ;
++pIt )
{
lProps[--c] = pIt->second;
}
return lProps;
// <- SAFE
}
//-----------------------------------------------------------------------------
css::beans::Property SAL_CALL PropertySetHelper::getPropertyByName(const ::rtl::OUString& sName)
throw(css::beans::UnknownPropertyException,
css::uno::RuntimeException )
{
TransactionGuard aTransaction(m_rTransactionManager, E_HARDEXCEPTIONS);
// SAFE ->
ReadGuard aReadLock(m_rLock);
PropertySetHelper::TPropInfoHash::const_iterator pIt = m_lProps.find(sName);
if (pIt == m_lProps.end())
throw css::beans::UnknownPropertyException();
return pIt->second;
// <- SAFE
}
//-----------------------------------------------------------------------------
sal_Bool SAL_CALL PropertySetHelper::hasPropertyByName(const ::rtl::OUString& sName)
throw(css::uno::RuntimeException)
{
TransactionGuard aTransaction(m_rTransactionManager, E_HARDEXCEPTIONS);
// SAFE ->
ReadGuard aReadLock(m_rLock);
PropertySetHelper::TPropInfoHash::iterator pIt = m_lProps.find(sName);
sal_Bool bExist = (pIt != m_lProps.end());
return bExist;
// <- SAFE
}
} // namespace framework
<commit_msg>INTEGRATION: CWS changefileheader (1.6.264); FILE MERGED 2008/03/28 15:35:12 rt 1.6.264.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: propertysethelper.cxx,v $
* $Revision: 1.7 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_framework.hxx"
//_________________________________________________________________________________________________________________
// my own includes
#include <classes/propertysethelper.hxx>
#include <threadhelp/transactionguard.hxx>
#include <threadhelp/readguard.hxx>
#include <threadhelp/writeguard.hxx>
//_________________________________________________________________________________________________________________
// interface includes
//_________________________________________________________________________________________________________________
// other includes
//_________________________________________________________________________________________________________________
// namespace
namespace framework{
//_________________________________________________________________________________________________________________
// non exported definitions
//-----------------------------------------------------------------------------
PropertySetHelper::PropertySetHelper(const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR ,
LockHelper* pExternalLock ,
TransactionManager* pExternalTransactionManager ,
sal_Bool bReleaseLockOnCall )
: m_xSMGR (xSMGR )
, m_lSimpleChangeListener(pExternalLock->getShareableOslMutex())
, m_lVetoChangeListener (pExternalLock->getShareableOslMutex())
, m_bReleaseLockOnCall (bReleaseLockOnCall )
, m_rLock (*pExternalLock )
, m_rTransactionManager (*pExternalTransactionManager )
{
}
//-----------------------------------------------------------------------------
PropertySetHelper::~PropertySetHelper()
{
}
//-----------------------------------------------------------------------------
void PropertySetHelper::impl_setPropertyChangeBroadcaster(const css::uno::Reference< css::uno::XInterface >& xBroadcaster)
{
TransactionGuard aTransaction(m_rTransactionManager, E_SOFTEXCEPTIONS);
// SAFE ->
WriteGuard aWriteLock(m_rLock);
m_xBroadcaster = xBroadcaster;
aWriteLock.unlock();
// <- SAFE
}
//-----------------------------------------------------------------------------
void SAL_CALL PropertySetHelper::impl_addPropertyInfo(const css::beans::Property& aProperty)
throw(css::beans::PropertyExistException,
css::uno::Exception )
{
TransactionGuard aTransaction(m_rTransactionManager, E_SOFTEXCEPTIONS);
// SAFE ->
WriteGuard aWriteLock(m_rLock);
PropertySetHelper::TPropInfoHash::const_iterator pIt = m_lProps.find(aProperty.Name);
if (pIt != m_lProps.end())
throw css::beans::PropertyExistException();
m_lProps[aProperty.Name] = aProperty;
// <- SAFE
}
//-----------------------------------------------------------------------------
void SAL_CALL PropertySetHelper::impl_removePropertyInfo(const ::rtl::OUString& sProperty)
throw(css::beans::UnknownPropertyException,
css::uno::Exception )
{
TransactionGuard aTransaction(m_rTransactionManager, E_SOFTEXCEPTIONS);
// SAFE ->
WriteGuard aWriteLock(m_rLock);
PropertySetHelper::TPropInfoHash::iterator pIt = m_lProps.find(sProperty);
if (pIt == m_lProps.end())
throw css::beans::UnknownPropertyException();
m_lProps.erase(pIt);
// <- SAFE
}
//-----------------------------------------------------------------------------
void SAL_CALL PropertySetHelper::impl_enablePropertySet()
{
}
//-----------------------------------------------------------------------------
void SAL_CALL PropertySetHelper::impl_disablePropertySet()
{
TransactionGuard aTransaction(m_rTransactionManager, E_SOFTEXCEPTIONS);
// SAFE ->
WriteGuard aWriteLock(m_rLock);
css::uno::Reference< css::uno::XInterface > xThis(static_cast< css::beans::XPropertySet* >(this), css::uno::UNO_QUERY);
css::lang::EventObject aEvent(xThis);
m_lSimpleChangeListener.disposeAndClear(aEvent);
m_lVetoChangeListener.disposeAndClear(aEvent);
m_lProps.free();
aWriteLock.unlock();
// <- SAFE
}
//-----------------------------------------------------------------------------
sal_Bool PropertySetHelper::impl_existsVeto(const css::beans::PropertyChangeEvent& aEvent)
{
/* Dont use the lock here!
The used helper is threadsafe and it lives for the whole lifetime of
our own object.
*/
::cppu::OInterfaceContainerHelper* pVetoListener = m_lVetoChangeListener.getContainer(aEvent.PropertyName);
if (! pVetoListener)
return sal_False;
::cppu::OInterfaceIteratorHelper pListener(*pVetoListener);
while (pListener.hasMoreElements())
{
try
{
css::uno::Reference< css::beans::XVetoableChangeListener > xListener(
((css::beans::XVetoableChangeListener*)pListener.next()),
css::uno::UNO_QUERY_THROW);
xListener->vetoableChange(aEvent);
}
catch(const css::uno::RuntimeException&)
{ pListener.remove(); }
catch(const css::beans::PropertyVetoException&)
{ return sal_True; }
}
return sal_False;
}
//-----------------------------------------------------------------------------
void PropertySetHelper::impl_notifyChangeListener(const css::beans::PropertyChangeEvent& aEvent)
{
/* Dont use the lock here!
The used helper is threadsafe and it lives for the whole lifetime of
our own object.
*/
::cppu::OInterfaceContainerHelper* pSimpleListener = m_lSimpleChangeListener.getContainer(aEvent.PropertyName);
if (! pSimpleListener)
return;
::cppu::OInterfaceIteratorHelper pListener(*pSimpleListener);
while (pListener.hasMoreElements())
{
try
{
css::uno::Reference< css::beans::XPropertyChangeListener > xListener(
((css::beans::XVetoableChangeListener*)pListener.next()),
css::uno::UNO_QUERY_THROW);
xListener->propertyChange(aEvent);
}
catch(const css::uno::RuntimeException&)
{ pListener.remove(); }
}
}
//-----------------------------------------------------------------------------
css::uno::Reference< css::beans::XPropertySetInfo > SAL_CALL PropertySetHelper::getPropertySetInfo()
throw(css::uno::RuntimeException)
{
TransactionGuard aTransaction(m_rTransactionManager, E_HARDEXCEPTIONS);
css::uno::Reference< css::beans::XPropertySetInfo > xInfo(static_cast< css::beans::XPropertySetInfo* >(this), css::uno::UNO_QUERY_THROW);
return xInfo;
}
//-----------------------------------------------------------------------------
void SAL_CALL PropertySetHelper::setPropertyValue(const ::rtl::OUString& sProperty,
const css::uno::Any& aValue )
throw(css::beans::UnknownPropertyException,
css::beans::PropertyVetoException ,
css::lang::IllegalArgumentException ,
css::lang::WrappedTargetException ,
css::uno::RuntimeException )
{
// TODO look for e.g. readonly props and reject setProp() call!
TransactionGuard aTransaction(m_rTransactionManager, E_HARDEXCEPTIONS);
// SAFE ->
WriteGuard aWriteLock(m_rLock);
PropertySetHelper::TPropInfoHash::const_iterator pIt = m_lProps.find(sProperty);
if (pIt == m_lProps.end())
throw css::beans::UnknownPropertyException();
css::beans::Property aPropInfo = pIt->second;
sal_Bool bLocked = sal_True;
if (m_bReleaseLockOnCall)
{
aWriteLock.unlock();
bLocked = sal_False;
// <- SAFE
}
css::uno::Any aCurrentValue = impl_getPropertyValue(aPropInfo.Name, aPropInfo.Handle);
if (! bLocked)
{
// SAFE ->
aWriteLock.lock();
bLocked = sal_True;
}
sal_Bool bWillBeChanged = (aCurrentValue != aValue);
if (! bWillBeChanged)
return;
css::beans::PropertyChangeEvent aEvent;
aEvent.PropertyName = aPropInfo.Name;
aEvent.Further = sal_False;
aEvent.PropertyHandle = aPropInfo.Handle;
aEvent.OldValue = aCurrentValue;
aEvent.NewValue = aValue;
aEvent.Source = css::uno::Reference< css::uno::XInterface >(m_xBroadcaster.get(), css::uno::UNO_QUERY);
if (m_bReleaseLockOnCall)
{
aWriteLock.unlock();
bLocked = sal_False;
// <- SAFE
}
if (impl_existsVeto(aEvent))
throw css::beans::PropertyVetoException();
impl_setPropertyValue(aPropInfo.Name, aPropInfo.Handle, aValue);
impl_notifyChangeListener(aEvent);
}
//-----------------------------------------------------------------------------
css::uno::Any SAL_CALL PropertySetHelper::getPropertyValue(const ::rtl::OUString& sProperty)
throw(css::beans::UnknownPropertyException,
css::lang::WrappedTargetException ,
css::uno::RuntimeException )
{
TransactionGuard aTransaction(m_rTransactionManager, E_HARDEXCEPTIONS);
// SAFE ->
ReadGuard aReadLock(m_rLock);
PropertySetHelper::TPropInfoHash::const_iterator pIt = m_lProps.find(sProperty);
if (pIt == m_lProps.end())
throw css::beans::UnknownPropertyException();
css::beans::Property aPropInfo = pIt->second;
sal_Bool bLocked = sal_True;
if (m_bReleaseLockOnCall)
{
aReadLock.unlock();
bLocked = sal_False;
// <- SAFE
}
css::uno::Any aValue = impl_getPropertyValue(aPropInfo.Name, aPropInfo.Handle);
return aValue;
}
//-----------------------------------------------------------------------------
void SAL_CALL PropertySetHelper::addPropertyChangeListener(const ::rtl::OUString& sProperty,
const css::uno::Reference< css::beans::XPropertyChangeListener >& xListener)
throw(css::beans::UnknownPropertyException,
css::lang::WrappedTargetException ,
css::uno::RuntimeException )
{
TransactionGuard aTransaction(m_rTransactionManager, E_HARDEXCEPTIONS);
// SAFE ->
ReadGuard aReadLock(m_rLock);
PropertySetHelper::TPropInfoHash::const_iterator pIt = m_lProps.find(sProperty);
if (pIt == m_lProps.end())
throw css::beans::UnknownPropertyException();
aReadLock.unlock();
// <- SAFE
m_lSimpleChangeListener.addInterface(sProperty, xListener);
}
//-----------------------------------------------------------------------------
void SAL_CALL PropertySetHelper::removePropertyChangeListener(const ::rtl::OUString& sProperty,
const css::uno::Reference< css::beans::XPropertyChangeListener >& xListener)
throw(css::beans::UnknownPropertyException,
css::lang::WrappedTargetException ,
css::uno::RuntimeException )
{
TransactionGuard aTransaction(m_rTransactionManager, E_SOFTEXCEPTIONS);
// SAFE ->
ReadGuard aReadLock(m_rLock);
PropertySetHelper::TPropInfoHash::const_iterator pIt = m_lProps.find(sProperty);
if (pIt == m_lProps.end())
throw css::beans::UnknownPropertyException();
aReadLock.unlock();
// <- SAFE
m_lSimpleChangeListener.removeInterface(sProperty, xListener);
}
//-----------------------------------------------------------------------------
void SAL_CALL PropertySetHelper::addVetoableChangeListener(const ::rtl::OUString& sProperty,
const css::uno::Reference< css::beans::XVetoableChangeListener >& xListener)
throw(css::beans::UnknownPropertyException,
css::lang::WrappedTargetException ,
css::uno::RuntimeException )
{
TransactionGuard aTransaction(m_rTransactionManager, E_HARDEXCEPTIONS);
// SAFE ->
ReadGuard aReadLock(m_rLock);
PropertySetHelper::TPropInfoHash::const_iterator pIt = m_lProps.find(sProperty);
if (pIt == m_lProps.end())
throw css::beans::UnknownPropertyException();
aReadLock.unlock();
// <- SAFE
m_lVetoChangeListener.addInterface(sProperty, xListener);
}
//-----------------------------------------------------------------------------
void SAL_CALL PropertySetHelper::removeVetoableChangeListener(const ::rtl::OUString& sProperty,
const css::uno::Reference< css::beans::XVetoableChangeListener >& xListener)
throw(css::beans::UnknownPropertyException,
css::lang::WrappedTargetException ,
css::uno::RuntimeException )
{
TransactionGuard aTransaction(m_rTransactionManager, E_SOFTEXCEPTIONS);
// SAFE ->
ReadGuard aReadLock(m_rLock);
PropertySetHelper::TPropInfoHash::const_iterator pIt = m_lProps.find(sProperty);
if (pIt == m_lProps.end())
throw css::beans::UnknownPropertyException();
aReadLock.unlock();
// <- SAFE
m_lVetoChangeListener.removeInterface(sProperty, xListener);
}
//-----------------------------------------------------------------------------
css::uno::Sequence< css::beans::Property > SAL_CALL PropertySetHelper::getProperties()
throw(css::uno::RuntimeException)
{
TransactionGuard aTransaction(m_rTransactionManager, E_HARDEXCEPTIONS);
// SAFE ->
ReadGuard aReadLock(m_rLock);
sal_Int32 c = (sal_Int32)m_lProps.size();
css::uno::Sequence< css::beans::Property > lProps(c);
PropertySetHelper::TPropInfoHash::const_iterator pIt ;
for ( pIt = m_lProps.begin();
pIt != m_lProps.end() ;
++pIt )
{
lProps[--c] = pIt->second;
}
return lProps;
// <- SAFE
}
//-----------------------------------------------------------------------------
css::beans::Property SAL_CALL PropertySetHelper::getPropertyByName(const ::rtl::OUString& sName)
throw(css::beans::UnknownPropertyException,
css::uno::RuntimeException )
{
TransactionGuard aTransaction(m_rTransactionManager, E_HARDEXCEPTIONS);
// SAFE ->
ReadGuard aReadLock(m_rLock);
PropertySetHelper::TPropInfoHash::const_iterator pIt = m_lProps.find(sName);
if (pIt == m_lProps.end())
throw css::beans::UnknownPropertyException();
return pIt->second;
// <- SAFE
}
//-----------------------------------------------------------------------------
sal_Bool SAL_CALL PropertySetHelper::hasPropertyByName(const ::rtl::OUString& sName)
throw(css::uno::RuntimeException)
{
TransactionGuard aTransaction(m_rTransactionManager, E_HARDEXCEPTIONS);
// SAFE ->
ReadGuard aReadLock(m_rLock);
PropertySetHelper::TPropInfoHash::iterator pIt = m_lProps.find(sName);
sal_Bool bExist = (pIt != m_lProps.end());
return bExist;
// <- SAFE
}
} // namespace framework
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: registerservices.cxx,v $
*
* $Revision: 1.29 $
*
* last change: $Author: rt $ $Date: 2005-02-02 13:54:34 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
//_________________________________________________________________________________________________________________
// includes of my own project
//_________________________________________________________________________________________________________________
#ifndef __FRAMEWORK_MACROS_REGISTRATION_HXX_
#include <macros/registration.hxx>
#endif
/*=================================================================================================================
Add new include and new register info to for new services.
Example:
#ifndef __YOUR_SERVICE_1_HXX_
#include <service1.hxx>
#endif
#ifndef __YOUR_SERVICE_2_HXX_
#include <service2.hxx>
#endif
COMPONENTGETIMPLEMENTATIONENVIRONMENT
COMPONENTWRITEINFO ( COMPONENTINFO( Service1 )
COMPONENTINFO( Service2 )
)
COMPONENTGETFACTORY ( IFFACTORIE( Service1 )
else
IFFACTORIE( Service2 )
)
=================================================================================================================*/
#ifndef __FRAMEWORK_SERVICES_URLTRANSFORMER_HXX_
#include <services/urltransformer.hxx>
#endif
#ifndef __FRAMEWORK_SERVICES_DESKTOP_HXX_
#include <services/desktop.hxx>
#endif
#ifndef __FRAMEWORK_SERVICES_DOCUMENTPROPERTIES_HXX_
#include <services/documentproperties.hxx>
#endif
#ifndef __FRAMEWORK_SERVICES_FRAME_HXX_
#include <services/frame.hxx>
#endif
#ifndef __FRAMEWORK_SERVICES_MODULEMANAGER_HXX_
#include <services/modulemanager.hxx>
#endif
#ifndef __FRAMEWORK_JOBS_JOBEXECUTOR_HXX_
#include <jobs/jobexecutor.hxx>
#endif
#ifndef __FRAMEWORK_DISPATCH_SOUNDHANDLER_HXX_
#include <dispatch/soundhandler.hxx>
#endif
#ifndef __FRAMEWORK_RECORDING_DISPATCHRECORDERSUPPLIER_HXX_
#include <recording/dispatchrecordersupplier.hxx>
#endif
#ifndef __FRAMEWORK_RECORDING_DISPATCHRECORDER_HXX_
#include <recording/dispatchrecorder.hxx>
#endif
#ifndef __FRAMEWORK_DISPATCH_MAILTODISPATCHER_HXX_
#include <dispatch/mailtodispatcher.hxx>
#endif
#ifndef __FRAMEWORK_DISPATCH_SERVICEHANDLER_HXX_
#include <dispatch/servicehandler.hxx>
#endif
#ifndef __FRAMEWORK_JOBS_JOBDISPATCH_HXX_
#include <jobs/jobdispatch.hxx>
#endif
#ifndef __FRAMEWORK_SERVICES_BACKINGCOMP_HXX_
#include <services/backingcomp.hxx>
#endif
#ifndef __FRAMEWORK_SERVICES_DISPATCHHELPER_HXX_
#include <services/dispatchhelper.hxx>
#endif
#ifndef __FRAMEWORK_SERVICES_LAYOUTMANAGER_HXX_
#include <services/layoutmanager.hxx>
#endif
#ifndef __FRAMEWORK_SERVICES_LICENSE_HXX_
#include <services/license.hxx>
#endif
#ifndef __FRAMEWORK_UIFACTORY_UIELEMENTFACTORYMANAGER_HXX_
#include <uifactory/uielementfactorymanager.hxx>
#endif
#ifndef __FRAMEWORK_UIFACTORY_POPUPMENUCONTROLLERFACTORY_HXX_
#include <uifactory/popupmenucontrollerfactory.hxx>
#endif
#ifndef __FRAMEWORK_UIELEMENT_FONTMENUCONTROLLER_HXX_
#include <uielement/fontmenucontroller.hxx>
#endif
#ifndef __FRAMEWORK_UIELEMENT_FONTSIZEMENUCONTROLLER_HXX_
#include <uielement/fontsizemenucontroller.hxx>
#endif
#ifndef __FRAMEWORK_UIELEMENT_OBJECTMENUCONTROLLER_HXX_
#include <uielement/objectmenucontroller.hxx>
#endif
#ifndef __FRAMEWORK_UIELEMENT_HEADERMENUCONTROLLER_HXX_
#include <uielement/headermenucontroller.hxx>
#endif
#ifndef __FRAMEWORK_UIELEMENT_FOOTERMENUCONTROLLER_HXX_
#include <uielement/footermenucontroller.hxx>
#endif
#ifndef __FRAMEWORK_UIELEMENT_CONTROLMENUCONTROLLER_HXX_
#include <uielement/controlmenucontroller.hxx>
#endif
#ifndef __FRAMEWORK_UIELEMENT_MACROSMENUCONTROLLER_HXX_
#include <uielement/macrosmenucontroller.hxx>
#endif
#ifndef __FRAMEWORK_UIELEMENT_UICOMMANDDESCRIPTION_HXX_
#include <uielement/uicommanddescription.hxx>
#endif
#ifndef __FRAMEWORK_UICONFIGURATION_UICONFIGMANAGER_HXX_
#include <uiconfiguration/uiconfigurationmanager.hxx>
#endif
#ifndef __FRAMEWORK_UICONFIGURATION_MODULEUICFGSUPPLIER_HXX_
#include <uiconfiguration/moduleuicfgsupplier.hxx>
#endif
#ifndef __FRAMEWORK_UICONFIGURATION_MODULEUICONFIGMANAGER_HXX_
#include <uiconfiguration/moduleuiconfigurationmanager.hxx>
#endif
#ifndef __FRAMEWORK_UIFACTORY_MENUBARFACTORY_HXX_
#include <uifactory/menubarfactory.hxx>
#endif
#ifndef __FRAMEWORK_ACCELERATORS_GLOBALACCELERATORCONFIGURATION_HXX_
#include <accelerators/globalacceleratorconfiguration.hxx>
#endif
#ifndef __FRAMEWORK_ACCELERATORS_MODULEACCELERATORCONFIGURATION_HXX_
#include <accelerators/moduleacceleratorconfiguration.hxx>
#endif
#ifndef __FRAMEWORK_ACCELERATORS_DOCUMENTACCELERATORCONFIGURATION_HXX_
#include <accelerators/documentacceleratorconfiguration.hxx>
#endif
#ifndef __FRAMEWORK_UIFACTORY_TOOLBOXFACTORY_HXX_
#include <uifactory/toolboxfactory.hxx>
#endif
#ifndef __FRAMEWORK_UIFACTORY_ADDONSTOOLBOXFACTORY_HXX_
#include <uifactory/addonstoolboxfactory.hxx>
#endif
#ifndef __FRAMEWORK_UICONFIGURATION_WINDOWSTATECONFIGURATION_HXX_
#include "uiconfiguration/windowstateconfiguration.hxx"
#endif
#ifndef __FRAMEWORK_UIELEMENT_TOOLBARSMENUCONTROLLER_HXX_
#include <uielement/toolbarsmenucontroller.hxx>
#endif
#ifndef __FRAMEWORK_UIFACTORY_TOOLBARCONTROLLERFACTORY_HXX_
#include "uifactory/toolbarcontrollerfactory.hxx"
#endif
#ifndef __FRAMEWORK_UIFACTORY_STATUSBARCONTROLLERFACTORY_HXX_
#include "uifactory/statusbarcontrollerfactory.hxx"
#endif
#ifndef __FRAMEWORK_UIELEMENT_TOOLBARSMENUCONTROLLER_HXX_
#include <uielement/toolbarsmenucontroller.hxx>
#endif
#ifndef __FRAMEWORK_SERVICES_AUTORECOVERY_HXX_
#include <services/autorecovery.hxx>
#endif
#ifndef __FRAMEWORK_HELPER_STATUSINDICATORFACTORY_HXX_
#include <helper/statusindicatorfactory.hxx>
#endif
#ifndef __FRAMEWORK_UIELEMENT_RECENTFILESMENUCONTROLLER_HXX_
#include <uielement/recentfilesmenucontroller.hxx>
#endif
#ifndef __FRAMEWORK_UIFACTORY_STATUSBARFACTORY_HXX_
#include <uifactory/statusbarfactory.hxx>
#endif
#ifndef __FRAMEWORK_UIELEMENT_UICATEGORYDESCRPTION_HXX_
#include <uiconfiguration/uicategorydescription.hxx>
#endif
#ifndef __FRAMEWORK_SERVICES_SESSIONLISTENER_HXX_
#include <services/sessionlistener.hxx>
#endif
COMPONENTGETIMPLEMENTATIONENVIRONMENT
COMPONENTWRITEINFO ( COMPONENTINFO( ::framework::URLTransformer )
COMPONENTINFO( ::framework::Desktop )
COMPONENTINFO( ::framework::Frame )
COMPONENTINFO( ::framework::DocumentProperties )
COMPONENTINFO( ::framework::SoundHandler )
COMPONENTINFO( ::framework::JobExecutor )
COMPONENTINFO( ::framework::DispatchRecorderSupplier )
COMPONENTINFO( ::framework::DispatchRecorder )
COMPONENTINFO( ::framework::MailToDispatcher )
COMPONENTINFO( ::framework::ServiceHandler )
COMPONENTINFO( ::framework::JobDispatch )
COMPONENTINFO( ::framework::BackingComp )
COMPONENTINFO( ::framework::DispatchHelper )
COMPONENTINFO( ::framework::LayoutManager )
COMPONENTINFO( ::framework::License )
COMPONENTINFO( ::framework::UIElementFactoryManager )
COMPONENTINFO( ::framework::PopupMenuControllerFactory )
COMPONENTINFO( ::framework::FontMenuController )
COMPONENTINFO( ::framework::FontSizeMenuController )
COMPONENTINFO( ::framework::ObjectMenuController )
COMPONENTINFO( ::framework::HeaderMenuController )
COMPONENTINFO( ::framework::FooterMenuController )
COMPONENTINFO( ::framework::ControlMenuController )
COMPONENTINFO( ::framework::MacrosMenuController )
COMPONENTINFO( ::framework::UICommandDescription )
COMPONENTINFO( ::framework::ModuleManager )
COMPONENTINFO( ::framework::UIConfigurationManager )
COMPONENTINFO( ::framework::ModuleUIConfigurationManagerSupplier )
COMPONENTINFO( ::framework::ModuleUIConfigurationManager )
COMPONENTINFO( ::framework::MenuBarFactory )
COMPONENTINFO( ::framework::GlobalAcceleratorConfiguration )
COMPONENTINFO( ::framework::ModuleAcceleratorConfiguration )
COMPONENTINFO( ::framework::DocumentAcceleratorConfiguration )
COMPONENTINFO( ::framework::ToolBoxFactory )
COMPONENTINFO( ::framework::AddonsToolBoxFactory )
COMPONENTINFO( ::framework::WindowStateConfiguration )
COMPONENTINFO( ::framework::ToolbarControllerFactory )
COMPONENTINFO( ::framework::ToolbarsMenuController )
COMPONENTINFO( ::framework::AutoRecovery )
COMPONENTINFO( ::framework::StatusIndicatorFactory )
COMPONENTINFO( ::framework::RecentFilesMenuController )
COMPONENTINFO( ::framework::StatusBarFactory )
COMPONENTINFO( ::framework::UICategoryDescription )
COMPONENTINFO( ::framework::StatusbarControllerFactory )
COMPONENTINFO( ::framework::SessionListener )
)
COMPONENTGETFACTORY ( IFFACTORY( ::framework::URLTransformer ) else
IFFACTORY( ::framework::Desktop ) else
IFFACTORY( ::framework::Frame ) else
IFFACTORY( ::framework::DocumentProperties ) else
IFFACTORY( ::framework::SoundHandler ) else
IFFACTORY( ::framework::JobExecutor ) else
IFFACTORY( ::framework::DispatchRecorderSupplier ) else
IFFACTORY( ::framework::DispatchRecorder ) else
IFFACTORY( ::framework::MailToDispatcher ) else
IFFACTORY( ::framework::ServiceHandler ) else
IFFACTORY( ::framework::JobDispatch ) else
IFFACTORY( ::framework::BackingComp ) else
IFFACTORY( ::framework::DispatchHelper ) else
IFFACTORY( ::framework::LayoutManager ) else
IFFACTORY( ::framework::License ) else
IFFACTORY( ::framework::UIElementFactoryManager ) else
IFFACTORY( ::framework::PopupMenuControllerFactory ) else
IFFACTORY( ::framework::FontMenuController ) else
IFFACTORY( ::framework::FontSizeMenuController ) else
IFFACTORY( ::framework::ObjectMenuController ) else
IFFACTORY( ::framework::HeaderMenuController ) else
IFFACTORY( ::framework::FooterMenuController ) else
IFFACTORY( ::framework::ControlMenuController ) else
IFFACTORY( ::framework::MacrosMenuController ) else
IFFACTORY( ::framework::UICommandDescription ) else
IFFACTORY( ::framework::ModuleManager ) else
IFFACTORY( ::framework::UIConfigurationManager ) else
IFFACTORY( ::framework::ModuleUIConfigurationManagerSupplier ) else
IFFACTORY( ::framework::ModuleUIConfigurationManager ) else
IFFACTORY( ::framework::MenuBarFactory ) else
IFFACTORY( ::framework::GlobalAcceleratorConfiguration ) else
IFFACTORY( ::framework::ModuleAcceleratorConfiguration ) else
IFFACTORY( ::framework::DocumentAcceleratorConfiguration ) else
IFFACTORY( ::framework::ToolBoxFactory ) else
IFFACTORY( ::framework::AddonsToolBoxFactory ) else
IFFACTORY( ::framework::WindowStateConfiguration ) else
IFFACTORY( ::framework::ToolbarControllerFactory ) else
IFFACTORY( ::framework::ToolbarsMenuController ) else
IFFACTORY( ::framework::AutoRecovery ) else
IFFACTORY( ::framework::StatusIndicatorFactory ) else
IFFACTORY( ::framework::RecentFilesMenuController ) else
IFFACTORY( ::framework::StatusBarFactory ) else
IFFACTORY( ::framework::UICategoryDescription ) else
IFFACTORY( ::framework::StatusbarControllerFactory ) else
IFFACTORY( ::framework::SessionListener )
)
<commit_msg>INTEGRATION: CWS perform01 (1.28.38); FILE MERGED 2005/01/26 10:11:24 cd 1.28.38.1: #i40989# Performance and usability improvements<commit_after>/*************************************************************************
*
* $RCSfile: registerservices.cxx,v $
*
* $Revision: 1.30 $
*
* last change: $Author: vg $ $Date: 2005-02-16 16:42: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): _______________________________________
*
*
************************************************************************/
//_________________________________________________________________________________________________________________
// includes of my own project
//_________________________________________________________________________________________________________________
#ifndef __FRAMEWORK_MACROS_REGISTRATION_HXX_
#include <macros/registration.hxx>
#endif
/*=================================================================================================================
Add new include and new register info to for new services.
Example:
#ifndef __YOUR_SERVICE_1_HXX_
#include <service1.hxx>
#endif
#ifndef __YOUR_SERVICE_2_HXX_
#include <service2.hxx>
#endif
COMPONENTGETIMPLEMENTATIONENVIRONMENT
COMPONENTWRITEINFO ( COMPONENTINFO( Service1 )
COMPONENTINFO( Service2 )
)
COMPONENTGETFACTORY ( IFFACTORIE( Service1 )
else
IFFACTORIE( Service2 )
)
=================================================================================================================*/
#ifndef __FRAMEWORK_SERVICES_URLTRANSFORMER_HXX_
#include <services/urltransformer.hxx>
#endif
#ifndef __FRAMEWORK_SERVICES_DESKTOP_HXX_
#include <services/desktop.hxx>
#endif
#ifndef __FRAMEWORK_SERVICES_DOCUMENTPROPERTIES_HXX_
#include <services/documentproperties.hxx>
#endif
#ifndef __FRAMEWORK_SERVICES_FRAME_HXX_
#include <services/frame.hxx>
#endif
#ifndef __FRAMEWORK_SERVICES_MODULEMANAGER_HXX_
#include <services/modulemanager.hxx>
#endif
#ifndef __FRAMEWORK_JOBS_JOBEXECUTOR_HXX_
#include <jobs/jobexecutor.hxx>
#endif
#ifndef __FRAMEWORK_DISPATCH_SOUNDHANDLER_HXX_
#include <dispatch/soundhandler.hxx>
#endif
#ifndef __FRAMEWORK_RECORDING_DISPATCHRECORDERSUPPLIER_HXX_
#include <recording/dispatchrecordersupplier.hxx>
#endif
#ifndef __FRAMEWORK_RECORDING_DISPATCHRECORDER_HXX_
#include <recording/dispatchrecorder.hxx>
#endif
#ifndef __FRAMEWORK_DISPATCH_MAILTODISPATCHER_HXX_
#include <dispatch/mailtodispatcher.hxx>
#endif
#ifndef __FRAMEWORK_DISPATCH_SERVICEHANDLER_HXX_
#include <dispatch/servicehandler.hxx>
#endif
#ifndef __FRAMEWORK_JOBS_JOBDISPATCH_HXX_
#include <jobs/jobdispatch.hxx>
#endif
#ifndef __FRAMEWORK_SERVICES_BACKINGCOMP_HXX_
#include <services/backingcomp.hxx>
#endif
#ifndef __FRAMEWORK_SERVICES_DISPATCHHELPER_HXX_
#include <services/dispatchhelper.hxx>
#endif
#ifndef __FRAMEWORK_SERVICES_LAYOUTMANAGER_HXX_
#include <services/layoutmanager.hxx>
#endif
#ifndef __FRAMEWORK_SERVICES_LICENSE_HXX_
#include <services/license.hxx>
#endif
#ifndef __FRAMEWORK_UIFACTORY_UIELEMENTFACTORYMANAGER_HXX_
#include <uifactory/uielementfactorymanager.hxx>
#endif
#ifndef __FRAMEWORK_UIFACTORY_POPUPMENUCONTROLLERFACTORY_HXX_
#include <uifactory/popupmenucontrollerfactory.hxx>
#endif
#ifndef __FRAMEWORK_UIELEMENT_FONTMENUCONTROLLER_HXX_
#include <uielement/fontmenucontroller.hxx>
#endif
#ifndef __FRAMEWORK_UIELEMENT_FONTSIZEMENUCONTROLLER_HXX_
#include <uielement/fontsizemenucontroller.hxx>
#endif
#ifndef __FRAMEWORK_UIELEMENT_OBJECTMENUCONTROLLER_HXX_
#include <uielement/objectmenucontroller.hxx>
#endif
#ifndef __FRAMEWORK_UIELEMENT_HEADERMENUCONTROLLER_HXX_
#include <uielement/headermenucontroller.hxx>
#endif
#ifndef __FRAMEWORK_UIELEMENT_FOOTERMENUCONTROLLER_HXX_
#include <uielement/footermenucontroller.hxx>
#endif
#ifndef __FRAMEWORK_UIELEMENT_CONTROLMENUCONTROLLER_HXX_
#include <uielement/controlmenucontroller.hxx>
#endif
#ifndef __FRAMEWORK_UIELEMENT_MACROSMENUCONTROLLER_HXX_
#include <uielement/macrosmenucontroller.hxx>
#endif
#ifndef __FRAMEWORK_UIELEMENT_UICOMMANDDESCRIPTION_HXX_
#include <uielement/uicommanddescription.hxx>
#endif
#ifndef __FRAMEWORK_UICONFIGURATION_UICONFIGMANAGER_HXX_
#include <uiconfiguration/uiconfigurationmanager.hxx>
#endif
#ifndef __FRAMEWORK_UICONFIGURATION_MODULEUICFGSUPPLIER_HXX_
#include <uiconfiguration/moduleuicfgsupplier.hxx>
#endif
#ifndef __FRAMEWORK_UICONFIGURATION_MODULEUICONFIGMANAGER_HXX_
#include <uiconfiguration/moduleuiconfigurationmanager.hxx>
#endif
#ifndef __FRAMEWORK_UIFACTORY_MENUBARFACTORY_HXX_
#include <uifactory/menubarfactory.hxx>
#endif
#ifndef __FRAMEWORK_ACCELERATORS_GLOBALACCELERATORCONFIGURATION_HXX_
#include <accelerators/globalacceleratorconfiguration.hxx>
#endif
#ifndef __FRAMEWORK_ACCELERATORS_MODULEACCELERATORCONFIGURATION_HXX_
#include <accelerators/moduleacceleratorconfiguration.hxx>
#endif
#ifndef __FRAMEWORK_ACCELERATORS_DOCUMENTACCELERATORCONFIGURATION_HXX_
#include <accelerators/documentacceleratorconfiguration.hxx>
#endif
#ifndef __FRAMEWORK_UIFACTORY_TOOLBOXFACTORY_HXX_
#include <uifactory/toolboxfactory.hxx>
#endif
#ifndef __FRAMEWORK_UIFACTORY_ADDONSTOOLBOXFACTORY_HXX_
#include <uifactory/addonstoolboxfactory.hxx>
#endif
#ifndef __FRAMEWORK_UICONFIGURATION_WINDOWSTATECONFIGURATION_HXX_
#include "uiconfiguration/windowstateconfiguration.hxx"
#endif
#ifndef __FRAMEWORK_UIELEMENT_TOOLBARSMENUCONTROLLER_HXX_
#include <uielement/toolbarsmenucontroller.hxx>
#endif
#ifndef __FRAMEWORK_UIFACTORY_TOOLBARCONTROLLERFACTORY_HXX_
#include "uifactory/toolbarcontrollerfactory.hxx"
#endif
#ifndef __FRAMEWORK_UIFACTORY_STATUSBARCONTROLLERFACTORY_HXX_
#include "uifactory/statusbarcontrollerfactory.hxx"
#endif
#ifndef __FRAMEWORK_UIELEMENT_TOOLBARSMENUCONTROLLER_HXX_
#include <uielement/toolbarsmenucontroller.hxx>
#endif
#ifndef __FRAMEWORK_SERVICES_AUTORECOVERY_HXX_
#include <services/autorecovery.hxx>
#endif
#ifndef __FRAMEWORK_HELPER_STATUSINDICATORFACTORY_HXX_
#include <helper/statusindicatorfactory.hxx>
#endif
#ifndef __FRAMEWORK_UIELEMENT_RECENTFILESMENUCONTROLLER_HXX_
#include <uielement/recentfilesmenucontroller.hxx>
#endif
#ifndef __FRAMEWORK_UIFACTORY_STATUSBARFACTORY_HXX_
#include <uifactory/statusbarfactory.hxx>
#endif
#ifndef __FRAMEWORK_UIELEMENT_UICATEGORYDESCRPTION_HXX_
#include <uiconfiguration/uicategorydescription.hxx>
#endif
#ifndef __FRAMEWORK_SERVICES_SESSIONLISTENER_HXX_
#include <services/sessionlistener.hxx>
#endif
#ifndef __FRAMEWORK_UIELEMENT_NEWMENUCONTROLLER_HXX_
#include <uielement/newmenucontroller.hxx>
#endif
COMPONENTGETIMPLEMENTATIONENVIRONMENT
COMPONENTWRITEINFO ( COMPONENTINFO( ::framework::URLTransformer )
COMPONENTINFO( ::framework::Desktop )
COMPONENTINFO( ::framework::Frame )
COMPONENTINFO( ::framework::DocumentProperties )
COMPONENTINFO( ::framework::SoundHandler )
COMPONENTINFO( ::framework::JobExecutor )
COMPONENTINFO( ::framework::DispatchRecorderSupplier )
COMPONENTINFO( ::framework::DispatchRecorder )
COMPONENTINFO( ::framework::MailToDispatcher )
COMPONENTINFO( ::framework::ServiceHandler )
COMPONENTINFO( ::framework::JobDispatch )
COMPONENTINFO( ::framework::BackingComp )
COMPONENTINFO( ::framework::DispatchHelper )
COMPONENTINFO( ::framework::LayoutManager )
COMPONENTINFO( ::framework::License )
COMPONENTINFO( ::framework::UIElementFactoryManager )
COMPONENTINFO( ::framework::PopupMenuControllerFactory )
COMPONENTINFO( ::framework::FontMenuController )
COMPONENTINFO( ::framework::FontSizeMenuController )
COMPONENTINFO( ::framework::ObjectMenuController )
COMPONENTINFO( ::framework::HeaderMenuController )
COMPONENTINFO( ::framework::FooterMenuController )
COMPONENTINFO( ::framework::ControlMenuController )
COMPONENTINFO( ::framework::MacrosMenuController )
COMPONENTINFO( ::framework::UICommandDescription )
COMPONENTINFO( ::framework::ModuleManager )
COMPONENTINFO( ::framework::UIConfigurationManager )
COMPONENTINFO( ::framework::ModuleUIConfigurationManagerSupplier )
COMPONENTINFO( ::framework::ModuleUIConfigurationManager )
COMPONENTINFO( ::framework::MenuBarFactory )
COMPONENTINFO( ::framework::GlobalAcceleratorConfiguration )
COMPONENTINFO( ::framework::ModuleAcceleratorConfiguration )
COMPONENTINFO( ::framework::DocumentAcceleratorConfiguration )
COMPONENTINFO( ::framework::ToolBoxFactory )
COMPONENTINFO( ::framework::AddonsToolBoxFactory )
COMPONENTINFO( ::framework::WindowStateConfiguration )
COMPONENTINFO( ::framework::ToolbarControllerFactory )
COMPONENTINFO( ::framework::ToolbarsMenuController )
COMPONENTINFO( ::framework::AutoRecovery )
COMPONENTINFO( ::framework::StatusIndicatorFactory )
COMPONENTINFO( ::framework::RecentFilesMenuController )
COMPONENTINFO( ::framework::StatusBarFactory )
COMPONENTINFO( ::framework::UICategoryDescription )
COMPONENTINFO( ::framework::StatusbarControllerFactory )
COMPONENTINFO( ::framework::SessionListener )
COMPONENTINFO( ::framework::NewMenuController )
)
COMPONENTGETFACTORY ( IFFACTORY( ::framework::URLTransformer ) else
IFFACTORY( ::framework::Desktop ) else
IFFACTORY( ::framework::Frame ) else
IFFACTORY( ::framework::DocumentProperties ) else
IFFACTORY( ::framework::SoundHandler ) else
IFFACTORY( ::framework::JobExecutor ) else
IFFACTORY( ::framework::DispatchRecorderSupplier ) else
IFFACTORY( ::framework::DispatchRecorder ) else
IFFACTORY( ::framework::MailToDispatcher ) else
IFFACTORY( ::framework::ServiceHandler ) else
IFFACTORY( ::framework::JobDispatch ) else
IFFACTORY( ::framework::BackingComp ) else
IFFACTORY( ::framework::DispatchHelper ) else
IFFACTORY( ::framework::LayoutManager ) else
IFFACTORY( ::framework::License ) else
IFFACTORY( ::framework::UIElementFactoryManager ) else
IFFACTORY( ::framework::PopupMenuControllerFactory ) else
IFFACTORY( ::framework::FontMenuController ) else
IFFACTORY( ::framework::FontSizeMenuController ) else
IFFACTORY( ::framework::ObjectMenuController ) else
IFFACTORY( ::framework::HeaderMenuController ) else
IFFACTORY( ::framework::FooterMenuController ) else
IFFACTORY( ::framework::ControlMenuController ) else
IFFACTORY( ::framework::MacrosMenuController ) else
IFFACTORY( ::framework::UICommandDescription ) else
IFFACTORY( ::framework::ModuleManager ) else
IFFACTORY( ::framework::UIConfigurationManager ) else
IFFACTORY( ::framework::ModuleUIConfigurationManagerSupplier ) else
IFFACTORY( ::framework::ModuleUIConfigurationManager ) else
IFFACTORY( ::framework::MenuBarFactory ) else
IFFACTORY( ::framework::GlobalAcceleratorConfiguration ) else
IFFACTORY( ::framework::ModuleAcceleratorConfiguration ) else
IFFACTORY( ::framework::DocumentAcceleratorConfiguration ) else
IFFACTORY( ::framework::ToolBoxFactory ) else
IFFACTORY( ::framework::AddonsToolBoxFactory ) else
IFFACTORY( ::framework::WindowStateConfiguration ) else
IFFACTORY( ::framework::ToolbarControllerFactory ) else
IFFACTORY( ::framework::ToolbarsMenuController ) else
IFFACTORY( ::framework::AutoRecovery ) else
IFFACTORY( ::framework::StatusIndicatorFactory ) else
IFFACTORY( ::framework::RecentFilesMenuController ) else
IFFACTORY( ::framework::StatusBarFactory ) else
IFFACTORY( ::framework::UICategoryDescription ) else
IFFACTORY( ::framework::SessionListener )
else
IFFACTORY( ::framework::StatusbarControllerFactory ) else
IFFACTORY( ::framework::NewMenuController )
)
<|endoftext|>
|
<commit_before>//===-- RegAllocSimple.cpp - A simple generic register allocator --- ------===//
//
// This file implements a simple register allocator. *Very* simple.
//
//===----------------------------------------------------------------------===//
#include "llvm/Function.h"
#include "llvm/iTerminators.h"
#include "llvm/Type.h"
#include "llvm/Constants.h"
#include "llvm/Pass.h"
#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/Target/MachineInstrInfo.h"
#include "llvm/Target/MRegisterInfo.h"
#include "llvm/Target/MachineRegInfo.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Support/InstVisitor.h"
#include "Support/Statistic.h"
#include <map>
namespace {
struct RegAllocSimple : public FunctionPass {
TargetMachine &TM;
MachineBasicBlock *CurrMBB;
MachineFunction *MF;
unsigned maxOffset;
const MRegisterInfo *RegInfo;
unsigned NumBytesAllocated, ByteAlignment;
// Maps SSA Regs => offsets on the stack where these values are stored
// FIXME: change name to VirtReg2OffsetMap
std::map<unsigned, unsigned> RegMap;
// Maps SSA Regs => physical regs
std::map<unsigned, unsigned> SSA2PhysRegMap;
// Maps physical register to their register classes
std::map<unsigned, const TargetRegisterClass*> PhysReg2RegClassMap;
// Made to combat the incorrect allocation of r2 = add r1, r1
std::map<unsigned, unsigned> VirtReg2PhysRegMap;
// Maps RegClass => which index we can take a register from. Since this is a
// simple register allocator, when we need a register of a certain class, we
// just take the next available one.
std::map<unsigned, unsigned> RegsUsed;
std::map<const TargetRegisterClass*, unsigned> RegClassIdx;
RegAllocSimple(TargetMachine &tm) : TM(tm), CurrMBB(0), maxOffset(0),
RegInfo(tm.getRegisterInfo()),
ByteAlignment(4)
{
// build reverse mapping for physReg -> register class
RegInfo->buildReg2RegClassMap(PhysReg2RegClassMap);
RegsUsed[RegInfo->getFramePointer()] = 1;
RegsUsed[RegInfo->getStackPointer()] = 1;
cleanupAfterFunction();
}
bool isAvailableReg(unsigned Reg) {
// assert(Reg < MRegisterInfo::FirstVirtualReg && "...");
return RegsUsed.find(Reg) == RegsUsed.end();
}
///
unsigned allocateStackSpaceFor(unsigned VirtReg,
const TargetRegisterClass *regClass);
/// Given size (in bytes), returns a register that is currently unused
/// Side effect: marks that register as being used until manually cleared
unsigned getFreeReg(unsigned virtualReg);
/// Returns all `borrowed' registers back to the free pool
void clearAllRegs() {
RegClassIdx.clear();
}
/// Invalidates any references, real or implicit, to physical registers
///
void invalidatePhysRegs(const MachineInstr *MI) {
unsigned Opcode = MI->getOpcode();
const MachineInstrInfo &MII = TM.getInstrInfo();
const MachineInstrDescriptor &Desc = MII.get(Opcode);
const unsigned *regs = Desc.ImplicitUses;
while (*regs)
RegsUsed[*regs++] = 1;
regs = Desc.ImplicitDefs;
while (*regs)
RegsUsed[*regs++] = 1;
/*
for (int i = MI->getNumOperands() - 1; i >= 0; --i) {
const MachineOperand &op = MI->getOperand(i);
if (op.isMachineRegister())
RegsUsed[op.getAllocatedRegNum()] = 1;
}
for (int i = MI->getNumImplicitRefs() - 1; i >= 0; --i) {
const MachineOperand &op = MI->getImplicitOp(i);
if (op.isMachineRegister())
RegsUsed[op.getAllocatedRegNum()] = 1;
}
*/
}
void cleanupAfterFunction() {
RegMap.clear();
SSA2PhysRegMap.clear();
NumBytesAllocated = ByteAlignment;
}
/// Moves value from memory into that register
MachineBasicBlock::iterator
moveUseToReg (MachineBasicBlock *MBB,
MachineBasicBlock::iterator I, unsigned VirtReg,
unsigned &PhysReg);
/// Saves reg value on the stack (maps virtual register to stack value)
MachineBasicBlock::iterator
saveVirtRegToStack (MachineBasicBlock *MBB,
MachineBasicBlock::iterator I, unsigned VirtReg,
unsigned PhysReg);
MachineBasicBlock::iterator
savePhysRegToStack (MachineBasicBlock *MBB,
MachineBasicBlock::iterator I, unsigned PhysReg);
/// runOnFunction - Top level implementation of instruction selection for
/// the entire function.
///
bool runOnMachineFunction(MachineFunction &Fn);
bool runOnFunction(Function &Fn) {
return runOnMachineFunction(MachineFunction::get(&Fn));
}
};
}
unsigned RegAllocSimple::allocateStackSpaceFor(unsigned VirtReg,
const TargetRegisterClass *regClass)
{
if (RegMap.find(VirtReg) == RegMap.end()) {
#if 0
unsigned size = regClass->getDataSize();
unsigned over = NumBytesAllocated - (NumBytesAllocated % ByteAlignment);
if (size >= ByteAlignment - over) {
// need to pad by (ByteAlignment - over)
NumBytesAllocated += ByteAlignment - over;
}
RegMap[VirtReg] = NumBytesAllocated;
NumBytesAllocated += size;
#endif
// FIXME: forcing each arg to take 4 bytes on the stack
RegMap[VirtReg] = NumBytesAllocated;
NumBytesAllocated += ByteAlignment;
}
return RegMap[VirtReg];
}
unsigned RegAllocSimple::getFreeReg(unsigned virtualReg) {
const TargetRegisterClass* regClass = MF->getRegClass(virtualReg);
unsigned physReg;
assert(regClass);
if (RegClassIdx.find(regClass) != RegClassIdx.end()) {
unsigned regIdx = RegClassIdx[regClass]++;
assert(regIdx < regClass->getNumRegs() && "Not enough registers!");
physReg = regClass->getRegister(regIdx);
} else {
physReg = regClass->getRegister(0);
// assert(physReg < regClass->getNumRegs() && "No registers in class!");
RegClassIdx[regClass] = 1;
}
if (isAvailableReg(physReg))
return physReg;
else {
return getFreeReg(virtualReg);
}
}
MachineBasicBlock::iterator
RegAllocSimple::moveUseToReg (MachineBasicBlock *MBB,
MachineBasicBlock::iterator I,
unsigned VirtReg, unsigned &PhysReg)
{
const TargetRegisterClass* regClass = MF->getRegClass(VirtReg);
assert(regClass);
unsigned stackOffset = allocateStackSpaceFor(VirtReg, regClass);
PhysReg = getFreeReg(VirtReg);
// Add move instruction(s)
return RegInfo->loadRegOffset2Reg(MBB, I, PhysReg,
RegInfo->getFramePointer(),
-stackOffset, regClass->getDataSize());
}
MachineBasicBlock::iterator
RegAllocSimple::saveVirtRegToStack (MachineBasicBlock *MBB,
MachineBasicBlock::iterator I,
unsigned VirtReg, unsigned PhysReg)
{
const TargetRegisterClass* regClass = MF->getRegClass(VirtReg);
assert(regClass);
unsigned stackOffset = allocateStackSpaceFor(VirtReg, regClass);
// Add move instruction(s)
return RegInfo->storeReg2RegOffset(MBB, I, PhysReg,
RegInfo->getFramePointer(),
-stackOffset, regClass->getDataSize());
}
MachineBasicBlock::iterator
RegAllocSimple::savePhysRegToStack (MachineBasicBlock *MBB,
MachineBasicBlock::iterator I,
unsigned PhysReg)
{
const TargetRegisterClass* regClass = MF->getRegClass(PhysReg);
assert(regClass);
unsigned offset = allocateStackSpaceFor(PhysReg, regClass);
// Add move instruction(s)
return RegInfo->storeReg2RegOffset(MBB, I, PhysReg,
RegInfo->getFramePointer(),
offset, regClass->getDataSize());
}
bool RegAllocSimple::runOnMachineFunction(MachineFunction &Fn) {
cleanupAfterFunction();
unsigned virtualReg, physReg;
DEBUG(std::cerr << "Machine Function " << "\n");
MF = &Fn;
for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
MBB != MBBe; ++MBB)
{
CurrMBB = &(*MBB);
// Handle PHI instructions specially: add moves to each pred block
while (MBB->front()->getOpcode() == 0) {
MachineInstr *MI = MBB->front();
// get rid of the phi
MBB->erase(MBB->begin());
// a preliminary pass that will invalidate any registers that
// are used by the instruction (including implicit uses)
invalidatePhysRegs(MI);
DEBUG(std::cerr << "num invalid regs: " << RegsUsed.size() << "\n");
DEBUG(std::cerr << "num ops: " << MI->getNumOperands() << "\n");
MachineOperand &targetReg = MI->getOperand(0);
// If it's a virtual register, allocate a physical one
// otherwise, just use whatever register is there now
// note: it MUST be a register -- we're assigning to it
virtualReg = (unsigned) targetReg.getAllocatedRegNum();
if (targetReg.isVirtualRegister()) {
physReg = getFreeReg(virtualReg);
} else {
physReg = targetReg.getAllocatedRegNum();
}
// Find the register class of the target register: should be the
// same as the values we're trying to store there
const TargetRegisterClass* regClass = PhysReg2RegClassMap[physReg];
assert(regClass && "Target register class not found!");
unsigned dataSize = regClass->getDataSize();
for (int i = MI->getNumOperands() - 1; i >= 2; i-=2) {
MachineOperand &opVal = MI->getOperand(i-1);
// Get the MachineBasicBlock equivalent of the BasicBlock that is the
// source path the phi
BasicBlock *opBB =
cast<BasicBlock>(MI->getOperand(i).getVRegValue());
MachineBasicBlock *opBlock = NULL;
for (MachineFunction::iterator opFi = Fn.begin(), opFe = Fn.end();
opFi != opFe; ++opFi)
{
if (opFi->getBasicBlock() == opBB) {
opBlock = opFi; break;
}
}
assert(opBlock && "MachineBasicBlock object not found for specified block!");
MachineBasicBlock::iterator opI = opBlock->end();
MachineInstr *opMI = *(--opI);
const MachineInstrInfo &MII = TM.getInstrInfo();
// insert the move just before the return/branch
if (MII.isReturn(opMI->getOpcode()) || MII.isBranch(opMI->getOpcode()))
{
// Retrieve the constant value from this op, move it to target
// register of the phi
if (opVal.getType() == MachineOperand::MO_SignExtendedImmed ||
opVal.getType() == MachineOperand::MO_UnextendedImmed)
{
opI = RegInfo->moveImm2Reg(opBlock, opI, physReg,
(unsigned) opVal.getImmedValue(),
dataSize);
saveVirtRegToStack(opBlock, opI, virtualReg, physReg);
} else {
// Allocate a physical register and add a move in the BB
unsigned opVirtualReg = (unsigned) opVal.getAllocatedRegNum();
unsigned opPhysReg; // = getFreeReg(opVirtualReg);
opI = moveUseToReg(opBlock, opI, opVirtualReg, opPhysReg);
opI = RegInfo->moveReg2Reg(opBlock, opI, physReg, opPhysReg,
dataSize);
// Save that register value to the stack of the TARGET REG
saveVirtRegToStack(opBlock, opI, virtualReg, opPhysReg);
}
}
// make regs available to other instructions
clearAllRegs();
}
// really delete the instruction
delete MI;
}
//loop over each basic block
for (MachineBasicBlock::iterator I = MBB->begin(); I != MBB->end(); ++I)
{
MachineInstr *MI = *I;
// a preliminary pass that will invalidate any registers that
// are used by the instruction (including implicit uses)
invalidatePhysRegs(MI);
// Loop over uses, move from memory into registers
for (int i = MI->getNumOperands() - 1; i >= 0; --i) {
MachineOperand &op = MI->getOperand(i);
if (op.getType() == MachineOperand::MO_SignExtendedImmed ||
op.getType() == MachineOperand::MO_UnextendedImmed)
{
DEBUG(std::cerr << "const\n");
} else if (op.isVirtualRegister()) {
virtualReg = (unsigned) op.getAllocatedRegNum();
DEBUG(std::cerr << "op: " << op << "\n");
DEBUG(std::cerr << "\t inst[" << i << "]: ";
MI->print(std::cerr, TM));
// make sure the same virtual register maps to the same physical
// register in any given instruction
if (VirtReg2PhysRegMap.find(virtualReg) != VirtReg2PhysRegMap.end()) {
physReg = VirtReg2PhysRegMap[virtualReg];
} else {
if (op.opIsDef()) {
if (TM.getInstrInfo().isTwoAddrInstr(MI->getOpcode()) && i == 0) {
// must be same register number as the first operand
// This maps a = b + c into b += c, and saves b into a's spot
physReg = (unsigned) MI->getOperand(1).getAllocatedRegNum();
} else {
physReg = getFreeReg(virtualReg);
}
MachineBasicBlock::iterator J = I;
J = saveVirtRegToStack(CurrMBB, ++J, virtualReg, physReg);
I = --J;
} else {
I = moveUseToReg(CurrMBB, I, virtualReg, physReg);
}
VirtReg2PhysRegMap[virtualReg] = physReg;
}
MI->SetMachineOperandReg(i, physReg);
DEBUG(std::cerr << "virt: " << virtualReg <<
", phys: " << op.getAllocatedRegNum() << "\n");
}
}
clearAllRegs();
VirtReg2PhysRegMap.clear();
}
}
// add prologue we should preserve callee-save registers...
MachineFunction::iterator Fi = Fn.begin();
MachineBasicBlock *MBB = Fi;
MachineBasicBlock::iterator MBBi = MBB->begin();
RegInfo->emitPrologue(MBB, MBBi, NumBytesAllocated);
// add epilogue to restore the callee-save registers
// loop over the basic block
for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
MBB != MBBe; ++MBB)
{
// check if last instruction is a RET
MachineBasicBlock::iterator I = (*MBB).end();
MachineInstr *MI = *(--I);
const MachineInstrInfo &MII = TM.getInstrInfo();
if (MII.isReturn(MI->getOpcode())) {
// this block has a return instruction, add epilogue
RegInfo->emitEpilogue(MBB, I, NumBytesAllocated);
}
}
return false; // We never modify the LLVM itself.
}
Pass *createSimpleX86RegisterAllocator(TargetMachine &TM) {
return new RegAllocSimple(TM);
}
<commit_msg>Need to insert all moves due to PHI nodes before *ALL* jumps in a predecessor basic block, as there could be multiple.<commit_after>//===-- RegAllocSimple.cpp - A simple generic register allocator --- ------===//
//
// This file implements a simple register allocator. *Very* simple.
//
//===----------------------------------------------------------------------===//
#include "llvm/Function.h"
#include "llvm/iTerminators.h"
#include "llvm/Type.h"
#include "llvm/Constants.h"
#include "llvm/Pass.h"
#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/Target/MachineInstrInfo.h"
#include "llvm/Target/MRegisterInfo.h"
#include "llvm/Target/MachineRegInfo.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Support/InstVisitor.h"
#include "Support/Statistic.h"
#include <map>
namespace {
struct RegAllocSimple : public FunctionPass {
TargetMachine &TM;
MachineBasicBlock *CurrMBB;
MachineFunction *MF;
unsigned maxOffset;
const MRegisterInfo *RegInfo;
unsigned NumBytesAllocated, ByteAlignment;
// Maps SSA Regs => offsets on the stack where these values are stored
// FIXME: change name to VirtReg2OffsetMap
std::map<unsigned, unsigned> RegMap;
// Maps SSA Regs => physical regs
std::map<unsigned, unsigned> SSA2PhysRegMap;
// Maps physical register to their register classes
std::map<unsigned, const TargetRegisterClass*> PhysReg2RegClassMap;
// Made to combat the incorrect allocation of r2 = add r1, r1
std::map<unsigned, unsigned> VirtReg2PhysRegMap;
// Maps RegClass => which index we can take a register from. Since this is a
// simple register allocator, when we need a register of a certain class, we
// just take the next available one.
std::map<unsigned, unsigned> RegsUsed;
std::map<const TargetRegisterClass*, unsigned> RegClassIdx;
RegAllocSimple(TargetMachine &tm) : TM(tm), CurrMBB(0), maxOffset(0),
RegInfo(tm.getRegisterInfo()),
ByteAlignment(4)
{
// build reverse mapping for physReg -> register class
RegInfo->buildReg2RegClassMap(PhysReg2RegClassMap);
RegsUsed[RegInfo->getFramePointer()] = 1;
RegsUsed[RegInfo->getStackPointer()] = 1;
cleanupAfterFunction();
}
bool isAvailableReg(unsigned Reg) {
// assert(Reg < MRegisterInfo::FirstVirtualReg && "...");
return RegsUsed.find(Reg) == RegsUsed.end();
}
///
unsigned allocateStackSpaceFor(unsigned VirtReg,
const TargetRegisterClass *regClass);
/// Given size (in bytes), returns a register that is currently unused
/// Side effect: marks that register as being used until manually cleared
unsigned getFreeReg(unsigned virtualReg);
/// Returns all `borrowed' registers back to the free pool
void clearAllRegs() {
RegClassIdx.clear();
}
/// Invalidates any references, real or implicit, to physical registers
///
void invalidatePhysRegs(const MachineInstr *MI) {
unsigned Opcode = MI->getOpcode();
const MachineInstrInfo &MII = TM.getInstrInfo();
const MachineInstrDescriptor &Desc = MII.get(Opcode);
const unsigned *regs = Desc.ImplicitUses;
while (*regs)
RegsUsed[*regs++] = 1;
regs = Desc.ImplicitDefs;
while (*regs)
RegsUsed[*regs++] = 1;
}
void cleanupAfterFunction() {
RegMap.clear();
SSA2PhysRegMap.clear();
NumBytesAllocated = ByteAlignment;
}
/// Moves value from memory into that register
MachineBasicBlock::iterator
moveUseToReg (MachineBasicBlock *MBB,
MachineBasicBlock::iterator I, unsigned VirtReg,
unsigned &PhysReg);
/// Saves reg value on the stack (maps virtual register to stack value)
MachineBasicBlock::iterator
saveVirtRegToStack (MachineBasicBlock *MBB,
MachineBasicBlock::iterator I, unsigned VirtReg,
unsigned PhysReg);
MachineBasicBlock::iterator
savePhysRegToStack (MachineBasicBlock *MBB,
MachineBasicBlock::iterator I, unsigned PhysReg);
/// runOnFunction - Top level implementation of instruction selection for
/// the entire function.
///
bool runOnMachineFunction(MachineFunction &Fn);
bool runOnFunction(Function &Fn) {
return runOnMachineFunction(MachineFunction::get(&Fn));
}
};
}
unsigned RegAllocSimple::allocateStackSpaceFor(unsigned VirtReg,
const TargetRegisterClass *regClass)
{
if (RegMap.find(VirtReg) == RegMap.end()) {
#if 0
unsigned size = regClass->getDataSize();
unsigned over = NumBytesAllocated - (NumBytesAllocated % ByteAlignment);
if (size >= ByteAlignment - over) {
// need to pad by (ByteAlignment - over)
NumBytesAllocated += ByteAlignment - over;
}
RegMap[VirtReg] = NumBytesAllocated;
NumBytesAllocated += size;
#endif
// FIXME: forcing each arg to take 4 bytes on the stack
RegMap[VirtReg] = NumBytesAllocated;
NumBytesAllocated += ByteAlignment;
}
return RegMap[VirtReg];
}
unsigned RegAllocSimple::getFreeReg(unsigned virtualReg) {
const TargetRegisterClass* regClass = MF->getRegClass(virtualReg);
unsigned physReg;
assert(regClass);
if (RegClassIdx.find(regClass) != RegClassIdx.end()) {
unsigned regIdx = RegClassIdx[regClass]++;
assert(regIdx < regClass->getNumRegs() && "Not enough registers!");
physReg = regClass->getRegister(regIdx);
} else {
physReg = regClass->getRegister(0);
// assert(physReg < regClass->getNumRegs() && "No registers in class!");
RegClassIdx[regClass] = 1;
}
if (isAvailableReg(physReg))
return physReg;
else {
return getFreeReg(virtualReg);
}
}
MachineBasicBlock::iterator
RegAllocSimple::moveUseToReg (MachineBasicBlock *MBB,
MachineBasicBlock::iterator I,
unsigned VirtReg, unsigned &PhysReg)
{
const TargetRegisterClass* regClass = MF->getRegClass(VirtReg);
assert(regClass);
unsigned stackOffset = allocateStackSpaceFor(VirtReg, regClass);
PhysReg = getFreeReg(VirtReg);
// Add move instruction(s)
return RegInfo->loadRegOffset2Reg(MBB, I, PhysReg,
RegInfo->getFramePointer(),
-stackOffset, regClass->getDataSize());
}
MachineBasicBlock::iterator
RegAllocSimple::saveVirtRegToStack (MachineBasicBlock *MBB,
MachineBasicBlock::iterator I,
unsigned VirtReg, unsigned PhysReg)
{
const TargetRegisterClass* regClass = MF->getRegClass(VirtReg);
assert(regClass);
unsigned stackOffset = allocateStackSpaceFor(VirtReg, regClass);
// Add move instruction(s)
return RegInfo->storeReg2RegOffset(MBB, I, PhysReg,
RegInfo->getFramePointer(),
-stackOffset, regClass->getDataSize());
}
MachineBasicBlock::iterator
RegAllocSimple::savePhysRegToStack (MachineBasicBlock *MBB,
MachineBasicBlock::iterator I,
unsigned PhysReg)
{
const TargetRegisterClass* regClass = MF->getRegClass(PhysReg);
assert(regClass);
unsigned offset = allocateStackSpaceFor(PhysReg, regClass);
// Add move instruction(s)
return RegInfo->storeReg2RegOffset(MBB, I, PhysReg,
RegInfo->getFramePointer(),
offset, regClass->getDataSize());
}
bool RegAllocSimple::runOnMachineFunction(MachineFunction &Fn) {
cleanupAfterFunction();
unsigned virtualReg, physReg;
DEBUG(std::cerr << "Machine Function " << "\n");
MF = &Fn;
for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
MBB != MBBe; ++MBB)
{
CurrMBB = &(*MBB);
// Handle PHI instructions specially: add moves to each pred block
while (MBB->front()->getOpcode() == 0) {
MachineInstr *MI = MBB->front();
// get rid of the phi
MBB->erase(MBB->begin());
// a preliminary pass that will invalidate any registers that
// are used by the instruction (including implicit uses)
invalidatePhysRegs(MI);
DEBUG(std::cerr << "num invalid regs: " << RegsUsed.size() << "\n");
DEBUG(std::cerr << "num ops: " << MI->getNumOperands() << "\n");
MachineOperand &targetReg = MI->getOperand(0);
// If it's a virtual register, allocate a physical one
// otherwise, just use whatever register is there now
// note: it MUST be a register -- we're assigning to it
virtualReg = (unsigned) targetReg.getAllocatedRegNum();
if (targetReg.isVirtualRegister()) {
physReg = getFreeReg(virtualReg);
} else {
physReg = targetReg.getAllocatedRegNum();
}
// Find the register class of the target register: should be the
// same as the values we're trying to store there
const TargetRegisterClass* regClass = PhysReg2RegClassMap[physReg];
assert(regClass && "Target register class not found!");
unsigned dataSize = regClass->getDataSize();
for (int i = MI->getNumOperands() - 1; i >= 2; i-=2) {
MachineOperand &opVal = MI->getOperand(i-1);
// Get the MachineBasicBlock equivalent of the BasicBlock that is the
// source path the phi
BasicBlock *opBB =
cast<BasicBlock>(MI->getOperand(i).getVRegValue());
MachineBasicBlock *opBlock = NULL;
for (MachineFunction::iterator opFi = Fn.begin(), opFe = Fn.end();
opFi != opFe; ++opFi)
{
if (opFi->getBasicBlock() == opBB) {
opBlock = opFi; break;
}
}
assert(opBlock && "MachineBasicBlock object not found for specified block!");
MachineBasicBlock::iterator opI = opBlock->end();
MachineInstr *opMI = *(--opI);
const MachineInstrInfo &MII = TM.getInstrInfo();
// must backtrack over ALL the branches in the previous block, until no more
while ((MII.isBranch(opMI->getOpcode()) || MII.isReturn(opMI->getOpcode()))
&& opI != opBlock->begin())
{
opMI = *(--opI);
}
// move back to the first branch instruction so new instructions
// are inserted right in front of it and not in front of a non-branch
++opI;
// insert the move just before the return/branch
if (MII.isReturn(opMI->getOpcode()) || MII.isBranch(opMI->getOpcode()))
{
// Retrieve the constant value from this op, move it to target
// register of the phi
if (opVal.getType() == MachineOperand::MO_SignExtendedImmed ||
opVal.getType() == MachineOperand::MO_UnextendedImmed)
{
opI = RegInfo->moveImm2Reg(opBlock, opI, physReg,
(unsigned) opVal.getImmedValue(),
dataSize);
saveVirtRegToStack(opBlock, opI, virtualReg, physReg);
} else {
// Allocate a physical register and add a move in the BB
unsigned opVirtualReg = (unsigned) opVal.getAllocatedRegNum();
unsigned opPhysReg; // = getFreeReg(opVirtualReg);
opI = moveUseToReg(opBlock, opI, opVirtualReg, opPhysReg);
opI = RegInfo->moveReg2Reg(opBlock, opI, physReg, opPhysReg,
dataSize);
// Save that register value to the stack of the TARGET REG
saveVirtRegToStack(opBlock, opI, virtualReg, opPhysReg);
}
}
// make regs available to other instructions
clearAllRegs();
}
// really delete the instruction
delete MI;
}
//loop over each basic block
for (MachineBasicBlock::iterator I = MBB->begin(); I != MBB->end(); ++I)
{
MachineInstr *MI = *I;
// a preliminary pass that will invalidate any registers that
// are used by the instruction (including implicit uses)
invalidatePhysRegs(MI);
// Loop over uses, move from memory into registers
for (int i = MI->getNumOperands() - 1; i >= 0; --i) {
MachineOperand &op = MI->getOperand(i);
if (op.getType() == MachineOperand::MO_SignExtendedImmed ||
op.getType() == MachineOperand::MO_UnextendedImmed)
{
DEBUG(std::cerr << "const\n");
} else if (op.isVirtualRegister()) {
virtualReg = (unsigned) op.getAllocatedRegNum();
DEBUG(std::cerr << "op: " << op << "\n");
DEBUG(std::cerr << "\t inst[" << i << "]: ";
MI->print(std::cerr, TM));
// make sure the same virtual register maps to the same physical
// register in any given instruction
if (VirtReg2PhysRegMap.find(virtualReg) != VirtReg2PhysRegMap.end()) {
physReg = VirtReg2PhysRegMap[virtualReg];
} else {
if (op.opIsDef()) {
if (TM.getInstrInfo().isTwoAddrInstr(MI->getOpcode()) && i == 0) {
// must be same register number as the first operand
// This maps a = b + c into b += c, and saves b into a's spot
physReg = (unsigned) MI->getOperand(1).getAllocatedRegNum();
} else {
physReg = getFreeReg(virtualReg);
}
MachineBasicBlock::iterator J = I;
J = saveVirtRegToStack(CurrMBB, ++J, virtualReg, physReg);
I = --J;
} else {
I = moveUseToReg(CurrMBB, I, virtualReg, physReg);
}
VirtReg2PhysRegMap[virtualReg] = physReg;
}
MI->SetMachineOperandReg(i, physReg);
DEBUG(std::cerr << "virt: " << virtualReg <<
", phys: " << op.getAllocatedRegNum() << "\n");
}
}
clearAllRegs();
VirtReg2PhysRegMap.clear();
}
}
// add prologue we should preserve callee-save registers...
MachineFunction::iterator Fi = Fn.begin();
MachineBasicBlock *MBB = Fi;
MachineBasicBlock::iterator MBBi = MBB->begin();
RegInfo->emitPrologue(MBB, MBBi, NumBytesAllocated);
// add epilogue to restore the callee-save registers
// loop over the basic block
for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
MBB != MBBe; ++MBB)
{
// check if last instruction is a RET
MachineBasicBlock::iterator I = (*MBB).end();
MachineInstr *MI = *(--I);
const MachineInstrInfo &MII = TM.getInstrInfo();
if (MII.isReturn(MI->getOpcode())) {
// this block has a return instruction, add epilogue
RegInfo->emitEpilogue(MBB, I, NumBytesAllocated);
}
}
return false; // We never modify the LLVM itself.
}
Pass *createSimpleX86RegisterAllocator(TargetMachine &TM) {
return new RegAllocSimple(TM);
}
<|endoftext|>
|
<commit_before>//===--- REPLCodeCompletion.cpp - Code completion for REPL ----------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This module provides completions to the immediate mode environment.
//
//===----------------------------------------------------------------------===//
#include "swift/IDE/REPLCodeCompletion.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/Module.h"
#include "swift/Basic/LLVM.h"
#include "swift/Basic/SourceManager.h"
#include "swift/Parse/DelayedParsingCallbacks.h"
#include "swift/Parse/Parser.h"
#include "swift/IDE/CodeCompletion.h"
#include "swift/Subsystems.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/ADT/SmallString.h"
#include <algorithm>
using namespace swift;
using namespace ide;
static std::string toInsertableString(CodeCompletionResult *Result) {
std::string Str;
for (auto C : Result->getCompletionString()->getChunks()) {
switch (C.getKind()) {
case CodeCompletionString::Chunk::ChunkKind::AccessControlKeyword:
case CodeCompletionString::Chunk::ChunkKind::OverrideKeyword:
case CodeCompletionString::Chunk::ChunkKind::ThrowsKeyword:
case CodeCompletionString::Chunk::ChunkKind::RethrowsKeyword:
case CodeCompletionString::Chunk::ChunkKind::DeclAttrKeyword:
case CodeCompletionString::Chunk::ChunkKind::DeclIntroducer:
case CodeCompletionString::Chunk::ChunkKind::Text:
case CodeCompletionString::Chunk::ChunkKind::LeftParen:
case CodeCompletionString::Chunk::ChunkKind::RightParen:
case CodeCompletionString::Chunk::ChunkKind::LeftBracket:
case CodeCompletionString::Chunk::ChunkKind::RightBracket:
case CodeCompletionString::Chunk::ChunkKind::LeftAngle:
case CodeCompletionString::Chunk::ChunkKind::RightAngle:
case CodeCompletionString::Chunk::ChunkKind::Dot:
case CodeCompletionString::Chunk::ChunkKind::Ellipsis:
case CodeCompletionString::Chunk::ChunkKind::Comma:
case CodeCompletionString::Chunk::ChunkKind::ExclamationMark:
case CodeCompletionString::Chunk::ChunkKind::QuestionMark:
case CodeCompletionString::Chunk::ChunkKind::Ampersand:
case CodeCompletionString::Chunk::ChunkKind::Equal:
case CodeCompletionString::Chunk::ChunkKind::Whitespace:
case CodeCompletionString::Chunk::ChunkKind::DynamicLookupMethodCallTail:
case CodeCompletionString::Chunk::ChunkKind::OptionalMethodCallTail:
if (!C.isAnnotation())
Str += C.getText();
break;
case CodeCompletionString::Chunk::ChunkKind::CallParameterName:
case CodeCompletionString::Chunk::ChunkKind::CallParameterInternalName:
case CodeCompletionString::Chunk::ChunkKind::CallParameterColon:
case CodeCompletionString::Chunk::ChunkKind::DeclAttrParamKeyword:
case CodeCompletionString::Chunk::ChunkKind::DeclAttrParamColon:
case CodeCompletionString::Chunk::ChunkKind::CallParameterType:
case CodeCompletionString::Chunk::ChunkKind::CallParameterClosureType:
case CodeCompletionString::Chunk::ChunkKind::OptionalBegin:
case CodeCompletionString::Chunk::ChunkKind::CallParameterBegin:
case CodeCompletionString::Chunk::ChunkKind::GenericParameterBegin:
case CodeCompletionString::Chunk::ChunkKind::GenericParameterName:
case CodeCompletionString::Chunk::ChunkKind::TypeAnnotation:
return Str;
case CodeCompletionString::Chunk::ChunkKind::BraceStmtWithCursor:
Str += " {";
break;
}
}
return Str;
}
static void toDisplayString(CodeCompletionResult *Result,
llvm::raw_ostream &OS) {
std::string Str;
for (auto C : Result->getCompletionString()->getChunks()) {
if (C.getKind() ==
CodeCompletionString::Chunk::ChunkKind::BraceStmtWithCursor) {
OS << ' ';
continue;
}
if (!C.isAnnotation() && C.hasText()) {
OS << C.getText();
continue;
}
if (C.getKind() == CodeCompletionString::Chunk::ChunkKind::TypeAnnotation) {
if (Result->getKind() == CodeCompletionResult::Declaration) {
switch (Result->getAssociatedDeclKind()) {
case CodeCompletionDeclKind::Module:
case CodeCompletionDeclKind::PrecedenceGroup:
case CodeCompletionDeclKind::Class:
case CodeCompletionDeclKind::Struct:
case CodeCompletionDeclKind::Enum:
continue;
case CodeCompletionDeclKind::EnumElement:
OS << ": ";
break;
case CodeCompletionDeclKind::Protocol:
case CodeCompletionDeclKind::TypeAlias:
case CodeCompletionDeclKind::AssociatedType:
case CodeCompletionDeclKind::GenericTypeParam:
case CodeCompletionDeclKind::Constructor:
case CodeCompletionDeclKind::Destructor:
continue;
case CodeCompletionDeclKind::Subscript:
case CodeCompletionDeclKind::StaticMethod:
case CodeCompletionDeclKind::InstanceMethod:
case CodeCompletionDeclKind::PrefixOperatorFunction:
case CodeCompletionDeclKind::PostfixOperatorFunction:
case CodeCompletionDeclKind::InfixOperatorFunction:
case CodeCompletionDeclKind::FreeFunction:
OS << " -> ";
break;
case CodeCompletionDeclKind::StaticVar:
case CodeCompletionDeclKind::InstanceVar:
case CodeCompletionDeclKind::LocalVar:
case CodeCompletionDeclKind::GlobalVar:
OS << ": ";
break;
}
} else {
OS << ": ";
}
OS << C.getText();
}
}
}
namespace swift {
class REPLCodeCompletionConsumer : public SimpleCachingCodeCompletionConsumer {
REPLCompletions &Completions;
public:
REPLCodeCompletionConsumer(REPLCompletions &Completions)
: Completions(Completions) {}
void handleResults(MutableArrayRef<CodeCompletionResult *> Results) override {
CodeCompletionContext::sortCompletionResults(Results);
for (auto Result : Results) {
std::string InsertableString = toInsertableString(Result);
if (StringRef(InsertableString).startswith(Completions.Prefix)) {
llvm::SmallString<128> PrintedResult;
{
llvm::raw_svector_ostream OS(PrintedResult);
toDisplayString(Result, OS);
}
Completions.CompletionStrings.push_back(
Completions.CompletionContext.copyString(PrintedResult));
InsertableString = InsertableString.substr(Completions.Prefix.size());
Completions.CookedResults.push_back(
{ Completions.CompletionContext.copyString(InsertableString),
Result->getNumBytesToErase() });
}
}
}
};
} // namespace swift
REPLCompletions::REPLCompletions()
: State(CompletionState::Invalid), CompletionContext(CompletionCache) {
// Create a CodeCompletionConsumer.
Consumer.reset(new REPLCodeCompletionConsumer(*this));
// Create a factory for code completion callbacks that will feed the
// Consumer.
CompletionCallbacksFactory.reset(
ide::makeCodeCompletionCallbacksFactory(CompletionContext,
*Consumer));
}
static void
doCodeCompletion(SourceFile &SF, StringRef EnteredCode, unsigned *BufferID,
CodeCompletionCallbacksFactory *CompletionCallbacksFactory) {
// Temporarily disable printing the diagnostics.
ASTContext &Ctx = SF.getASTContext();
auto DiagnosticConsumers = Ctx.Diags.takeConsumers();
std::string AugmentedCode = EnteredCode.str();
AugmentedCode += '\0';
*BufferID = Ctx.SourceMgr.addMemBufferCopy(AugmentedCode, "<REPL Input>");
const unsigned CodeCompletionOffset = AugmentedCode.size() - 1;
Ctx.SourceMgr.setCodeCompletionPoint(*BufferID, CodeCompletionOffset);
// Parse, typecheck and temporarily insert the incomplete code into the AST.
const unsigned OriginalDeclCount = SF.Decls.size();
unsigned CurElem = OriginalDeclCount;
PersistentParserState PersistentState(Ctx);
std::unique_ptr<DelayedParsingCallbacks> DelayedCB(
new CodeCompleteDelayedCallbacks(Ctx.SourceMgr.getCodeCompletionLoc()));
bool Done;
do {
parseIntoSourceFile(SF, *BufferID, &Done, nullptr, &PersistentState,
DelayedCB.get());
performTypeChecking(SF, PersistentState.getTopLevelContext(), None,
CurElem);
CurElem = SF.Decls.size();
} while (!Done);
performDelayedParsing(&SF, PersistentState, CompletionCallbacksFactory);
// Now we are done with code completion. Remove the declarations we
// temporarily inserted.
SF.Decls.resize(OriginalDeclCount);
// Add the diagnostic consumers back.
for (auto DC : DiagnosticConsumers)
Ctx.Diags.addConsumer(*DC);
Ctx.Diags.resetHadAnyError();
}
void REPLCompletions::populate(SourceFile &SF, StringRef EnteredCode) {
Prefix = "";
Root.reset();
CurrentCompletionIdx = ~size_t(0);
CompletionStrings.clear();
CookedResults.clear();
assert(SF.Kind == SourceFileKind::REPL && "Can't append to a non-REPL file");
unsigned BufferID;
doCodeCompletion(SF, EnteredCode, &BufferID,
CompletionCallbacksFactory.get());
ASTContext &Ctx = SF.getASTContext();
std::vector<Token> Tokens = tokenize(Ctx.LangOpts, Ctx.SourceMgr, BufferID);
if (!Tokens.empty() && Tokens.back().is(tok::code_complete))
Tokens.pop_back();
if (!Tokens.empty()) {
Token &LastToken = Tokens.back();
if (LastToken.is(tok::identifier) || LastToken.isKeyword()) {
Prefix = LastToken.getText();
unsigned Offset = Ctx.SourceMgr.getLocOffsetInBuffer(LastToken.getLoc(),
BufferID);
doCodeCompletion(SF, EnteredCode.substr(0, Offset),
&BufferID, CompletionCallbacksFactory.get());
}
}
if (CookedResults.empty())
State = CompletionState::Empty;
else if (CookedResults.size() == 1)
State = CompletionState::Unique;
else
State = CompletionState::CompletedRoot;
}
StringRef REPLCompletions::getRoot() const {
if (Root)
return Root.getValue();
if (CookedResults.empty()) {
Root = std::string();
return Root.getValue();
}
std::string RootStr = CookedResults[0].InsertableString;
for (auto R : CookedResults) {
if (R.NumBytesToErase != 0) {
RootStr.resize(0);
break;
}
auto MismatchPlace = std::mismatch(RootStr.begin(), RootStr.end(),
R.InsertableString.begin());
RootStr.resize(MismatchPlace.first - RootStr.begin());
}
Root = RootStr;
return Root.getValue();
}
REPLCompletions::CookedResult REPLCompletions::getPreviousStem() const {
if (CurrentCompletionIdx == ~size_t(0) || CookedResults.empty())
return {};
const auto &Result = CookedResults[CurrentCompletionIdx];
return { Result.InsertableString.substr(getRoot().size()),
Result.NumBytesToErase };
}
REPLCompletions::CookedResult REPLCompletions::getNextStem() {
if (CookedResults.empty())
return {};
CurrentCompletionIdx++;
if (CurrentCompletionIdx >= CookedResults.size())
CurrentCompletionIdx = 0;
const auto &Result = CookedResults[CurrentCompletionIdx];
return { Result.InsertableString.substr(getRoot().size()),
Result.NumBytesToErase };
}
void REPLCompletions::reset() { State = CompletionState::Invalid; }
<commit_msg>Simplify the integrated REPL code completion a little<commit_after>//===--- REPLCodeCompletion.cpp - Code completion for REPL ----------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This module provides completions to the immediate mode environment.
//
//===----------------------------------------------------------------------===//
#include "swift/IDE/REPLCodeCompletion.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/Module.h"
#include "swift/Basic/LLVM.h"
#include "swift/Basic/SourceManager.h"
#include "swift/Parse/DelayedParsingCallbacks.h"
#include "swift/Parse/Parser.h"
#include "swift/IDE/CodeCompletion.h"
#include "swift/Subsystems.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/ADT/SmallString.h"
#include <algorithm>
using namespace swift;
using namespace ide;
static std::string toInsertableString(CodeCompletionResult *Result) {
std::string Str;
for (auto C : Result->getCompletionString()->getChunks()) {
switch (C.getKind()) {
case CodeCompletionString::Chunk::ChunkKind::AccessControlKeyword:
case CodeCompletionString::Chunk::ChunkKind::OverrideKeyword:
case CodeCompletionString::Chunk::ChunkKind::ThrowsKeyword:
case CodeCompletionString::Chunk::ChunkKind::RethrowsKeyword:
case CodeCompletionString::Chunk::ChunkKind::DeclAttrKeyword:
case CodeCompletionString::Chunk::ChunkKind::DeclIntroducer:
case CodeCompletionString::Chunk::ChunkKind::Text:
case CodeCompletionString::Chunk::ChunkKind::LeftParen:
case CodeCompletionString::Chunk::ChunkKind::RightParen:
case CodeCompletionString::Chunk::ChunkKind::LeftBracket:
case CodeCompletionString::Chunk::ChunkKind::RightBracket:
case CodeCompletionString::Chunk::ChunkKind::LeftAngle:
case CodeCompletionString::Chunk::ChunkKind::RightAngle:
case CodeCompletionString::Chunk::ChunkKind::Dot:
case CodeCompletionString::Chunk::ChunkKind::Ellipsis:
case CodeCompletionString::Chunk::ChunkKind::Comma:
case CodeCompletionString::Chunk::ChunkKind::ExclamationMark:
case CodeCompletionString::Chunk::ChunkKind::QuestionMark:
case CodeCompletionString::Chunk::ChunkKind::Ampersand:
case CodeCompletionString::Chunk::ChunkKind::Equal:
case CodeCompletionString::Chunk::ChunkKind::Whitespace:
case CodeCompletionString::Chunk::ChunkKind::DynamicLookupMethodCallTail:
case CodeCompletionString::Chunk::ChunkKind::OptionalMethodCallTail:
if (!C.isAnnotation())
Str += C.getText();
break;
case CodeCompletionString::Chunk::ChunkKind::CallParameterName:
case CodeCompletionString::Chunk::ChunkKind::CallParameterInternalName:
case CodeCompletionString::Chunk::ChunkKind::CallParameterColon:
case CodeCompletionString::Chunk::ChunkKind::DeclAttrParamKeyword:
case CodeCompletionString::Chunk::ChunkKind::DeclAttrParamColon:
case CodeCompletionString::Chunk::ChunkKind::CallParameterType:
case CodeCompletionString::Chunk::ChunkKind::CallParameterClosureType:
case CodeCompletionString::Chunk::ChunkKind::OptionalBegin:
case CodeCompletionString::Chunk::ChunkKind::CallParameterBegin:
case CodeCompletionString::Chunk::ChunkKind::GenericParameterBegin:
case CodeCompletionString::Chunk::ChunkKind::GenericParameterName:
case CodeCompletionString::Chunk::ChunkKind::TypeAnnotation:
return Str;
case CodeCompletionString::Chunk::ChunkKind::BraceStmtWithCursor:
Str += " {";
break;
}
}
return Str;
}
static void toDisplayString(CodeCompletionResult *Result,
llvm::raw_ostream &OS) {
std::string Str;
for (auto C : Result->getCompletionString()->getChunks()) {
if (C.getKind() ==
CodeCompletionString::Chunk::ChunkKind::BraceStmtWithCursor) {
OS << ' ';
continue;
}
if (!C.isAnnotation() && C.hasText()) {
OS << C.getText();
continue;
}
if (C.getKind() == CodeCompletionString::Chunk::ChunkKind::TypeAnnotation) {
if (Result->getKind() == CodeCompletionResult::Declaration) {
switch (Result->getAssociatedDeclKind()) {
case CodeCompletionDeclKind::Module:
case CodeCompletionDeclKind::PrecedenceGroup:
case CodeCompletionDeclKind::Class:
case CodeCompletionDeclKind::Struct:
case CodeCompletionDeclKind::Enum:
continue;
case CodeCompletionDeclKind::EnumElement:
OS << ": ";
break;
case CodeCompletionDeclKind::Protocol:
case CodeCompletionDeclKind::TypeAlias:
case CodeCompletionDeclKind::AssociatedType:
case CodeCompletionDeclKind::GenericTypeParam:
case CodeCompletionDeclKind::Constructor:
case CodeCompletionDeclKind::Destructor:
continue;
case CodeCompletionDeclKind::Subscript:
case CodeCompletionDeclKind::StaticMethod:
case CodeCompletionDeclKind::InstanceMethod:
case CodeCompletionDeclKind::PrefixOperatorFunction:
case CodeCompletionDeclKind::PostfixOperatorFunction:
case CodeCompletionDeclKind::InfixOperatorFunction:
case CodeCompletionDeclKind::FreeFunction:
OS << " -> ";
break;
case CodeCompletionDeclKind::StaticVar:
case CodeCompletionDeclKind::InstanceVar:
case CodeCompletionDeclKind::LocalVar:
case CodeCompletionDeclKind::GlobalVar:
OS << ": ";
break;
}
} else {
OS << ": ";
}
OS << C.getText();
}
}
}
namespace swift {
class REPLCodeCompletionConsumer : public SimpleCachingCodeCompletionConsumer {
REPLCompletions &Completions;
public:
REPLCodeCompletionConsumer(REPLCompletions &Completions)
: Completions(Completions) {}
void handleResults(MutableArrayRef<CodeCompletionResult *> Results) override {
CodeCompletionContext::sortCompletionResults(Results);
for (auto Result : Results) {
std::string InsertableString = toInsertableString(Result);
if (StringRef(InsertableString).startswith(Completions.Prefix)) {
llvm::SmallString<128> PrintedResult;
{
llvm::raw_svector_ostream OS(PrintedResult);
toDisplayString(Result, OS);
}
Completions.CompletionStrings.push_back(
Completions.CompletionContext.copyString(PrintedResult));
InsertableString = InsertableString.substr(Completions.Prefix.size());
Completions.CookedResults.push_back(
{ Completions.CompletionContext.copyString(InsertableString),
Result->getNumBytesToErase() });
}
}
}
};
} // namespace swift
REPLCompletions::REPLCompletions()
: State(CompletionState::Invalid), CompletionContext(CompletionCache) {
// Create a CodeCompletionConsumer.
Consumer.reset(new REPLCodeCompletionConsumer(*this));
// Create a factory for code completion callbacks that will feed the
// Consumer.
CompletionCallbacksFactory.reset(
ide::makeCodeCompletionCallbacksFactory(CompletionContext,
*Consumer));
}
static void
doCodeCompletion(SourceFile &SF, StringRef EnteredCode, unsigned *BufferID,
CodeCompletionCallbacksFactory *CompletionCallbacksFactory) {
// Temporarily disable printing the diagnostics.
ASTContext &Ctx = SF.getASTContext();
DiagnosticTransaction DelayedDiags(Ctx.Diags);
std::string AugmentedCode = EnteredCode.str();
AugmentedCode += '\0';
*BufferID = Ctx.SourceMgr.addMemBufferCopy(AugmentedCode, "<REPL Input>");
const unsigned CodeCompletionOffset = AugmentedCode.size() - 1;
Ctx.SourceMgr.setCodeCompletionPoint(*BufferID, CodeCompletionOffset);
// Parse, typecheck and temporarily insert the incomplete code into the AST.
const unsigned OriginalDeclCount = SF.Decls.size();
PersistentParserState PersistentState(Ctx);
std::unique_ptr<DelayedParsingCallbacks> DelayedCB(
new CodeCompleteDelayedCallbacks(Ctx.SourceMgr.getCodeCompletionLoc()));
bool Done;
do {
parseIntoSourceFile(SF, *BufferID, &Done, nullptr, &PersistentState,
DelayedCB.get());
} while (!Done);
performTypeChecking(SF, PersistentState.getTopLevelContext(), None,
OriginalDeclCount);
performDelayedParsing(&SF, PersistentState, CompletionCallbacksFactory);
// Now we are done with code completion. Remove the declarations we
// temporarily inserted.
SF.Decls.resize(OriginalDeclCount);
DelayedDiags.abort();
}
void REPLCompletions::populate(SourceFile &SF, StringRef EnteredCode) {
Prefix = "";
Root.reset();
CurrentCompletionIdx = ~size_t(0);
CompletionStrings.clear();
CookedResults.clear();
assert(SF.Kind == SourceFileKind::REPL && "Can't append to a non-REPL file");
unsigned BufferID;
doCodeCompletion(SF, EnteredCode, &BufferID,
CompletionCallbacksFactory.get());
ASTContext &Ctx = SF.getASTContext();
std::vector<Token> Tokens = tokenize(Ctx.LangOpts, Ctx.SourceMgr, BufferID);
if (!Tokens.empty() && Tokens.back().is(tok::code_complete))
Tokens.pop_back();
if (!Tokens.empty()) {
Token &LastToken = Tokens.back();
if (LastToken.is(tok::identifier) || LastToken.isKeyword()) {
Prefix = LastToken.getText();
unsigned Offset = Ctx.SourceMgr.getLocOffsetInBuffer(LastToken.getLoc(),
BufferID);
doCodeCompletion(SF, EnteredCode.substr(0, Offset),
&BufferID, CompletionCallbacksFactory.get());
}
}
if (CookedResults.empty())
State = CompletionState::Empty;
else if (CookedResults.size() == 1)
State = CompletionState::Unique;
else
State = CompletionState::CompletedRoot;
}
StringRef REPLCompletions::getRoot() const {
if (Root)
return Root.getValue();
if (CookedResults.empty()) {
Root = std::string();
return Root.getValue();
}
std::string RootStr = CookedResults[0].InsertableString;
for (auto R : CookedResults) {
if (R.NumBytesToErase != 0) {
RootStr.resize(0);
break;
}
auto MismatchPlace = std::mismatch(RootStr.begin(), RootStr.end(),
R.InsertableString.begin());
RootStr.resize(MismatchPlace.first - RootStr.begin());
}
Root = RootStr;
return Root.getValue();
}
REPLCompletions::CookedResult REPLCompletions::getPreviousStem() const {
if (CurrentCompletionIdx == ~size_t(0) || CookedResults.empty())
return {};
const auto &Result = CookedResults[CurrentCompletionIdx];
return { Result.InsertableString.substr(getRoot().size()),
Result.NumBytesToErase };
}
REPLCompletions::CookedResult REPLCompletions::getNextStem() {
if (CookedResults.empty())
return {};
CurrentCompletionIdx++;
if (CurrentCompletionIdx >= CookedResults.size())
CurrentCompletionIdx = 0;
const auto &Result = CookedResults[CurrentCompletionIdx];
return { Result.InsertableString.substr(getRoot().size()),
Result.NumBytesToErase };
}
void REPLCompletions::reset() { State = CompletionState::Invalid; }
<|endoftext|>
|
<commit_before>#include "TrainSession.h"
#include <fstream>
#include <string>
#include <iomanip>
#include <SmurffCpp/Utils/omp_util.h>
#include <SmurffCpp/Utils/Distribution.h>
#include <SmurffCpp/Utils/MatrixUtils.h>
#include <SmurffCpp/Utils/counters.h>
#include <SmurffCpp/Utils/Error.h>
#include <SmurffCpp/Utils/StringUtils.h>
#include <SmurffCpp/Configs/Config.h>
#include <SmurffCpp/Priors/PriorFactory.h>
#include <SmurffCpp/result.h>
#include <SmurffCpp/StatusItem.h>
namespace smurff {
void TrainSession::init()
{
THROWERROR_ASSERT_MSG(!m_is_init, "TrainSession::init called twice");
getConfig().validate();
if (!getConfig().getSaveName().empty())
{
// create state file
m_stateFile = std::make_shared<StateFile>(getConfig().getSaveName(), true);
//save config
m_stateFile->saveConfig(getConfig());
// close stateFile is we do not need it anymore
if (!getConfig().getSaveFreq() && !getConfig().getCheckpointFreq())
m_stateFile.reset();
}
// initialize pred
if (getConfig().getTest().hasData())
{
m_pred = Result(getConfig().getTest());
m_pred.setSavePred(getConfig().getSavePred());
if (getConfig().getClassify())
m_pred.setThreshold(getConfig().getThreshold());
}
// init data
data_ptr = Data::create(getConfig().getData());
// initialize priors
std::shared_ptr<IPriorFactory> priorFactory = this->create_prior_factory();
for (std::size_t i = 0; i < getConfig().getPriorTypes().size(); i++)
{
m_priors.push_back(priorFactory->create_prior(*this, i));
m_priors.back()->setMode(i);
}
//init omp
threads::init(getConfig().getVerbose(), getConfig().getNumThreads());
//initialize random generator
initRng();
//init performance counters
perf_data_init();
//initialize test set
m_pred.init();
//initialize train matrix (centring and noise model)
data().init();
//initialize model (samples)
model().init(getConfig().getNumLatent(), data().dim(), getConfig().getModelInitType(), getConfig().getSaveModel());
//initialize priors
for (auto &p : m_priors)
p->init();
// all basic init done
m_is_init = true;
//write info to console
if (getConfig().getVerbose())
info(std::cout, "");
//restore trainSession (model, priors)
bool resume = restore(m_iter);
//print trainSession status to console
if (getConfig().getVerbose())
printStatus(std::cout, resume);
}
void TrainSession::run()
{
init();
while (step())
;
}
bool TrainSession::step()
{
COUNTER("step");
THROWERROR_ASSERT_MSG(m_is_init, "TrainSession::init() needs to be called before ::step()")
// go to the next iteration
m_iter++;
bool isStep = m_iter < getConfig().getBurnin() + getConfig().getNSamples();
if (isStep)
{
auto starti = tick();
#pragma omp parallel
#pragma omp master
for (auto p : m_priors)
{
p->sample_latents();
#pragma omp task
p->update_prior();
}
data().update(model());
auto endi = tick();
//WARNING: update is an expensive operation because of sort (when calculating AUC)
m_pred.update(m_model, m_iter < getConfig().getBurnin());
m_secs_per_iter = endi - starti;
m_secs_total += m_secs_per_iter;
printStatus(std::cout);
save();
}
return isStep;
}
std::ostream &TrainSession::info(std::ostream &os, std::string indent) const
{
os << indent << name << " {\n";
os << indent << " Data: {" << std::endl;
data().info(os, indent + " ");
os << indent << " }" << std::endl;
os << indent << " Model: {" << std::endl;
model().info(os, indent + " ");
os << indent << " }" << std::endl;
os << indent << " Priors: {" << std::endl;
for (auto &p : m_priors)
p->info(os, indent + " ");
os << indent << " }" << std::endl;
os << indent << " Result: {" << std::endl;
m_pred.info(os, indent + " ");
os << indent << " }" << std::endl;
os << indent << " Config: {" << std::endl;
getConfig().info(os, indent + " ");
os << indent << " }" << std::endl;
os << indent << "}\n";
return os;
}
void TrainSession::save()
{
//do not save if 'never save' mode is selected
if (!getConfig().getSaveFreq() &&
!getConfig().getCheckpointFreq())
return;
std::int32_t isample = m_iter - getConfig().getBurnin() + 1;
std::int32_t niter = getConfig().getBurnin() + getConfig().getNSamples();
//save if checkpoint threshold overdue
if (
getConfig().getCheckpointFreq() &&
(
((tick() - m_lastCheckpointTime) >= getConfig().getCheckpointFreq()) ||
(m_iter == niter - 1) // also save checkpoint in last iteration
)
)
{
std::int32_t icheckpoint = m_iter + 1;
//save this iteration
saveInternal(icheckpoint, true);
//remove previous iteration if required (initial m_lastCheckpointIter is -1 which means that it does not exist)
m_stateFile->removeOldCheckpoints();
//upddate counters
m_lastCheckpointTime = tick();
m_lastCheckpointIter = m_iter;
}
//save model during sampling stage
if (getConfig().getSaveFreq() && isample > 0)
{
//save_freq > 0: check modulo - do not save if not a save iteration
if (getConfig().getSaveFreq() > 0 && (isample % getConfig().getSaveFreq()) != 0)
{
// don't save
}
//save_freq < 0: save last iter - do not save if (final model) mode is selected and not a final iteration
else if (getConfig().getSaveFreq() < 0 && isample < getConfig().getNSamples())
{
// don't save
}
else
{
//do save this iteration
saveInternal(isample, false);
}
}
// close after final step
if (m_iter == niter - 1) m_stateFile.reset();
}
void TrainSession::saveInternal(int iteration, bool checkpoint)
{
bool final = iteration == getConfig().getNSamples();
SaveState saveState = m_stateFile->createStep(iteration, checkpoint, final || checkpoint);
if (getConfig().getVerbose())
{
std::cout << "-- Saving model, predictions,... into '" << m_stateFile->getPath() << "'." << std::endl;
}
double start = tick();
m_model.save(saveState);
m_pred.save(saveState);
for (auto &p : m_priors) p->save(saveState);
double stop = tick();
if (getConfig().getVerbose())
{
std::cout << "-- Done saving model. Took " << stop - start << " seconds." << std::endl;
}
}
bool TrainSession::restore(int &iteration)
{
//if there is nothing to restore - start from initial iteration
iteration = -1;
//to keep track at what time we last checkpointed
m_lastCheckpointTime = tick();
m_lastCheckpointIter = -1;
if (getConfig().getRestoreName().empty())
return false;
// open state file
StateFile restoreFile(getConfig().getRestoreName());
if (!restoreFile.hasCheckpoint())
return false;
SaveState saveState = restoreFile.openCheckpoint();
if (getConfig().getVerbose())
std::cout << "-- Restoring model, predictions,... from '" << restoreFile.getPath() << "'." << std::endl;
m_model.restore(saveState);
m_pred.restore(saveState);
for (auto &p : m_priors)
p->restore(saveState);
//restore last iteration index
if (saveState.isCheckpoint())
{
iteration = saveState.getIsample() - 1; //restore original state
//to keep track at what time we last checkpointed
m_lastCheckpointTime = tick();
m_lastCheckpointIter = iteration;
}
else
{
iteration = saveState.getIsample() + getConfig().getBurnin() - 1; //restore original state
//to keep track at what time we last checkpointed
m_lastCheckpointTime = tick();
m_lastCheckpointIter = iteration;
}
return true;
}
const Result &TrainSession::getResult() const
{
return m_pred;
}
StatusItem TrainSession::getStatus() const
{
THROWERROR_ASSERT(m_is_init);
StatusItem ret;
if (m_iter < 0)
{
ret.phase = "Initial";
ret.iter = m_iter + 1;
ret.phase_iter = 0;
}
else if (m_iter < getConfig().getBurnin())
{
ret.phase = "Burnin";
ret.iter = m_iter + 1;
ret.phase_iter = getConfig().getBurnin();
}
else
{
ret.phase = "Sample";
ret.iter = m_iter - getConfig().getBurnin() + 1;
ret.phase_iter = getConfig().getNSamples();
}
for (int i = 0; i < (int)model().nmodes(); ++i)
{
ret.model_norms.push_back(model().U(i).norm());
}
ret.train_rmse = data().train_rmse(model());
ret.rmse_avg = m_pred.rmse_avg;
ret.rmse_1sample = m_pred.rmse_1sample;
ret.auc_avg = m_pred.auc_avg;
ret.auc_1sample = m_pred.auc_1sample;
ret.elapsed_iter = m_secs_per_iter;
ret.elapsed_total = m_secs_total;
ret.nnz_per_sec = (double)(data().nnz()) / m_secs_per_iter;
ret.samples_per_sec = (double)(model().nsamples()) / m_secs_per_iter;
return ret;
}
void TrainSession::printStatus(std::ostream &output, bool resume)
{
if (!getConfig().getVerbose())
return;
auto status_item = getStatus();
std::string resumeString = resume ? "Continue from " : std::string();
if (getConfig().getVerbose() > 0)
{
if (m_iter < 0)
{
output << " ====== Initial phase ====== " << std::endl;
}
else if (m_iter < getConfig().getBurnin() && m_iter == 0)
{
output << " ====== Sampling (burning phase) ====== " << std::endl;
}
else if (m_iter == getConfig().getBurnin())
{
output << " ====== Burn-in complete, averaging samples ====== " << std::endl;
}
output << resumeString << status_item.asString() << std::endl;
if (getConfig().getVerbose() > 1)
{
output << std::fixed << std::setprecision(4) << " RMSE train: " << status_item.train_rmse << std::endl;
output << " Priors:" << std::endl;
for (const auto &p : m_priors)
p->status(output, " ");
output << " Model:" << std::endl;
model().status(output, " ");
output << " Noise:" << std::endl;
data().status(output, " ");
}
if (getConfig().getVerbose() > 2)
{
output << " Compute Performance: " << status_item.samples_per_sec << " samples/sec, " << status_item.nnz_per_sec << " nnz/sec" << std::endl;
}
}
}
std::string StatusItem::getCsvHeader()
{
return "phase;iter;phase_len;rmse_avg;rmse_1samp;train_rmse;auc_avg;auc_1samp;elapsed_1samp;elapsed_total";
}
std::string StatusItem::asCsvString() const
{
char ret[1024];
snprintf(ret, 1024, "%s;%d;%d;%.4f;%.4f;%.4f;%.4f;:%.4f;%0.1f;%0.1f",
phase.c_str(), iter, phase_iter, rmse_avg, rmse_1sample, train_rmse,
auc_1sample, auc_avg, elapsed_iter, elapsed_total);
return ret;
}
void TrainSession::initRng()
{
//init random generator
if (getConfig().getRandomSeedSet())
init_bmrng(getConfig().getRandomSeed());
else
init_bmrng();
}
std::shared_ptr<IPriorFactory> TrainSession::create_prior_factory() const
{
return std::make_shared<PriorFactory>();
}
} // end namespace smurff
<commit_msg>WIP: OpenMP task dependencies<commit_after>#include "TrainSession.h"
#include <fstream>
#include <string>
#include <iomanip>
#include <SmurffCpp/Utils/omp_util.h>
#include <SmurffCpp/Utils/Distribution.h>
#include <SmurffCpp/Utils/MatrixUtils.h>
#include <SmurffCpp/Utils/counters.h>
#include <SmurffCpp/Utils/Error.h>
#include <SmurffCpp/Utils/StringUtils.h>
#include <SmurffCpp/Configs/Config.h>
#include <SmurffCpp/Priors/PriorFactory.h>
#include <SmurffCpp/result.h>
#include <SmurffCpp/StatusItem.h>
namespace smurff {
void TrainSession::init()
{
THROWERROR_ASSERT_MSG(!m_is_init, "TrainSession::init called twice");
getConfig().validate();
if (!getConfig().getSaveName().empty())
{
// create state file
m_stateFile = std::make_shared<StateFile>(getConfig().getSaveName(), true);
//save config
m_stateFile->saveConfig(getConfig());
// close stateFile is we do not need it anymore
if (!getConfig().getSaveFreq() && !getConfig().getCheckpointFreq())
m_stateFile.reset();
}
// initialize pred
if (getConfig().getTest().hasData())
{
m_pred = Result(getConfig().getTest());
m_pred.setSavePred(getConfig().getSavePred());
if (getConfig().getClassify())
m_pred.setThreshold(getConfig().getThreshold());
}
// init data
data_ptr = Data::create(getConfig().getData());
// initialize priors
std::shared_ptr<IPriorFactory> priorFactory = this->create_prior_factory();
for (std::size_t i = 0; i < getConfig().getPriorTypes().size(); i++)
{
m_priors.push_back(priorFactory->create_prior(*this, i));
m_priors.back()->setMode(i);
}
//init omp
threads::init(getConfig().getVerbose(), getConfig().getNumThreads());
//initialize random generator
initRng();
//init performance counters
perf_data_init();
//initialize test set
m_pred.init();
//initialize train matrix (centring and noise model)
data().init();
//initialize model (samples)
model().init(getConfig().getNumLatent(), data().dim(), getConfig().getModelInitType(), getConfig().getSaveModel());
//initialize priors
for (auto &p : m_priors)
p->init();
// all basic init done
m_is_init = true;
//write info to console
if (getConfig().getVerbose())
info(std::cout, "");
//restore trainSession (model, priors)
bool resume = restore(m_iter);
//print trainSession status to console
if (getConfig().getVerbose())
printStatus(std::cout, resume);
}
void TrainSession::run()
{
init();
while (step())
;
}
bool TrainSession::step()
{
COUNTER("step");
THROWERROR_ASSERT_MSG(m_is_init, "TrainSession::init() needs to be called before ::step()")
// go to the next iteration
m_iter++;
bool isStep = m_iter < getConfig().getBurnin() + getConfig().getNSamples();
if (isStep)
{
bool deps[MaxDims];
auto starti = tick();
#pragma omp parallel
#pragma omp master
for (unsigned i=0; i<m_priors.size(); ++i)
{
#pragma omp task depend(in: deps[i-1]) depend(out:deps[i])
m_priors[i]->sample_latents();
#pragma omp task depend(in: deps[i])
m_priors[i]->update_prior();
}
data().update(model());
auto endi = tick();
//WARNING: update is an expensive operation because of sort (when calculating AUC)
m_pred.update(m_model, m_iter < getConfig().getBurnin());
m_secs_per_iter = endi - starti;
m_secs_total += m_secs_per_iter;
printStatus(std::cout);
save();
}
return isStep;
}
std::ostream &TrainSession::info(std::ostream &os, std::string indent) const
{
os << indent << name << " {\n";
os << indent << " Data: {" << std::endl;
data().info(os, indent + " ");
os << indent << " }" << std::endl;
os << indent << " Model: {" << std::endl;
model().info(os, indent + " ");
os << indent << " }" << std::endl;
os << indent << " Priors: {" << std::endl;
for (auto &p : m_priors)
p->info(os, indent + " ");
os << indent << " }" << std::endl;
os << indent << " Result: {" << std::endl;
m_pred.info(os, indent + " ");
os << indent << " }" << std::endl;
os << indent << " Config: {" << std::endl;
getConfig().info(os, indent + " ");
os << indent << " }" << std::endl;
os << indent << "}\n";
return os;
}
void TrainSession::save()
{
//do not save if 'never save' mode is selected
if (!getConfig().getSaveFreq() &&
!getConfig().getCheckpointFreq())
return;
std::int32_t isample = m_iter - getConfig().getBurnin() + 1;
std::int32_t niter = getConfig().getBurnin() + getConfig().getNSamples();
//save if checkpoint threshold overdue
if (
getConfig().getCheckpointFreq() &&
(
((tick() - m_lastCheckpointTime) >= getConfig().getCheckpointFreq()) ||
(m_iter == niter - 1) // also save checkpoint in last iteration
)
)
{
std::int32_t icheckpoint = m_iter + 1;
//save this iteration
saveInternal(icheckpoint, true);
//remove previous iteration if required (initial m_lastCheckpointIter is -1 which means that it does not exist)
m_stateFile->removeOldCheckpoints();
//upddate counters
m_lastCheckpointTime = tick();
m_lastCheckpointIter = m_iter;
}
//save model during sampling stage
if (getConfig().getSaveFreq() && isample > 0)
{
//save_freq > 0: check modulo - do not save if not a save iteration
if (getConfig().getSaveFreq() > 0 && (isample % getConfig().getSaveFreq()) != 0)
{
// don't save
}
//save_freq < 0: save last iter - do not save if (final model) mode is selected and not a final iteration
else if (getConfig().getSaveFreq() < 0 && isample < getConfig().getNSamples())
{
// don't save
}
else
{
//do save this iteration
saveInternal(isample, false);
}
}
// close after final step
if (m_iter == niter - 1) m_stateFile.reset();
}
void TrainSession::saveInternal(int iteration, bool checkpoint)
{
bool final = iteration == getConfig().getNSamples();
SaveState saveState = m_stateFile->createStep(iteration, checkpoint, final || checkpoint);
if (getConfig().getVerbose())
{
std::cout << "-- Saving model, predictions,... into '" << m_stateFile->getPath() << "'." << std::endl;
}
double start = tick();
m_model.save(saveState);
m_pred.save(saveState);
for (auto &p : m_priors) p->save(saveState);
double stop = tick();
if (getConfig().getVerbose())
{
std::cout << "-- Done saving model. Took " << stop - start << " seconds." << std::endl;
}
}
bool TrainSession::restore(int &iteration)
{
//if there is nothing to restore - start from initial iteration
iteration = -1;
//to keep track at what time we last checkpointed
m_lastCheckpointTime = tick();
m_lastCheckpointIter = -1;
if (getConfig().getRestoreName().empty())
return false;
// open state file
StateFile restoreFile(getConfig().getRestoreName());
if (!restoreFile.hasCheckpoint())
return false;
SaveState saveState = restoreFile.openCheckpoint();
if (getConfig().getVerbose())
std::cout << "-- Restoring model, predictions,... from '" << restoreFile.getPath() << "'." << std::endl;
m_model.restore(saveState);
m_pred.restore(saveState);
for (auto &p : m_priors)
p->restore(saveState);
//restore last iteration index
if (saveState.isCheckpoint())
{
iteration = saveState.getIsample() - 1; //restore original state
//to keep track at what time we last checkpointed
m_lastCheckpointTime = tick();
m_lastCheckpointIter = iteration;
}
else
{
iteration = saveState.getIsample() + getConfig().getBurnin() - 1; //restore original state
//to keep track at what time we last checkpointed
m_lastCheckpointTime = tick();
m_lastCheckpointIter = iteration;
}
return true;
}
const Result &TrainSession::getResult() const
{
return m_pred;
}
StatusItem TrainSession::getStatus() const
{
THROWERROR_ASSERT(m_is_init);
StatusItem ret;
if (m_iter < 0)
{
ret.phase = "Initial";
ret.iter = m_iter + 1;
ret.phase_iter = 0;
}
else if (m_iter < getConfig().getBurnin())
{
ret.phase = "Burnin";
ret.iter = m_iter + 1;
ret.phase_iter = getConfig().getBurnin();
}
else
{
ret.phase = "Sample";
ret.iter = m_iter - getConfig().getBurnin() + 1;
ret.phase_iter = getConfig().getNSamples();
}
for (int i = 0; i < (int)model().nmodes(); ++i)
{
ret.model_norms.push_back(model().U(i).norm());
}
ret.train_rmse = data().train_rmse(model());
ret.rmse_avg = m_pred.rmse_avg;
ret.rmse_1sample = m_pred.rmse_1sample;
ret.auc_avg = m_pred.auc_avg;
ret.auc_1sample = m_pred.auc_1sample;
ret.elapsed_iter = m_secs_per_iter;
ret.elapsed_total = m_secs_total;
ret.nnz_per_sec = (double)(data().nnz()) / m_secs_per_iter;
ret.samples_per_sec = (double)(model().nsamples()) / m_secs_per_iter;
return ret;
}
void TrainSession::printStatus(std::ostream &output, bool resume)
{
if (!getConfig().getVerbose())
return;
auto status_item = getStatus();
std::string resumeString = resume ? "Continue from " : std::string();
if (getConfig().getVerbose() > 0)
{
if (m_iter < 0)
{
output << " ====== Initial phase ====== " << std::endl;
}
else if (m_iter < getConfig().getBurnin() && m_iter == 0)
{
output << " ====== Sampling (burning phase) ====== " << std::endl;
}
else if (m_iter == getConfig().getBurnin())
{
output << " ====== Burn-in complete, averaging samples ====== " << std::endl;
}
output << resumeString << status_item.asString() << std::endl;
if (getConfig().getVerbose() > 1)
{
output << std::fixed << std::setprecision(4) << " RMSE train: " << status_item.train_rmse << std::endl;
output << " Priors:" << std::endl;
for (const auto &p : m_priors)
p->status(output, " ");
output << " Model:" << std::endl;
model().status(output, " ");
output << " Noise:" << std::endl;
data().status(output, " ");
}
if (getConfig().getVerbose() > 2)
{
output << " Compute Performance: " << status_item.samples_per_sec << " samples/sec, " << status_item.nnz_per_sec << " nnz/sec" << std::endl;
}
}
}
std::string StatusItem::getCsvHeader()
{
return "phase;iter;phase_len;rmse_avg;rmse_1samp;train_rmse;auc_avg;auc_1samp;elapsed_1samp;elapsed_total";
}
std::string StatusItem::asCsvString() const
{
char ret[1024];
snprintf(ret, 1024, "%s;%d;%d;%.4f;%.4f;%.4f;%.4f;:%.4f;%0.1f;%0.1f",
phase.c_str(), iter, phase_iter, rmse_avg, rmse_1sample, train_rmse,
auc_1sample, auc_avg, elapsed_iter, elapsed_total);
return ret;
}
void TrainSession::initRng()
{
//init random generator
if (getConfig().getRandomSeedSet())
init_bmrng(getConfig().getRandomSeed());
else
init_bmrng();
}
std::shared_ptr<IPriorFactory> TrainSession::create_prior_factory() const
{
return std::make_shared<PriorFactory>();
}
} // end namespace smurff
<|endoftext|>
|
<commit_before>
/*
* nextpnr -- Next Generation Place and Route
*
* Copyright (C) 2018 Miodrag Milanovic <miodrag@symbioticeda.com>
* Copyright (C) 2018 Serge Bazanski <q3k@symbioticeda.com>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
#include "application.h"
#include <QMessageBox>
#include <QSurfaceFormat>
#include <QTextStream>
#include <exception>
NEXTPNR_NAMESPACE_BEGIN
#ifdef _WIN32
#include <windows.h>
BOOL WINAPI WinHandler(DWORD dwCtrlType)
{
if (dwCtrlType == CTRL_C_EVENT)
qApp->quit();
return TRUE;
}
#endif
Application::Application(int &argc, char **argv) : QApplication(argc, argv)
{
QSurfaceFormat fmt;
fmt.setSamples(10);
fmt.setProfile(QSurfaceFormat::CoreProfile);
// macOS is very picky about this version matching
// the version of openGL used in ImGuiRenderer
fmt.setMajorVersion(3);
fmt.setMinorVersion(2);
QSurfaceFormat::setDefaultFormat(fmt);
#ifdef _WIN32
SetConsoleCtrlHandler((PHANDLER_ROUTINE)WinHandler, TRUE);
#endif
}
bool Application::notify(QObject *receiver, QEvent *event)
{
bool retVal = true;
try {
retVal = QApplication::notify(receiver, event);
} catch (assertion_failure ex) {
QString msg;
QTextStream out(&msg);
out << ex.filename.c_str() << " at " << ex.line << "\n";
out << ex.msg.c_str();
QMessageBox::critical(0, "Error", msg);
} catch (...) {
QMessageBox::critical(0, "Error", "Fatal error !!!");
}
return retVal;
}
NEXTPNR_NAMESPACE_END
<commit_msg>Bring back check that GL contexts get the format requested.<commit_after>
/*
* nextpnr -- Next Generation Place and Route
*
* Copyright (C) 2018 Miodrag Milanovic <miodrag@symbioticeda.com>
* Copyright (C) 2018 Serge Bazanski <q3k@symbioticeda.com>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
#include "application.h"
#include "log.h"
#include <QOpenGLContext>
#include <QMessageBox>
#include <QSurfaceFormat>
#include <QTextStream>
#include <exception>
NEXTPNR_NAMESPACE_BEGIN
#ifdef _WIN32
#include <windows.h>
BOOL WINAPI WinHandler(DWORD dwCtrlType)
{
if (dwCtrlType == CTRL_C_EVENT)
qApp->quit();
return TRUE;
}
#endif
Application::Application(int &argc, char **argv) : QApplication(argc, argv)
{
QSurfaceFormat fmt;
fmt.setSamples(10);
fmt.setProfile(QSurfaceFormat::CoreProfile);
// macOS is very picky about this version matching
// the version of openGL used in ImGuiRenderer
fmt.setMajorVersion(3);
fmt.setMinorVersion(2);
QSurfaceFormat::setDefaultFormat(fmt);
QOpenGLContext glContext;
fmt = glContext.format();
if (fmt.majorVersion() < 3) {
printf("Could not get OpenGL 3.0 context. Aborting.\n");
log_abort();
}
if (fmt.minorVersion() < 2) {
printf("Could not get OpenGL 3.2 context - trying anyway...\n ");
}
#ifdef _WIN32
SetConsoleCtrlHandler((PHANDLER_ROUTINE)WinHandler, TRUE);
#endif
}
bool Application::notify(QObject *receiver, QEvent *event)
{
bool retVal = true;
try {
retVal = QApplication::notify(receiver, event);
} catch (assertion_failure ex) {
QString msg;
QTextStream out(&msg);
out << ex.filename.c_str() << " at " << ex.line << "\n";
out << ex.msg.c_str();
QMessageBox::critical(0, "Error", msg);
} catch (...) {
QMessageBox::critical(0, "Error", "Fatal error !!!");
}
return retVal;
}
NEXTPNR_NAMESPACE_END
<|endoftext|>
|
<commit_before>#include "chatwindow.h"
#include "ui_chatwindow.h"
#include "QString"
#include "QColor"
#include "gui.h"
//
ChatWindow::ChatWindow(Gui* guiPointer) :
QMainWindow(nullptr),
ui(new Ui::ChatWindow)
{
ui->setupUi(this);
chatGui = guiPointer;
}
void ChatWindow::receiveMessage(const QString from, const QString to, const QString message, const QString time){
ui->messageHistory->moveCursor(QTextCursor::End);
if(to == name){
ui->messageHistory->setTextColor(Qt::magenta);
ui->messageHistory->insertPlainText(from +" whispers to you: ");
ui->messageHistory->setTextColor(Qt::black);
}
else if (from == name && to != "root"){
ui->messageHistory->setTextColor(Qt::magenta);
ui->messageHistory->insertPlainText("You whisper to " + to + ": ");
ui->messageHistory->setTextColor(Qt::black);
}
else if (from == name && to == "root"){
ui->messageHistory->setTextColor(Qt::blue);
ui->messageHistory->insertPlainText("You say: ");
ui->messageHistory->setTextColor(Qt::black);
}
else {
ui->messageHistory->setTextColor(Qt::blue);
ui->messageHistory->insertPlainText(from + " says: ");
ui->messageHistory->setTextColor(Qt::black);
}
ui->messageHistory->insertPlainText(message);
ui->messageHistory->insertPlainText("\n");
if(ui->messageHistory->verticalScrollBar()->value() != ui->messageHistory->verticalScrollBar()->maximum())
{
}
else{
ui->messageHistory->verticalScrollBar()->setValue(ui->messageHistory->verticalScrollBar()->maximum());
}
}
void ChatWindow::setName(QString inName){
name = inName;
}
void ChatWindow::setServer(QString serverName){
server = serverName;
ui->roomTree->setHeaderLabel(server);
}
void ChatWindow::updateStruct(QVector<QString> treeStruct){
QTreeWidgetItem* treeParent=new QTreeWidgetItem(ui->roomTree);
treeParent=addRoot(treeStruct.at(0));
for (int i=1; i<= treeStruct.size(); i++){
if (treeStruct.at(i)=="User"){
while (i+1 <= treeStruct.size()){
addLeaf(treeParent,treeStruct.at(i+1));
i++;
}
}
treeParent=addSubRoot(treeParent,treeStruct.at(i));
}
}
QTreeWidgetItem* ChatWindow::addRoot(const QString rootName){
QTreeWidgetItem* item = new QTreeWidgetItem(ui->roomTree);
item->setText(0,rootName);
ui->roomTree->addTopLevelItem(item);
return item;
}
QTreeWidgetItem* ChatWindow::addSubRoot(QTreeWidgetItem *parent,const QString childName){
QTreeWidgetItem* item = new QTreeWidgetItem(ui->roomTree);
item->setText(0,childName);
parent->addChild(item);
return item;
}
void ChatWindow::addLeaf(QTreeWidgetItem *parent,const QString leafName){
QTreeWidgetItem* item = new QTreeWidgetItem(ui->roomTree);
item->setText(0,leafName);
parent->addChild(item);
}
ChatWindow::~ChatWindow()
{
delete ui;
}
//If sendbutton is pressed display sent from text and message in messagehistory
void ChatWindow::on_sendButton_clicked()
{
sendMessage();
ui->messageInput->clear();
receiver="root";
ui->sendButton->setText("Send");
//observera at root är en templösning
}
// send message on return
void ChatWindow::on_messageInput_returnPressed()
{
on_sendButton_clicked();
}
//whisper control
void ChatWindow::on_messageInput_textEdited(const QString &arg1)
{
QString to = arg1;
QString w = arg1;
QString whisper = arg1;
w.truncate(3);
whisper.truncate(9);
if(w == "/w " or w =="/W "){
to.remove("/w ",Qt::CaseInsensitive);
if(to.length() > 0 && to.endsWith(" ")){
to.chop(1);
receiver = to;
ui->sendButton->setText("To " + to);
ui->messageInput->clear();
}
}
if(whisper == "/whisper " or whisper =="/Whisper "){
to.remove("/whisper ",Qt::CaseInsensitive);
if(to.length() > 0 && to.endsWith(" ")){
to.chop(1);
receiver = to;
ui->sendButton->setText("To " + to);
ui->messageInput->clear();
}
}
// if(w=="/r " or w=="/R "){
}
void ChatWindow::sendMessage(){
chatGui->sendMessage(name,receiver,ui->messageInput->text());
}
void ChatWindow::on_actionBlack_triggered()
{
ui->messageInput->setStyleSheet("color: black;"
"background-color: grey;"
"selection-color: black;"
"selection-background-color: white");
ui->roomTree->setStyleSheet("color: black;"
"background-color: grey;"
"selection-color: black;"
"selection-background-color: white");
ui->messageHistory->setStyleSheet("color: black;"
"background-color: grey;"
"selection-color: black;"
"selection-background-color: white");
this->setStyleSheet("color: white;"
"background-color: black;"
"selection-color: black;"
"selection-background-color: white");
ui->mainToolBar->setStyleSheet("color: white;"
"background-color: black;"
"selection-color: black;"
"selection-background-color: white");
}
void ChatWindow::on_actionDefault_triggered()
{
ui->messageInput->setStyleSheet("");
ui->roomTree->setStyleSheet("");
ui->messageHistory->setStyleSheet("");
this->setStyleSheet("");
ui->mainToolBar->setStyleSheet("");
}
}
void ChatWindow::receiveHistory(QVector<QString> &historyVector){
for(int i = 0;i==historyVector.size(); i+=4){
ui->messageHistory->insertPlainText(historyVector.at(i) + " says: " + historyVector.at(i+2) + "\n");
}
}
<commit_msg>Fixed some errors<commit_after>#include "chatwindow.h"
#include "ui_chatwindow.h"
#include "QString"
#include "QColor"
#include "gui.h"
//
ChatWindow::ChatWindow(Gui* guiPointer) :
QMainWindow(nullptr),
ui(new Ui::ChatWindow)
{
ui->setupUi(this);
chatGui = guiPointer;
}
void ChatWindow::receiveMessage(const QString from, const QString to, const QString message, const QString time){
ui->messageHistory->moveCursor(QTextCursor::End);
if(to == name){
ui->messageHistory->setTextColor(Qt::magenta);
ui->messageHistory->insertPlainText(from +" whispers to you: ");
ui->messageHistory->setTextColor(Qt::black);
}
else if (from == name && to != "root"){
ui->messageHistory->setTextColor(Qt::magenta);
ui->messageHistory->insertPlainText("You whisper to " + to + ": ");
ui->messageHistory->setTextColor(Qt::black);
}
else if (from == name && to == "root"){
ui->messageHistory->setTextColor(Qt::blue);
ui->messageHistory->insertPlainText("You say: ");
ui->messageHistory->setTextColor(Qt::black);
}
else {
ui->messageHistory->setTextColor(Qt::blue);
ui->messageHistory->insertPlainText(from + " says: ");
ui->messageHistory->setTextColor(Qt::black);
}
ui->messageHistory->insertPlainText(message);
ui->messageHistory->insertPlainText("\n");
if(ui->messageHistory->verticalScrollBar()->value() != ui->messageHistory->verticalScrollBar()->maximum())
{
}
else{
ui->messageHistory->verticalScrollBar()->setValue(ui->messageHistory->verticalScrollBar()->maximum());
}
}
void ChatWindow::setName(QString inName){
name = inName;
}
void ChatWindow::setServer(QString serverName){
server = serverName;
ui->roomTree->setHeaderLabel(server);
}
void ChatWindow::updateStruct(QVector<QString> treeStruct){
QTreeWidgetItem* treeParent=new QTreeWidgetItem(ui->roomTree);
treeParent=addRoot(treeStruct.at(0));
for (int i=1; i<= treeStruct.size(); i++){
if (treeStruct.at(i)=="User"){
while (i+1 <= treeStruct.size()){
addLeaf(treeParent,treeStruct.at(i+1));
i++;
}
}
treeParent=addSubRoot(treeParent,treeStruct.at(i));
}
}
QTreeWidgetItem* ChatWindow::addRoot(const QString rootName){
QTreeWidgetItem* item = new QTreeWidgetItem(ui->roomTree);
item->setText(0,rootName);
ui->roomTree->addTopLevelItem(item);
return item;
}
QTreeWidgetItem* ChatWindow::addSubRoot(QTreeWidgetItem *parent,const QString childName){
QTreeWidgetItem* item = new QTreeWidgetItem(ui->roomTree);
item->setText(0,childName);
parent->addChild(item);
return item;
}
void ChatWindow::addLeaf(QTreeWidgetItem *parent,const QString leafName){
QTreeWidgetItem* item = new QTreeWidgetItem(ui->roomTree);
item->setText(0,leafName);
parent->addChild(item);
}
ChatWindow::~ChatWindow()
{
delete ui;
}
//If sendbutton is pressed display sent from text and message in messagehistory
void ChatWindow::on_sendButton_clicked()
{
sendMessage();
ui->messageInput->clear();
receiver="root";
ui->sendButton->setText("Send");
//observera at root är en templösning
}
// send message on return
void ChatWindow::on_messageInput_returnPressed()
{
on_sendButton_clicked();
}
//whisper control
void ChatWindow::on_messageInput_textEdited(const QString &arg1)
{
QString to = arg1;
QString w = arg1;
QString whisper = arg1;
w.truncate(3);
whisper.truncate(9);
if(w == "/w " or w =="/W "){
to.remove("/w ",Qt::CaseInsensitive);
if(to.length() > 0 && to.endsWith(" ")){
to.chop(1);
receiver = to;
ui->sendButton->setText("To " + to);
ui->messageInput->clear();
}
}
if(whisper == "/whisper " or whisper =="/Whisper "){
to.remove("/whisper ",Qt::CaseInsensitive);
if(to.length() > 0 && to.endsWith(" ")){
to.chop(1);
receiver = to;
ui->sendButton->setText("To " + to);
ui->messageInput->clear();
}
}
// if(w=="/r " or w=="/R "){
}
void ChatWindow::sendMessage(){
chatGui->sendMessage(name,receiver,ui->messageInput->text());
}
void ChatWindow::on_actionBlack_triggered()
{
ui->messageInput->setStyleSheet("color: black;"
"background-color: grey;"
"selection-color: black;"
"selection-background-color: white");
ui->roomTree->setStyleSheet("color: black;"
"background-color: grey;"
"selection-color: black;"
"selection-background-color: white");
ui->messageHistory->setStyleSheet("color: black;"
"background-color: grey;"
"selection-color: black;"
"selection-background-color: white");
this->setStyleSheet("color: white;"
"background-color: black;"
"selection-color: black;"
"selection-background-color: white");
ui->mainToolBar->setStyleSheet("color: white;"
"background-color: black;"
"selection-color: black;"
"selection-background-color: white");
}
void ChatWindow::on_actionDefault_triggered()
{
ui->messageInput->setStyleSheet("");
ui->roomTree->setStyleSheet("");
ui->messageHistory->setStyleSheet("");
this->setStyleSheet("");
ui->mainToolBar->setStyleSheet("");
}
void ChatWindow::receiveHistory(QVector<QString> &historyVector){
for(int i = 0;i==historyVector.size(); i+=4){
ui->messageHistory->insertPlainText(historyVector.at(i) + " says: " + historyVector.at(i+2) + "\n");
}
}
<|endoftext|>
|
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#if defined _MSC_VER
#pragma warning(push, 1)
#endif
#include <windows.h>
#if defined _MSC_VER
#pragma warning(pop)
#endif
#include <malloc.h>
#include "internal/registry.hxx"
#if defined _MSC_VER
#pragma warning(push, 1)
#endif
#include <objbase.h>
#if defined _MSC_VER
#pragma warning(pop)
#endif
//---------------------------------------
// Size of a CLSID as a string
const int CLSID_STRING_SIZE = 39;
//---------------------------------------
bool SetRegistryKey(HKEY RootKey, const char* KeyName, const char* ValueName, const char* Value)
{
HKEY hSubKey;
// open or create the desired key
int rc = RegCreateKeyExA(
RootKey, KeyName, 0, "", REG_OPTION_NON_VOLATILE, KEY_WRITE, 0, &hSubKey, 0);
if (ERROR_SUCCESS == rc)
{
rc = RegSetValueExA(
hSubKey, ValueName, 0, REG_SZ, reinterpret_cast<const BYTE*>(Value), strlen(Value) + 1);
RegCloseKey(hSubKey);
}
return (ERROR_SUCCESS == rc);
}
//---------------------------------------
bool DeleteRegistryKey(HKEY RootKey, const char* KeyName)
{
HKEY hKey;
int rc = RegOpenKeyExA(
RootKey,
KeyName,
0,
KEY_READ | DELETE,
&hKey);
if ( rc == ERROR_FILE_NOT_FOUND )
return true;
if (ERROR_SUCCESS == rc)
{
char* SubKey;
DWORD nMaxSubKeyLen;
rc = RegQueryInfoKeyA(
hKey, 0, 0, 0, 0,
&nMaxSubKeyLen,
0, 0, 0, 0, 0, 0);
nMaxSubKeyLen++; // space for trailing '\0'
SubKey = reinterpret_cast<char*>(
_alloca(nMaxSubKeyLen*sizeof(char)));
while (ERROR_SUCCESS == rc)
{
DWORD nLen = nMaxSubKeyLen;
rc = RegEnumKeyExA(
hKey,
0, // always index zero
SubKey,
&nLen,
0, 0, 0, 0);
if (ERROR_NO_MORE_ITEMS == rc)
{
rc = RegDeleteKeyA(RootKey, KeyName);
break;
}
else if (rc == ERROR_SUCCESS)
{
DeleteRegistryKey(hKey, SubKey);
}
} // while
RegCloseKey(hKey);
} // if
return (ERROR_SUCCESS == rc);
}
/** May be used to determine if the specified registry key has subkeys
The function returns true on success else if an error occures false
*/
bool HasSubkeysRegistryKey(HKEY RootKey, const char* KeyName, /* out */ bool& bResult)
{
HKEY hKey;
LONG rc = RegOpenKeyExA(RootKey, KeyName, 0, KEY_READ, &hKey);
if (ERROR_SUCCESS == rc)
{
DWORD nSubKeys = 0;
rc = RegQueryInfoKeyA(hKey, 0, 0, 0, &nSubKeys, 0, 0, 0, 0, 0, 0, 0);
bResult = (nSubKeys > 0);
}
return (ERROR_SUCCESS == rc);
}
// Convert a CLSID to a char string.
std::string ClsidToString(const CLSID& clsid)
{
// Get CLSID
LPOLESTR wszCLSID = NULL;
StringFromCLSID(clsid, &wszCLSID);
char buff[39];
// Covert from wide characters to non-wide.
wcstombs(buff, wszCLSID, sizeof(buff));
// Free memory.
CoTaskMemFree(wszCLSID) ;
return std::string(buff);
}
//---------------------------------------
bool QueryRegistryKey(HKEY RootKey, const char* KeyName, const char* ValueName, char *pszData, DWORD dwBufLen)
{
HKEY hKey;
int rc = RegOpenKeyExA(
RootKey,
KeyName,
0,
KEY_READ,
&hKey);
if (ERROR_SUCCESS == rc)
{
rc = RegQueryValueExA(
hKey, ValueName, NULL, NULL, (LPBYTE)pszData,&dwBufLen);
RegCloseKey(hKey);
}
return (ERROR_SUCCESS == rc);
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>WaE: invalid conversion from 'const char*' to 'LPSTR'<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#if defined _MSC_VER
#pragma warning(push, 1)
#endif
#include <windows.h>
#if defined _MSC_VER
#pragma warning(pop)
#endif
#include <malloc.h>
#include "internal/registry.hxx"
#if defined _MSC_VER
#pragma warning(push, 1)
#endif
#include <objbase.h>
#if defined _MSC_VER
#pragma warning(pop)
#endif
//---------------------------------------
// Size of a CLSID as a string
const int CLSID_STRING_SIZE = 39;
//---------------------------------------
bool SetRegistryKey(HKEY RootKey, const char* KeyName, const char* ValueName, const char* Value)
{
HKEY hSubKey;
// open or create the desired key
char dummy[] = "";
int rc = RegCreateKeyExA(
RootKey, const_cast<char*>(KeyName), 0, dummy, REG_OPTION_NON_VOLATILE, KEY_WRITE, 0, &hSubKey, 0);
if (ERROR_SUCCESS == rc)
{
rc = RegSetValueExA(
hSubKey, ValueName, 0, REG_SZ, reinterpret_cast<const BYTE*>(Value), strlen(Value) + 1);
RegCloseKey(hSubKey);
}
return (ERROR_SUCCESS == rc);
}
//---------------------------------------
bool DeleteRegistryKey(HKEY RootKey, const char* KeyName)
{
HKEY hKey;
int rc = RegOpenKeyExA(
RootKey,
KeyName,
0,
KEY_READ | DELETE,
&hKey);
if ( rc == ERROR_FILE_NOT_FOUND )
return true;
if (ERROR_SUCCESS == rc)
{
char* SubKey;
DWORD nMaxSubKeyLen;
rc = RegQueryInfoKeyA(
hKey, 0, 0, 0, 0,
&nMaxSubKeyLen,
0, 0, 0, 0, 0, 0);
nMaxSubKeyLen++; // space for trailing '\0'
SubKey = reinterpret_cast<char*>(
_alloca(nMaxSubKeyLen*sizeof(char)));
while (ERROR_SUCCESS == rc)
{
DWORD nLen = nMaxSubKeyLen;
rc = RegEnumKeyExA(
hKey,
0, // always index zero
SubKey,
&nLen,
0, 0, 0, 0);
if (ERROR_NO_MORE_ITEMS == rc)
{
rc = RegDeleteKeyA(RootKey, KeyName);
break;
}
else if (rc == ERROR_SUCCESS)
{
DeleteRegistryKey(hKey, SubKey);
}
} // while
RegCloseKey(hKey);
} // if
return (ERROR_SUCCESS == rc);
}
/** May be used to determine if the specified registry key has subkeys
The function returns true on success else if an error occures false
*/
bool HasSubkeysRegistryKey(HKEY RootKey, const char* KeyName, /* out */ bool& bResult)
{
HKEY hKey;
LONG rc = RegOpenKeyExA(RootKey, KeyName, 0, KEY_READ, &hKey);
if (ERROR_SUCCESS == rc)
{
DWORD nSubKeys = 0;
rc = RegQueryInfoKeyA(hKey, 0, 0, 0, &nSubKeys, 0, 0, 0, 0, 0, 0, 0);
bResult = (nSubKeys > 0);
}
return (ERROR_SUCCESS == rc);
}
// Convert a CLSID to a char string.
std::string ClsidToString(const CLSID& clsid)
{
// Get CLSID
LPOLESTR wszCLSID = NULL;
StringFromCLSID(clsid, &wszCLSID);
char buff[39];
// Covert from wide characters to non-wide.
wcstombs(buff, wszCLSID, sizeof(buff));
// Free memory.
CoTaskMemFree(wszCLSID) ;
return std::string(buff);
}
//---------------------------------------
bool QueryRegistryKey(HKEY RootKey, const char* KeyName, const char* ValueName, char *pszData, DWORD dwBufLen)
{
HKEY hKey;
int rc = RegOpenKeyExA(
RootKey,
KeyName,
0,
KEY_READ,
&hKey);
if (ERROR_SUCCESS == rc)
{
rc = RegQueryValueExA(
hKey, ValueName, NULL, NULL, (LPBYTE)pszData,&dwBufLen);
RegCloseKey(hKey);
}
return (ERROR_SUCCESS == rc);
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>
|
<commit_before><commit_msg>Obey no transfer queue flag on Vulkan<commit_after><|endoftext|>
|
<commit_before>//===-- ARMFastISel.cpp - ARM FastISel implementation ---------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the ARM-specific support for the FastISel class. Some
// of the target-specific code is generated by tablegen in the file
// ARMGenFastISel.inc, which is #included here.
//
//===----------------------------------------------------------------------===//
#include "ARM.h"
#include "ARMRegisterInfo.h"
#include "ARMTargetMachine.h"
#include "ARMSubtarget.h"
#include "llvm/CallingConv.h"
#include "llvm/DerivedTypes.h"
#include "llvm/GlobalVariable.h"
#include "llvm/Instructions.h"
#include "llvm/IntrinsicInst.h"
#include "llvm/CodeGen/Analysis.h"
#include "llvm/CodeGen/FastISel.h"
#include "llvm/CodeGen/FunctionLoweringInfo.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineModuleInfo.h"
#include "llvm/CodeGen/MachineConstantPool.h"
#include "llvm/CodeGen/MachineFrameInfo.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/Support/CallSite.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/GetElementPtrTypeIterator.h"
#include "llvm/Target/TargetData.h"
#include "llvm/Target/TargetInstrInfo.h"
#include "llvm/Target/TargetLowering.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetOptions.h"
using namespace llvm;
static cl::opt<bool>
EnableARMFastISel("arm-fast-isel",
cl::desc("Turn on experimental ARM fast-isel support"),
cl::init(false), cl::Hidden);
namespace {
class ARMFastISel : public FastISel {
/// Subtarget - Keep a pointer to the ARMSubtarget around so that we can
/// make the right decision when generating code for different targets.
const ARMSubtarget *Subtarget;
const TargetMachine &TM;
const TargetInstrInfo &TII;
const TargetLowering &TLI;
public:
explicit ARMFastISel(FunctionLoweringInfo &funcInfo)
: FastISel(funcInfo),
TM(funcInfo.MF->getTarget()),
TII(*TM.getInstrInfo()),
TLI(*TM.getTargetLowering()) {
Subtarget = &TM.getSubtarget<ARMSubtarget>();
}
virtual unsigned FastEmitInst_(unsigned MachineInstOpcode,
const TargetRegisterClass *RC);
virtual unsigned FastEmitInst_r(unsigned MachineInstOpcode,
const TargetRegisterClass *RC,
unsigned Op0, bool Op0IsKill);
virtual unsigned FastEmitInst_rr(unsigned MachineInstOpcode,
const TargetRegisterClass *RC,
unsigned Op0, bool Op0IsKill,
unsigned Op1, bool Op1IsKill);
virtual unsigned FastEmitInst_ri(unsigned MachineInstOpcode,
const TargetRegisterClass *RC,
unsigned Op0, bool Op0IsKill,
uint64_t Imm);
virtual unsigned FastEmitInst_rf(unsigned MachineInstOpcode,
const TargetRegisterClass *RC,
unsigned Op0, bool Op0IsKill,
const ConstantFP *FPImm);
virtual unsigned FastEmitInst_i(unsigned MachineInstOpcode,
const TargetRegisterClass *RC,
uint64_t Imm);
virtual unsigned FastEmitInst_rri(unsigned MachineInstOpcode,
const TargetRegisterClass *RC,
unsigned Op0, bool Op0IsKill,
unsigned Op1, bool Op1IsKill,
uint64_t Imm);
virtual unsigned FastEmitInst_extractsubreg(MVT RetVT,
unsigned Op0, bool Op0IsKill,
uint32_t Idx);
virtual bool TargetSelectInstruction(const Instruction *I);
#include "ARMGenFastISel.inc"
};
} // end anonymous namespace
// #include "ARMGenCallingConv.inc"
unsigned ARMFastISel::FastEmitInst_(unsigned MachineInstOpcode,
const TargetRegisterClass* RC) {
unsigned ResultReg = createResultReg(RC);
const TargetInstrDesc &II = TII.get(MachineInstOpcode);
AddDefaultPred(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg));
return ResultReg;
}
unsigned ARMFastISel::FastEmitInst_r(unsigned MachineInstOpcode,
const TargetRegisterClass *RC,
unsigned Op0, bool Op0IsKill) {
unsigned ResultReg = createResultReg(RC);
const TargetInstrDesc &II = TII.get(MachineInstOpcode);
if (II.getNumDefs() >= 1)
AddDefaultPred(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
.addReg(Op0, Op0IsKill * RegState::Kill));
else {
AddDefaultPred(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
.addReg(Op0, Op0IsKill * RegState::Kill));
AddDefaultPred(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
TII.get(TargetOpcode::COPY), ResultReg)
.addReg(II.ImplicitDefs[0]));
}
return ResultReg;
}
unsigned ARMFastISel::FastEmitInst_rr(unsigned MachineInstOpcode,
const TargetRegisterClass *RC,
unsigned Op0, bool Op0IsKill,
unsigned Op1, bool Op1IsKill) {
unsigned ResultReg = createResultReg(RC);
const TargetInstrDesc &II = TII.get(MachineInstOpcode);
if (II.getNumDefs() >= 1)
AddDefaultPred(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
.addReg(Op0, Op0IsKill * RegState::Kill)
.addReg(Op1, Op1IsKill * RegState::Kill));
else {
AddDefaultPred(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
.addReg(Op0, Op0IsKill * RegState::Kill)
.addReg(Op1, Op1IsKill * RegState::Kill));
AddDefaultPred(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
TII.get(TargetOpcode::COPY), ResultReg)
.addReg(II.ImplicitDefs[0]));
}
return ResultReg;
}
unsigned ARMFastISel::FastEmitInst_ri(unsigned MachineInstOpcode,
const TargetRegisterClass *RC,
unsigned Op0, bool Op0IsKill,
uint64_t Imm) {
unsigned ResultReg = createResultReg(RC);
const TargetInstrDesc &II = TII.get(MachineInstOpcode);
if (II.getNumDefs() >= 1)
AddDefaultPred(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
.addReg(Op0, Op0IsKill * RegState::Kill)
.addImm(Imm));
else {
AddDefaultPred(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
.addReg(Op0, Op0IsKill * RegState::Kill)
.addImm(Imm));
AddDefaultPred(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
TII.get(TargetOpcode::COPY), ResultReg)
.addReg(II.ImplicitDefs[0]));
}
return ResultReg;
}
unsigned ARMFastISel::FastEmitInst_rf(unsigned MachineInstOpcode,
const TargetRegisterClass *RC,
unsigned Op0, bool Op0IsKill,
const ConstantFP *FPImm) {
unsigned ResultReg = createResultReg(RC);
const TargetInstrDesc &II = TII.get(MachineInstOpcode);
if (II.getNumDefs() >= 1)
AddDefaultPred(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
.addReg(Op0, Op0IsKill * RegState::Kill)
.addFPImm(FPImm));
else {
AddDefaultPred(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
.addReg(Op0, Op0IsKill * RegState::Kill)
.addFPImm(FPImm));
AddDefaultPred(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
TII.get(TargetOpcode::COPY), ResultReg)
.addReg(II.ImplicitDefs[0]));
}
return ResultReg;
}
unsigned ARMFastISel::FastEmitInst_rri(unsigned MachineInstOpcode,
const TargetRegisterClass *RC,
unsigned Op0, bool Op0IsKill,
unsigned Op1, bool Op1IsKill,
uint64_t Imm) {
unsigned ResultReg = createResultReg(RC);
const TargetInstrDesc &II = TII.get(MachineInstOpcode);
if (II.getNumDefs() >= 1)
AddDefaultPred(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
.addReg(Op0, Op0IsKill * RegState::Kill)
.addReg(Op1, Op1IsKill * RegState::Kill)
.addImm(Imm));
else {
AddDefaultPred(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
.addReg(Op0, Op0IsKill * RegState::Kill)
.addReg(Op1, Op1IsKill * RegState::Kill)
.addImm(Imm));
AddDefaultPred(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
TII.get(TargetOpcode::COPY), ResultReg)
.addReg(II.ImplicitDefs[0]));
}
return ResultReg;
}
unsigned ARMFastISel::FastEmitInst_i(unsigned MachineInstOpcode,
const TargetRegisterClass *RC,
uint64_t Imm) {
unsigned ResultReg = createResultReg(RC);
const TargetInstrDesc &II = TII.get(MachineInstOpcode);
if (II.getNumDefs() >= 1)
AddDefaultPred(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
.addImm(Imm));
else {
AddDefaultPred(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
.addImm(Imm));
AddDefaultPred(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
TII.get(TargetOpcode::COPY), ResultReg)
.addReg(II.ImplicitDefs[0]));
}
return ResultReg;
}
unsigned ARMFastISel::FastEmitInst_extractsubreg(MVT RetVT,
unsigned Op0, bool Op0IsKill,
uint32_t Idx) {
unsigned ResultReg = createResultReg(TLI.getRegClassFor(RetVT));
assert(TargetRegisterInfo::isVirtualRegister(Op0) &&
"Cannot yet extract from physregs");
AddDefaultPred(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt,
DL, TII.get(TargetOpcode::COPY), ResultReg)
.addReg(Op0, getKillRegState(Op0IsKill), Idx));
return ResultReg;
}
bool ARMFastISel::TargetSelectInstruction(const Instruction *I) {
switch (I->getOpcode()) {
default: break;
}
return false;
}
namespace llvm {
llvm::FastISel *ARM::createFastISel(FunctionLoweringInfo &funcInfo) {
if (EnableARMFastISel) return new ARMFastISel(funcInfo);
return 0;
}
}
<commit_msg>Add an AddOptionalDefs method and use it.<commit_after>//===-- ARMFastISel.cpp - ARM FastISel implementation ---------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the ARM-specific support for the FastISel class. Some
// of the target-specific code is generated by tablegen in the file
// ARMGenFastISel.inc, which is #included here.
//
//===----------------------------------------------------------------------===//
#include "ARM.h"
#include "ARMBaseInstrInfo.h"
#include "ARMRegisterInfo.h"
#include "ARMTargetMachine.h"
#include "ARMSubtarget.h"
#include "llvm/CallingConv.h"
#include "llvm/DerivedTypes.h"
#include "llvm/GlobalVariable.h"
#include "llvm/Instructions.h"
#include "llvm/IntrinsicInst.h"
#include "llvm/CodeGen/Analysis.h"
#include "llvm/CodeGen/FastISel.h"
#include "llvm/CodeGen/FunctionLoweringInfo.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineModuleInfo.h"
#include "llvm/CodeGen/MachineConstantPool.h"
#include "llvm/CodeGen/MachineFrameInfo.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/Support/CallSite.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/GetElementPtrTypeIterator.h"
#include "llvm/Target/TargetData.h"
#include "llvm/Target/TargetInstrInfo.h"
#include "llvm/Target/TargetLowering.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetOptions.h"
using namespace llvm;
static cl::opt<bool>
EnableARMFastISel("arm-fast-isel",
cl::desc("Turn on experimental ARM fast-isel support"),
cl::init(false), cl::Hidden);
namespace {
class ARMFastISel : public FastISel {
/// Subtarget - Keep a pointer to the ARMSubtarget around so that we can
/// make the right decision when generating code for different targets.
const ARMSubtarget *Subtarget;
const TargetMachine &TM;
const TargetInstrInfo &TII;
const TargetLowering &TLI;
public:
explicit ARMFastISel(FunctionLoweringInfo &funcInfo)
: FastISel(funcInfo),
TM(funcInfo.MF->getTarget()),
TII(*TM.getInstrInfo()),
TLI(*TM.getTargetLowering()) {
Subtarget = &TM.getSubtarget<ARMSubtarget>();
}
virtual unsigned FastEmitInst_(unsigned MachineInstOpcode,
const TargetRegisterClass *RC);
virtual unsigned FastEmitInst_r(unsigned MachineInstOpcode,
const TargetRegisterClass *RC,
unsigned Op0, bool Op0IsKill);
virtual unsigned FastEmitInst_rr(unsigned MachineInstOpcode,
const TargetRegisterClass *RC,
unsigned Op0, bool Op0IsKill,
unsigned Op1, bool Op1IsKill);
virtual unsigned FastEmitInst_ri(unsigned MachineInstOpcode,
const TargetRegisterClass *RC,
unsigned Op0, bool Op0IsKill,
uint64_t Imm);
virtual unsigned FastEmitInst_rf(unsigned MachineInstOpcode,
const TargetRegisterClass *RC,
unsigned Op0, bool Op0IsKill,
const ConstantFP *FPImm);
virtual unsigned FastEmitInst_i(unsigned MachineInstOpcode,
const TargetRegisterClass *RC,
uint64_t Imm);
virtual unsigned FastEmitInst_rri(unsigned MachineInstOpcode,
const TargetRegisterClass *RC,
unsigned Op0, bool Op0IsKill,
unsigned Op1, bool Op1IsKill,
uint64_t Imm);
virtual unsigned FastEmitInst_extractsubreg(MVT RetVT,
unsigned Op0, bool Op0IsKill,
uint32_t Idx);
virtual bool TargetSelectInstruction(const Instruction *I);
#include "ARMGenFastISel.inc"
private:
bool DefinesOptionalPredicate(MachineInstr *MI, bool *CPSR);
const MachineInstrBuilder &AddOptionalDefs(const MachineInstrBuilder &MIB);
};
} // end anonymous namespace
// #include "ARMGenCallingConv.inc"
// DefinesOptionalPredicate - This is different from DefinesPredicate in that
// we don't care about implicit defs here, just places we'll need to add a
// default CCReg argument. Sets CPSR if we're setting CPSR instead of CCR.
bool ARMFastISel::DefinesOptionalPredicate(MachineInstr *MI, bool *CPSR) {
const TargetInstrDesc &TID = MI->getDesc();
if (!TID.hasOptionalDef())
return false;
// Look to see if our OptionalDef is defining CPSR or CCR.
for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
const MachineOperand &MO = MI->getOperand(i);
if (MO.isDef() && MO.isReg() && MO.getReg() == ARM::CPSR)
*CPSR = true;
}
return true;
}
// If the machine is predicable go ahead and add the predicate operands, if
// it needs default CC operands add those.
const MachineInstrBuilder &
ARMFastISel::AddOptionalDefs(const MachineInstrBuilder &MIB) {
MachineInstr *MI = &*MIB;
// Do we use a predicate?
if (TII.isPredicable(MI))
AddDefaultPred(MIB);
// Do we optionally set a predicate? Preds is size > 0 iff the predicate
// defines CPSR. All other OptionalDefines in ARM are the CCR register.
bool CPSR;
if (DefinesOptionalPredicate(MI, &CPSR)) {
if (CPSR)
AddDefaultT1CC(MIB);
else
AddDefaultCC(MIB);
}
return MIB;
}
unsigned ARMFastISel::FastEmitInst_(unsigned MachineInstOpcode,
const TargetRegisterClass* RC) {
unsigned ResultReg = createResultReg(RC);
const TargetInstrDesc &II = TII.get(MachineInstOpcode);
AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg));
return ResultReg;
}
unsigned ARMFastISel::FastEmitInst_r(unsigned MachineInstOpcode,
const TargetRegisterClass *RC,
unsigned Op0, bool Op0IsKill) {
unsigned ResultReg = createResultReg(RC);
const TargetInstrDesc &II = TII.get(MachineInstOpcode);
if (II.getNumDefs() >= 1)
AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
.addReg(Op0, Op0IsKill * RegState::Kill));
else {
AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
.addReg(Op0, Op0IsKill * RegState::Kill));
AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
TII.get(TargetOpcode::COPY), ResultReg)
.addReg(II.ImplicitDefs[0]));
}
return ResultReg;
}
unsigned ARMFastISel::FastEmitInst_rr(unsigned MachineInstOpcode,
const TargetRegisterClass *RC,
unsigned Op0, bool Op0IsKill,
unsigned Op1, bool Op1IsKill) {
unsigned ResultReg = createResultReg(RC);
const TargetInstrDesc &II = TII.get(MachineInstOpcode);
if (II.getNumDefs() >= 1)
AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
.addReg(Op0, Op0IsKill * RegState::Kill)
.addReg(Op1, Op1IsKill * RegState::Kill));
else {
AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
.addReg(Op0, Op0IsKill * RegState::Kill)
.addReg(Op1, Op1IsKill * RegState::Kill));
AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
TII.get(TargetOpcode::COPY), ResultReg)
.addReg(II.ImplicitDefs[0]));
}
return ResultReg;
}
unsigned ARMFastISel::FastEmitInst_ri(unsigned MachineInstOpcode,
const TargetRegisterClass *RC,
unsigned Op0, bool Op0IsKill,
uint64_t Imm) {
unsigned ResultReg = createResultReg(RC);
const TargetInstrDesc &II = TII.get(MachineInstOpcode);
if (II.getNumDefs() >= 1)
AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
.addReg(Op0, Op0IsKill * RegState::Kill)
.addImm(Imm));
else {
AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
.addReg(Op0, Op0IsKill * RegState::Kill)
.addImm(Imm));
AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
TII.get(TargetOpcode::COPY), ResultReg)
.addReg(II.ImplicitDefs[0]));
}
return ResultReg;
}
unsigned ARMFastISel::FastEmitInst_rf(unsigned MachineInstOpcode,
const TargetRegisterClass *RC,
unsigned Op0, bool Op0IsKill,
const ConstantFP *FPImm) {
unsigned ResultReg = createResultReg(RC);
const TargetInstrDesc &II = TII.get(MachineInstOpcode);
if (II.getNumDefs() >= 1)
AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
.addReg(Op0, Op0IsKill * RegState::Kill)
.addFPImm(FPImm));
else {
AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
.addReg(Op0, Op0IsKill * RegState::Kill)
.addFPImm(FPImm));
AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
TII.get(TargetOpcode::COPY), ResultReg)
.addReg(II.ImplicitDefs[0]));
}
return ResultReg;
}
unsigned ARMFastISel::FastEmitInst_rri(unsigned MachineInstOpcode,
const TargetRegisterClass *RC,
unsigned Op0, bool Op0IsKill,
unsigned Op1, bool Op1IsKill,
uint64_t Imm) {
unsigned ResultReg = createResultReg(RC);
const TargetInstrDesc &II = TII.get(MachineInstOpcode);
if (II.getNumDefs() >= 1)
AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
.addReg(Op0, Op0IsKill * RegState::Kill)
.addReg(Op1, Op1IsKill * RegState::Kill)
.addImm(Imm));
else {
AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
.addReg(Op0, Op0IsKill * RegState::Kill)
.addReg(Op1, Op1IsKill * RegState::Kill)
.addImm(Imm));
AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
TII.get(TargetOpcode::COPY), ResultReg)
.addReg(II.ImplicitDefs[0]));
}
return ResultReg;
}
unsigned ARMFastISel::FastEmitInst_i(unsigned MachineInstOpcode,
const TargetRegisterClass *RC,
uint64_t Imm) {
unsigned ResultReg = createResultReg(RC);
const TargetInstrDesc &II = TII.get(MachineInstOpcode);
if (II.getNumDefs() >= 1)
AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
.addImm(Imm));
else {
AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
.addImm(Imm));
AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
TII.get(TargetOpcode::COPY), ResultReg)
.addReg(II.ImplicitDefs[0]));
}
return ResultReg;
}
unsigned ARMFastISel::FastEmitInst_extractsubreg(MVT RetVT,
unsigned Op0, bool Op0IsKill,
uint32_t Idx) {
unsigned ResultReg = createResultReg(TLI.getRegClassFor(RetVT));
assert(TargetRegisterInfo::isVirtualRegister(Op0) &&
"Cannot yet extract from physregs");
AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt,
DL, TII.get(TargetOpcode::COPY), ResultReg)
.addReg(Op0, getKillRegState(Op0IsKill), Idx));
return ResultReg;
}
bool ARMFastISel::TargetSelectInstruction(const Instruction *I) {
switch (I->getOpcode()) {
default: break;
}
return false;
}
namespace llvm {
llvm::FastISel *ARM::createFastISel(FunctionLoweringInfo &funcInfo) {
if (EnableARMFastISel) return new ARMFastISel(funcInfo);
return 0;
}
}
<|endoftext|>
|
<commit_before>//===- Inliner.cpp - Code common to all inliners --------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the mechanics required to implement inlining without
// missing any calls and updating the call graph. The decisions of which calls
// are profitable to inline are implemented elsewhere.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "inline"
#include "llvm/Module.h"
#include "llvm/Instructions.h"
#include "llvm/Analysis/CallGraph.h"
#include "llvm/Support/CallSite.h"
#include "llvm/Target/TargetData.h"
#include "llvm/Transforms/IPO/InlinerPass.h"
#include "llvm/Transforms/Utils/Cloning.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/ADT/Statistic.h"
#include <set>
using namespace llvm;
STATISTIC(NumInlined, "Number of functions inlined");
STATISTIC(NumDeleted, "Number of functions deleted because all callers found");
static cl::opt<int>
InlineLimit("inline-threshold", cl::Hidden, cl::init(200),
cl::desc("Control the amount of inlining to perform (default = 200)"));
Inliner::Inliner(void *ID)
: CallGraphSCCPass(ID), InlineThreshold(InlineLimit) {}
Inliner::Inliner(void *ID, int Threshold)
: CallGraphSCCPass(ID), InlineThreshold(Threshold) {}
/// getAnalysisUsage - For this class, we declare that we require and preserve
/// the call graph. If the derived class implements this method, it should
/// always explicitly call the implementation here.
void Inliner::getAnalysisUsage(AnalysisUsage &Info) const {
Info.addRequired<TargetData>();
CallGraphSCCPass::getAnalysisUsage(Info);
}
// InlineCallIfPossible - If it is possible to inline the specified call site,
// do so and update the CallGraph for this operation.
static bool InlineCallIfPossible(CallSite CS, CallGraph &CG,
const std::set<Function*> &SCCFunctions,
const TargetData &TD) {
Function *Callee = CS.getCalledFunction();
if (!InlineFunction(CS, &CG, &TD)) return false;
// If the inlined function had a higher stack protection level than the
// calling function, then bump up the caller's stack protection level.
Function *Caller = CS.getCaller();
if (Callee->hasFnAttr(Attribute::StackProtectReq))
Caller->addFnAttr(Attribute::StackProtectReq);
else if (Callee->hasFnAttr(Attribute::StackProtect) &&
!Caller->hasFnAttr(Attribute::StackProtectReq))
Caller->addFnAttr(Attribute::StackProtect);
// If we inlined the last possible call site to the function, delete the
// function body now.
if (Callee->use_empty() && Callee->hasInternalLinkage() &&
!SCCFunctions.count(Callee)) {
DOUT << " -> Deleting dead function: " << Callee->getName() << "\n";
CallGraphNode *CalleeNode = CG[Callee];
// Remove any call graph edges from the callee to its callees.
CalleeNode->removeAllCalledFunctions();
// Removing the node for callee from the call graph and delete it.
delete CG.removeFunctionFromModule(CalleeNode);
++NumDeleted;
}
return true;
}
/// shouldInline - Return true if the inliner should attempt to inline
/// at the given CallSite.
bool Inliner::shouldInline(CallSite CS) {
InlineCost IC = getInlineCost(CS);
float FudgeFactor = getInlineFudgeFactor(CS);
if (IC.isAlways()) {
DOUT << " Inlining: cost=always"
<< ", Call: " << *CS.getInstruction();
return true;
}
if (IC.isNever()) {
DOUT << " NOT Inlining: cost=never"
<< ", Call: " << *CS.getInstruction();
return false;
}
int Cost = IC.getValue();
int CurrentThreshold = InlineThreshold;
Function *Fn = CS.getCaller();
if (Fn && !Fn->isDeclaration()
&& Fn->hasFnAttr(Attribute::OptimizeForSize)
&& InlineThreshold != 50) {
CurrentThreshold = 50;
}
if (Cost >= (int)(CurrentThreshold * FudgeFactor)) {
DOUT << " NOT Inlining: cost=" << Cost
<< ", Call: " << *CS.getInstruction();
return false;
} else {
DOUT << " Inlining: cost=" << Cost
<< ", Call: " << *CS.getInstruction();
return true;
}
}
bool Inliner::runOnSCC(const std::vector<CallGraphNode*> &SCC) {
CallGraph &CG = getAnalysis<CallGraph>();
std::set<Function*> SCCFunctions;
DOUT << "Inliner visiting SCC:";
for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
Function *F = SCC[i]->getFunction();
if (F) SCCFunctions.insert(F);
DOUT << " " << (F ? F->getName() : "INDIRECTNODE");
}
// Scan through and identify all call sites ahead of time so that we only
// inline call sites in the original functions, not call sites that result
// from inlining other functions.
std::vector<CallSite> CallSites;
for (unsigned i = 0, e = SCC.size(); i != e; ++i)
if (Function *F = SCC[i]->getFunction())
for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) {
CallSite CS = CallSite::get(I);
if (CS.getInstruction() && (!CS.getCalledFunction() ||
!CS.getCalledFunction()->isDeclaration()))
CallSites.push_back(CS);
}
DOUT << ": " << CallSites.size() << " call sites.\n";
// Now that we have all of the call sites, move the ones to functions in the
// current SCC to the end of the list.
unsigned FirstCallInSCC = CallSites.size();
for (unsigned i = 0; i < FirstCallInSCC; ++i)
if (Function *F = CallSites[i].getCalledFunction())
if (SCCFunctions.count(F))
std::swap(CallSites[i--], CallSites[--FirstCallInSCC]);
// Now that we have all of the call sites, loop over them and inline them if
// it looks profitable to do so.
bool Changed = false;
bool LocalChange;
do {
LocalChange = false;
// Iterate over the outer loop because inlining functions can cause indirect
// calls to become direct calls.
for (unsigned CSi = 0; CSi != CallSites.size(); ++CSi)
if (Function *Callee = CallSites[CSi].getCalledFunction()) {
// Calls to external functions are never inlinable.
if (Callee->isDeclaration() ||
CallSites[CSi].getInstruction()->getParent()->getParent() ==Callee){
if (SCC.size() == 1) {
std::swap(CallSites[CSi], CallSites.back());
CallSites.pop_back();
} else {
// Keep the 'in SCC / not in SCC' boundary correct.
CallSites.erase(CallSites.begin()+CSi);
}
--CSi;
continue;
}
// If the policy determines that we should inline this function,
// try to do so.
CallSite CS = CallSites[CSi];
if (shouldInline(CS)) {
// Attempt to inline the function...
if (InlineCallIfPossible(CS, CG, SCCFunctions,
getAnalysis<TargetData>())) {
// Remove this call site from the list. If possible, use
// swap/pop_back for efficiency, but do not use it if doing so would
// move a call site to a function in this SCC before the
// 'FirstCallInSCC' barrier.
if (SCC.size() == 1) {
std::swap(CallSites[CSi], CallSites.back());
CallSites.pop_back();
} else {
CallSites.erase(CallSites.begin()+CSi);
}
--CSi;
++NumInlined;
Changed = true;
LocalChange = true;
}
}
}
} while (LocalChange);
return Changed;
}
// doFinalization - Remove now-dead linkonce functions at the end of
// processing to avoid breaking the SCC traversal.
bool Inliner::doFinalization(CallGraph &CG) {
return removeDeadFunctions(CG);
}
/// removeDeadFunctions - Remove dead functions that are not included in
/// DNR (Do Not Remove) list.
bool Inliner::removeDeadFunctions(CallGraph &CG,
SmallPtrSet<const Function *, 16> *DNR) {
std::set<CallGraphNode*> FunctionsToRemove;
// Scan for all of the functions, looking for ones that should now be removed
// from the program. Insert the dead ones in the FunctionsToRemove set.
for (CallGraph::iterator I = CG.begin(), E = CG.end(); I != E; ++I) {
CallGraphNode *CGN = I->second;
if (Function *F = CGN ? CGN->getFunction() : 0) {
// If the only remaining users of the function are dead constants, remove
// them.
F->removeDeadConstantUsers();
if (DNR && DNR->count(F))
continue;
if ((F->hasLinkOnceLinkage() || F->hasInternalLinkage()) &&
F->use_empty()) {
// Remove any call graph edges from the function to its callees.
CGN->removeAllCalledFunctions();
// Remove any edges from the external node to the function's call graph
// node. These edges might have been made irrelegant due to
// optimization of the program.
CG.getExternalCallingNode()->removeAnyCallEdgeTo(CGN);
// Removing the node for callee from the call graph and delete it.
FunctionsToRemove.insert(CGN);
}
}
}
// Now that we know which functions to delete, do so. We didn't want to do
// this inline, because that would invalidate our CallGraph::iterator
// objects. :(
bool Changed = false;
for (std::set<CallGraphNode*>::iterator I = FunctionsToRemove.begin(),
E = FunctionsToRemove.end(); I != E; ++I) {
delete CG.removeFunctionFromModule(*I);
++NumDeleted;
Changed = true;
}
return Changed;
}
<commit_msg>Fix error where it wasn't getting the correct caller function.<commit_after>//===- Inliner.cpp - Code common to all inliners --------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the mechanics required to implement inlining without
// missing any calls and updating the call graph. The decisions of which calls
// are profitable to inline are implemented elsewhere.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "inline"
#include "llvm/Module.h"
#include "llvm/Instructions.h"
#include "llvm/Analysis/CallGraph.h"
#include "llvm/Support/CallSite.h"
#include "llvm/Target/TargetData.h"
#include "llvm/Transforms/IPO/InlinerPass.h"
#include "llvm/Transforms/Utils/Cloning.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/ADT/Statistic.h"
#include <set>
using namespace llvm;
STATISTIC(NumInlined, "Number of functions inlined");
STATISTIC(NumDeleted, "Number of functions deleted because all callers found");
static cl::opt<int>
InlineLimit("inline-threshold", cl::Hidden, cl::init(200),
cl::desc("Control the amount of inlining to perform (default = 200)"));
Inliner::Inliner(void *ID)
: CallGraphSCCPass(ID), InlineThreshold(InlineLimit) {}
Inliner::Inliner(void *ID, int Threshold)
: CallGraphSCCPass(ID), InlineThreshold(Threshold) {}
/// getAnalysisUsage - For this class, we declare that we require and preserve
/// the call graph. If the derived class implements this method, it should
/// always explicitly call the implementation here.
void Inliner::getAnalysisUsage(AnalysisUsage &Info) const {
Info.addRequired<TargetData>();
CallGraphSCCPass::getAnalysisUsage(Info);
}
// InlineCallIfPossible - If it is possible to inline the specified call site,
// do so and update the CallGraph for this operation.
static bool InlineCallIfPossible(CallSite CS, CallGraph &CG,
const std::set<Function*> &SCCFunctions,
const TargetData &TD) {
Function *Callee = CS.getCalledFunction();
Function *Caller = CS.getCaller();
if (!InlineFunction(CS, &CG, &TD)) return false;
// If the inlined function had a higher stack protection level than the
// calling function, then bump up the caller's stack protection level.
if (Callee->hasFnAttr(Attribute::StackProtectReq))
Caller->addFnAttr(Attribute::StackProtectReq);
else if (Callee->hasFnAttr(Attribute::StackProtect) &&
!Caller->hasFnAttr(Attribute::StackProtectReq))
Caller->addFnAttr(Attribute::StackProtect);
// If we inlined the last possible call site to the function, delete the
// function body now.
if (Callee->use_empty() && Callee->hasInternalLinkage() &&
!SCCFunctions.count(Callee)) {
DOUT << " -> Deleting dead function: " << Callee->getName() << "\n";
CallGraphNode *CalleeNode = CG[Callee];
// Remove any call graph edges from the callee to its callees.
CalleeNode->removeAllCalledFunctions();
// Removing the node for callee from the call graph and delete it.
delete CG.removeFunctionFromModule(CalleeNode);
++NumDeleted;
}
return true;
}
/// shouldInline - Return true if the inliner should attempt to inline
/// at the given CallSite.
bool Inliner::shouldInline(CallSite CS) {
InlineCost IC = getInlineCost(CS);
float FudgeFactor = getInlineFudgeFactor(CS);
if (IC.isAlways()) {
DOUT << " Inlining: cost=always"
<< ", Call: " << *CS.getInstruction();
return true;
}
if (IC.isNever()) {
DOUT << " NOT Inlining: cost=never"
<< ", Call: " << *CS.getInstruction();
return false;
}
int Cost = IC.getValue();
int CurrentThreshold = InlineThreshold;
Function *Fn = CS.getCaller();
if (Fn && !Fn->isDeclaration()
&& Fn->hasFnAttr(Attribute::OptimizeForSize)
&& InlineThreshold != 50) {
CurrentThreshold = 50;
}
if (Cost >= (int)(CurrentThreshold * FudgeFactor)) {
DOUT << " NOT Inlining: cost=" << Cost
<< ", Call: " << *CS.getInstruction();
return false;
} else {
DOUT << " Inlining: cost=" << Cost
<< ", Call: " << *CS.getInstruction();
return true;
}
}
bool Inliner::runOnSCC(const std::vector<CallGraphNode*> &SCC) {
CallGraph &CG = getAnalysis<CallGraph>();
std::set<Function*> SCCFunctions;
DOUT << "Inliner visiting SCC:";
for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
Function *F = SCC[i]->getFunction();
if (F) SCCFunctions.insert(F);
DOUT << " " << (F ? F->getName() : "INDIRECTNODE");
}
// Scan through and identify all call sites ahead of time so that we only
// inline call sites in the original functions, not call sites that result
// from inlining other functions.
std::vector<CallSite> CallSites;
for (unsigned i = 0, e = SCC.size(); i != e; ++i)
if (Function *F = SCC[i]->getFunction())
for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) {
CallSite CS = CallSite::get(I);
if (CS.getInstruction() && (!CS.getCalledFunction() ||
!CS.getCalledFunction()->isDeclaration()))
CallSites.push_back(CS);
}
DOUT << ": " << CallSites.size() << " call sites.\n";
// Now that we have all of the call sites, move the ones to functions in the
// current SCC to the end of the list.
unsigned FirstCallInSCC = CallSites.size();
for (unsigned i = 0; i < FirstCallInSCC; ++i)
if (Function *F = CallSites[i].getCalledFunction())
if (SCCFunctions.count(F))
std::swap(CallSites[i--], CallSites[--FirstCallInSCC]);
// Now that we have all of the call sites, loop over them and inline them if
// it looks profitable to do so.
bool Changed = false;
bool LocalChange;
do {
LocalChange = false;
// Iterate over the outer loop because inlining functions can cause indirect
// calls to become direct calls.
for (unsigned CSi = 0; CSi != CallSites.size(); ++CSi)
if (Function *Callee = CallSites[CSi].getCalledFunction()) {
// Calls to external functions are never inlinable.
if (Callee->isDeclaration() ||
CallSites[CSi].getInstruction()->getParent()->getParent() ==Callee){
if (SCC.size() == 1) {
std::swap(CallSites[CSi], CallSites.back());
CallSites.pop_back();
} else {
// Keep the 'in SCC / not in SCC' boundary correct.
CallSites.erase(CallSites.begin()+CSi);
}
--CSi;
continue;
}
// If the policy determines that we should inline this function,
// try to do so.
CallSite CS = CallSites[CSi];
if (shouldInline(CS)) {
// Attempt to inline the function...
if (InlineCallIfPossible(CS, CG, SCCFunctions,
getAnalysis<TargetData>())) {
// Remove this call site from the list. If possible, use
// swap/pop_back for efficiency, but do not use it if doing so would
// move a call site to a function in this SCC before the
// 'FirstCallInSCC' barrier.
if (SCC.size() == 1) {
std::swap(CallSites[CSi], CallSites.back());
CallSites.pop_back();
} else {
CallSites.erase(CallSites.begin()+CSi);
}
--CSi;
++NumInlined;
Changed = true;
LocalChange = true;
}
}
}
} while (LocalChange);
return Changed;
}
// doFinalization - Remove now-dead linkonce functions at the end of
// processing to avoid breaking the SCC traversal.
bool Inliner::doFinalization(CallGraph &CG) {
return removeDeadFunctions(CG);
}
/// removeDeadFunctions - Remove dead functions that are not included in
/// DNR (Do Not Remove) list.
bool Inliner::removeDeadFunctions(CallGraph &CG,
SmallPtrSet<const Function *, 16> *DNR) {
std::set<CallGraphNode*> FunctionsToRemove;
// Scan for all of the functions, looking for ones that should now be removed
// from the program. Insert the dead ones in the FunctionsToRemove set.
for (CallGraph::iterator I = CG.begin(), E = CG.end(); I != E; ++I) {
CallGraphNode *CGN = I->second;
if (Function *F = CGN ? CGN->getFunction() : 0) {
// If the only remaining users of the function are dead constants, remove
// them.
F->removeDeadConstantUsers();
if (DNR && DNR->count(F))
continue;
if ((F->hasLinkOnceLinkage() || F->hasInternalLinkage()) &&
F->use_empty()) {
// Remove any call graph edges from the function to its callees.
CGN->removeAllCalledFunctions();
// Remove any edges from the external node to the function's call graph
// node. These edges might have been made irrelegant due to
// optimization of the program.
CG.getExternalCallingNode()->removeAnyCallEdgeTo(CGN);
// Removing the node for callee from the call graph and delete it.
FunctionsToRemove.insert(CGN);
}
}
}
// Now that we know which functions to delete, do so. We didn't want to do
// this inline, because that would invalidate our CallGraph::iterator
// objects. :(
bool Changed = false;
for (std::set<CallGraphNode*>::iterator I = FunctionsToRemove.begin(),
E = FunctionsToRemove.end(); I != E; ++I) {
delete CG.removeFunctionFromModule(*I);
++NumDeleted;
Changed = true;
}
return Changed;
}
<|endoftext|>
|
<commit_before>/*
* detector_helpers.cc
*
* Copyright (C) 2013 Diamond Light Source
*
* Author: James Parkhurst
*
* This code is distributed under the BSD license, a copy of which is
* included in the root directory of this package.
*/
#include <boost/python.hpp>
#include <boost/python/def.hpp>
#include <boost/format.hpp>
#include <string>
#include <dials/model/experiment/detector.h>
#include <dials/model/experiment/detector_helpers.h>
namespace dials { namespace model { namespace boost_python {
using namespace boost::python;
template <typename DetectorType>
is_coordinate_valid <DetectorType> make_is_coordinate_valid(
const DetectorType& detector) {
return is_coordinate_valid<DetectorType>(detector);
}
template <typename DetectorType>
diffracted_beam_intersection <DetectorType> make_diffracted_beam_intersection(
const DetectorType& detector) {
return diffracted_beam_intersection<DetectorType>(detector);
}
void export_is_coordinate_valid()
{
class_<is_coordinate_valid<FlatPanelDetector> >(
"FlatPanelDetector_is_coordinate_valid", no_init)
.def("__call__",
&is_coordinate_valid<FlatPanelDetector>::operator() <vec2 <double> >);
class_<is_coordinate_valid<MultiFlatPanelDetector> >(
"MultiFlatPanelDetector_is_coordinate_valid", no_init)
.def("__call__",
&is_coordinate_valid<MultiFlatPanelDetector>::operator() <vec3 <double> >);
def("is_coordinate_valid",
&make_is_coordinate_valid<FlatPanelDetector>);
def("is_coordinate_valid",
&make_is_coordinate_valid<MultiFlatPanelDetector>);
}
void export_diffracted_beam_intersection()
{
class_<diffracted_beam_intersection<FlatPanelDetector> >(
"FlatPanelDetector_diffracted_beam_intersection", no_init)
.def("__call__",
&diffracted_beam_intersection<FlatPanelDetector>::operator());
vec3<double> (diffracted_beam_intersection<MultiFlatPanelDetector>::*func)(vec3<double>) const =
&diffracted_beam_intersection<MultiFlatPanelDetector>::operator();
vec3<double> (diffracted_beam_intersection<MultiFlatPanelDetector>::*func2)(vec3<double>, std::size_t) const =
&diffracted_beam_intersection<MultiFlatPanelDetector>::operator();
class_<diffracted_beam_intersection<MultiFlatPanelDetector> >(
"MultiFlatPanelDetector_diffracted_beam_intersection", no_init)
.def("__call__", func);
.def("__call__", func2);
def("diffracted_beam_intersection",
&make_diffracted_beam_intersection<FlatPanelDetector>);
def("diffracted_beam_intersection",
&make_diffracted_beam_intersection<MultiFlatPanelDetector>);
}
void export_detector_helpers()
{
export_is_coordinate_valid();
export_diffracted_beam_intersection();
}
}}} // namespace = dials::model::boost_python
<commit_msg>Previous commit didn't build; fixed<commit_after>/*
* detector_helpers.cc
*
* Copyright (C) 2013 Diamond Light Source
*
* Author: James Parkhurst
*
* This code is distributed under the BSD license, a copy of which is
* included in the root directory of this package.
*/
#include <boost/python.hpp>
#include <boost/python/def.hpp>
#include <boost/format.hpp>
#include <string>
#include <dials/model/experiment/detector.h>
#include <dials/model/experiment/detector_helpers.h>
namespace dials { namespace model { namespace boost_python {
using namespace boost::python;
template <typename DetectorType>
is_coordinate_valid <DetectorType> make_is_coordinate_valid(
const DetectorType& detector) {
return is_coordinate_valid<DetectorType>(detector);
}
template <typename DetectorType>
diffracted_beam_intersection <DetectorType> make_diffracted_beam_intersection(
const DetectorType& detector) {
return diffracted_beam_intersection<DetectorType>(detector);
}
void export_is_coordinate_valid()
{
class_<is_coordinate_valid<FlatPanelDetector> >(
"FlatPanelDetector_is_coordinate_valid", no_init)
.def("__call__",
&is_coordinate_valid<FlatPanelDetector>::operator() <vec2 <double> >);
class_<is_coordinate_valid<MultiFlatPanelDetector> >(
"MultiFlatPanelDetector_is_coordinate_valid", no_init)
.def("__call__",
&is_coordinate_valid<MultiFlatPanelDetector>::operator() <vec3 <double> >);
def("is_coordinate_valid",
&make_is_coordinate_valid<FlatPanelDetector>);
def("is_coordinate_valid",
&make_is_coordinate_valid<MultiFlatPanelDetector>);
}
void export_diffracted_beam_intersection()
{
class_<diffracted_beam_intersection<FlatPanelDetector> >(
"FlatPanelDetector_diffracted_beam_intersection", no_init)
.def("__call__",
&diffracted_beam_intersection<FlatPanelDetector>::operator());
vec3<double> (diffracted_beam_intersection<MultiFlatPanelDetector>::*func)(vec3<double>) const =
&diffracted_beam_intersection<MultiFlatPanelDetector>::operator();
vec3<double> (diffracted_beam_intersection<MultiFlatPanelDetector>::*func2)(vec3<double>, std::size_t) const =
&diffracted_beam_intersection<MultiFlatPanelDetector>::operator();
class_<diffracted_beam_intersection<MultiFlatPanelDetector> >(
"MultiFlatPanelDetector_diffracted_beam_intersection", no_init)
.def("__call__", func)
.def("__call__", func2);
def("diffracted_beam_intersection",
&make_diffracted_beam_intersection<FlatPanelDetector>);
def("diffracted_beam_intersection",
&make_diffracted_beam_intersection<MultiFlatPanelDetector>);
}
void export_detector_helpers()
{
export_is_coordinate_valid();
export_diffracted_beam_intersection();
}
}}} // namespace = dials::model::boost_python
<|endoftext|>
|
<commit_before>/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2017 *
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy of this *
* software and associated documentation files (the "Software"), to deal in the Software *
* without restriction, including without limitation the rights to use, copy, modify, *
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to *
* permit persons to whom the Software is furnished to do so, subject to the following *
* conditions: *
* *
* The above copyright notice and this permission notice shall be included in all copies *
* or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A *
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF *
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE *
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
****************************************************************************************/
#include <modules/newhorizons/rendering/renderablecrawlingline.h>
#include <openspace/documentation/documentation.h>
#include <openspace/documentation/verifier.h>
#include <openspace/engine/openspaceengine.h>
#include <openspace/rendering/renderengine.h>
#include <openspace/util/spicemanager.h>
#include <modules/newhorizons/util/imagesequencer.h>
namespace {
const char* KeySource = "Source";
const char* KeyTarget = "Target";
const char* KeyInstrument = "Instrument";
const char* KeyColor = "Color";
const char* KeyColorStart = "Start";
const char* KeyColorEnd = "End";
struct VBOData {
float position[3];
float color[4];
};
} // namespace
namespace openspace {
documentation::Documentation RenderableCrawlingLine::Documentation() {
using namespace documentation;
return {
"RenderableCrawlingLine",
"newhorizons_renderable_crawlingline",
{
{
KeySource,
new StringVerifier,
"Denotes the SPICE name of the source of the renderable crawling line, "
"for example, the space craft",
Optional::No
},
{
KeyTarget,
new StringVerifier,
"Denotes the SPICE name of the target of the crawling line",
Optional::Yes
},
{
KeyInstrument,
new StringVerifier,
"Denotes the SPICE name of the instrument that is used to render the "
"crawling line",
Optional::No
},
{
KeyColor,
new TableVerifier({
{
{
KeyColorStart,
new DoubleVector4Verifier,
"The color at the start of the line",
Optional::No
},
{
KeyColorEnd,
new DoubleVector4Verifier,
"The color at the end of the line",
Optional::No
}
},
Exhaustive::Yes
}),
"Specifies the colors that are used for the crawling line. One value "
"determines the starting color of the line, the second value is the "
"color at the end of the line.",
Optional::No
}
}
};
}
RenderableCrawlingLine::RenderableCrawlingLine(const ghoul::Dictionary& dictionary)
: Renderable(dictionary)
, _program(nullptr)
, _imageSequenceTime(-1.f)
, _vao(0)
, _vbo(0)
, _frameCounter(0)
, _drawLine(false)
{
documentation::testSpecificationAndThrow(
Documentation(),
dictionary,
"RenderableCrawlingLine"
);
_source = dictionary.value<std::string>(KeySource);
_target = dictionary.value<std::string>(KeyTarget);
_instrumentName = dictionary.value<std::string>(KeyInstrument);
_lineColorBegin = dictionary.value<glm::vec4>(
std::string(KeyColor) + "." + KeyColorStart
);
_lineColorEnd = dictionary.value<glm::vec4>(
std::string(KeyColor) + "." + KeyColorEnd
);
}
bool RenderableCrawlingLine::isReady() const {
return (_program != nullptr);
}
bool RenderableCrawlingLine::initialize() {
RenderEngine& renderEngine = OsEng.renderEngine();
_program = renderEngine.buildRenderProgram(
"RenderableCrawlingLine",
"${MODULE_NEWHORIZONS}/shaders/crawlingline_vs.glsl",
"${MODULE_NEWHORIZONS}/shaders/crawlingline_fs.glsl"
);
glGenVertexArrays(1, &_vao);
glGenBuffers(1, &_vbo);
glBindVertexArray(_vao);
glBindBuffer(GL_ARRAY_BUFFER, _vbo);
glBufferData(GL_ARRAY_BUFFER, 2 * sizeof(VBOData), NULL, GL_DYNAMIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, sizeof(VBOData), (void*)0);
glEnableVertexAttribArray(1);
glVertexAttribPointer(
1,
4,
GL_FLOAT,
GL_FALSE,
sizeof(VBOData),
reinterpret_cast<void*>(offsetof(VBOData, color))
);
glBindVertexArray(0);
return true;
}
bool RenderableCrawlingLine::deinitialize(){
glDeleteVertexArrays(1, &_vao);
_vao = 0;
glDeleteBuffers(1, &_vbo);
_vbo = 0;
RenderEngine& renderEngine = OsEng.renderEngine();
if (_program) {
renderEngine.removeRenderProgram(_program);
_program = nullptr;
}
return true;
}
void RenderableCrawlingLine::render(const RenderData& data) {
if (!_drawLine) {
return;
}
_program->activate();
_frameCounter++;
glm::dmat4 modelTransform =
glm::translate(glm::dmat4(1.0), data.modelTransform.translation) * // Translation
glm::dmat4(data.modelTransform.rotation) * // Spice rotation
glm::scale(glm::dmat4(1.0), glm::dvec3(data.modelTransform.scale));
glm::dmat4 modelViewProjectionTransform =
data.camera.projectionMatrix() *
glm::mat4(data.camera.combinedViewMatrix() *
modelTransform
)
;
//glm::dmat4 modelViewTransform = data.camera.combinedViewMatrix() * modelTransform;
// setup the data to the shader
//_program->setUniform("modelViewTransform", glm::mat4(modelViewTransform));
//_program->setUniform("projectionTransform", data.camera.projectionMatrix());
_program->setUniform("modelViewProjection", modelViewProjectionTransform);
int frame = _frameCounter % 60;
float fadingFactor = static_cast<float>(sin((frame * 3.14159) / 60));
float alpha = 0.6f + fadingFactor*0.4f;
glLineWidth(2.f);
_program->setUniform("_alpha", alpha);
//_program->setUniform("color", _lineColor);
//setPscUniforms(*_program.get(), data.camera, data.position);
glBindVertexArray(_vao);
glDrawArrays(GL_LINES, 0, 2);
glBindVertexArray(0);
_program->deactivate();
}
void RenderableCrawlingLine::update(const UpdateData& data) {
if (_program->isDirty()) {
_program->rebuildFromFile();
}
glm::dmat3 transformMatrix = SpiceManager::ref().positionTransformMatrix(
_source,
//"ECLIPJ2000",
"GALACTIC",
data.time
);
glm::dmat3 tm = SpiceManager::ref().frameTransformationMatrix(_instrumentName, "ECLIPJ2000", data.time);
//_positions[SourcePosition] = { 0.f, 0.f, 0.f, 0.f };
glm::dvec3 boresight;
//try {
SpiceManager::FieldOfViewResult res =
SpiceManager::ref().fieldOfView(_source);
boresight = res.boresightVector;
//}
//catch (const SpiceManager::SpiceException& e) {
//LERROR(e.what());
//}
glm::vec4 target(boresight[0], boresight[1], boresight[2], 12);
//target = glm::dmat4(tm) * target;
//_positions[TargetPosition] = target;
//_positions[TargetPosition] = {
// target.x * pow(10, target.w),
// target.y * pow(10, target.w),
// target.z * pow(10, target.w),
// 0
//};
VBOData vboData[2] = {
{
{ 0.f, 0.f, 0.f },
_lineColorBegin.r, _lineColorBegin.g, _lineColorBegin.b, _lineColorBegin.a
},
{
{ target.x * pow(10, target.w), target.y * pow(10, target.w), target.z * pow(10, target.w) },
{ _lineColorEnd.r, _lineColorEnd.g, _lineColorEnd.b, _lineColorEnd.a }
}
};
glBindBuffer(GL_ARRAY_BUFFER, _vbo);
glBufferSubData(
GL_ARRAY_BUFFER,
0,
2 * sizeof(VBOData),
vboData
);
//glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(psc) * 2, _positions);
if (ImageSequencer::ref().isReady()) {
_imageSequenceTime = ImageSequencer::ref().instrumentActiveTime(_instrumentName);
_drawLine = _imageSequenceTime != -1.f;
}
}
} // namespace openspace
<commit_msg>OSX compile fix<commit_after>/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2017 *
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy of this *
* software and associated documentation files (the "Software"), to deal in the Software *
* without restriction, including without limitation the rights to use, copy, modify, *
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to *
* permit persons to whom the Software is furnished to do so, subject to the following *
* conditions: *
* *
* The above copyright notice and this permission notice shall be included in all copies *
* or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A *
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF *
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE *
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
****************************************************************************************/
#include <modules/newhorizons/rendering/renderablecrawlingline.h>
#include <openspace/documentation/documentation.h>
#include <openspace/documentation/verifier.h>
#include <openspace/engine/openspaceengine.h>
#include <openspace/rendering/renderengine.h>
#include <openspace/util/spicemanager.h>
#include <modules/newhorizons/util/imagesequencer.h>
namespace {
const char* KeySource = "Source";
const char* KeyTarget = "Target";
const char* KeyInstrument = "Instrument";
const char* KeyColor = "Color";
const char* KeyColorStart = "Start";
const char* KeyColorEnd = "End";
struct VBOData {
float position[3];
float color[4];
};
} // namespace
namespace openspace {
documentation::Documentation RenderableCrawlingLine::Documentation() {
using namespace documentation;
return {
"RenderableCrawlingLine",
"newhorizons_renderable_crawlingline",
{
{
KeySource,
new StringVerifier,
"Denotes the SPICE name of the source of the renderable crawling line, "
"for example, the space craft",
Optional::No
},
{
KeyTarget,
new StringVerifier,
"Denotes the SPICE name of the target of the crawling line",
Optional::Yes
},
{
KeyInstrument,
new StringVerifier,
"Denotes the SPICE name of the instrument that is used to render the "
"crawling line",
Optional::No
},
{
KeyColor,
new TableVerifier({
{
{
KeyColorStart,
new DoubleVector4Verifier,
"The color at the start of the line",
Optional::No
},
{
KeyColorEnd,
new DoubleVector4Verifier,
"The color at the end of the line",
Optional::No
}
},
Exhaustive::Yes
}),
"Specifies the colors that are used for the crawling line. One value "
"determines the starting color of the line, the second value is the "
"color at the end of the line.",
Optional::No
}
}
};
}
RenderableCrawlingLine::RenderableCrawlingLine(const ghoul::Dictionary& dictionary)
: Renderable(dictionary)
, _program(nullptr)
, _imageSequenceTime(-1.f)
, _vao(0)
, _vbo(0)
, _frameCounter(0)
, _drawLine(false)
{
documentation::testSpecificationAndThrow(
Documentation(),
dictionary,
"RenderableCrawlingLine"
);
_source = dictionary.value<std::string>(KeySource);
_target = dictionary.value<std::string>(KeyTarget);
_instrumentName = dictionary.value<std::string>(KeyInstrument);
_lineColorBegin = dictionary.value<glm::vec4>(
std::string(KeyColor) + "." + KeyColorStart
);
_lineColorEnd = dictionary.value<glm::vec4>(
std::string(KeyColor) + "." + KeyColorEnd
);
}
bool RenderableCrawlingLine::isReady() const {
return (_program != nullptr);
}
bool RenderableCrawlingLine::initialize() {
RenderEngine& renderEngine = OsEng.renderEngine();
_program = renderEngine.buildRenderProgram(
"RenderableCrawlingLine",
"${MODULE_NEWHORIZONS}/shaders/crawlingline_vs.glsl",
"${MODULE_NEWHORIZONS}/shaders/crawlingline_fs.glsl"
);
glGenVertexArrays(1, &_vao);
glGenBuffers(1, &_vbo);
glBindVertexArray(_vao);
glBindBuffer(GL_ARRAY_BUFFER, _vbo);
glBufferData(GL_ARRAY_BUFFER, 2 * sizeof(VBOData), NULL, GL_DYNAMIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, sizeof(VBOData), (void*)0);
glEnableVertexAttribArray(1);
glVertexAttribPointer(
1,
4,
GL_FLOAT,
GL_FALSE,
sizeof(VBOData),
reinterpret_cast<void*>(offsetof(VBOData, color))
);
glBindVertexArray(0);
return true;
}
bool RenderableCrawlingLine::deinitialize(){
glDeleteVertexArrays(1, &_vao);
_vao = 0;
glDeleteBuffers(1, &_vbo);
_vbo = 0;
RenderEngine& renderEngine = OsEng.renderEngine();
if (_program) {
renderEngine.removeRenderProgram(_program);
_program = nullptr;
}
return true;
}
void RenderableCrawlingLine::render(const RenderData& data) {
if (!_drawLine) {
return;
}
_program->activate();
_frameCounter++;
glm::dmat4 modelTransform =
glm::translate(glm::dmat4(1.0), data.modelTransform.translation) * // Translation
glm::dmat4(data.modelTransform.rotation) * // Spice rotation
glm::scale(glm::dmat4(1.0), glm::dvec3(data.modelTransform.scale));
glm::dmat4 modelViewProjectionTransform =
data.camera.projectionMatrix() *
glm::mat4(data.camera.combinedViewMatrix() *
modelTransform
)
;
//glm::dmat4 modelViewTransform = data.camera.combinedViewMatrix() * modelTransform;
// setup the data to the shader
//_program->setUniform("modelViewTransform", glm::mat4(modelViewTransform));
//_program->setUniform("projectionTransform", data.camera.projectionMatrix());
_program->setUniform("modelViewProjection", modelViewProjectionTransform);
int frame = _frameCounter % 60;
float fadingFactor = static_cast<float>(sin((frame * 3.14159) / 60));
float alpha = 0.6f + fadingFactor*0.4f;
glLineWidth(2.f);
_program->setUniform("_alpha", alpha);
//_program->setUniform("color", _lineColor);
//setPscUniforms(*_program.get(), data.camera, data.position);
glBindVertexArray(_vao);
glDrawArrays(GL_LINES, 0, 2);
glBindVertexArray(0);
_program->deactivate();
}
void RenderableCrawlingLine::update(const UpdateData& data) {
if (_program->isDirty()) {
_program->rebuildFromFile();
}
glm::dmat3 transformMatrix = SpiceManager::ref().positionTransformMatrix(
_source,
//"ECLIPJ2000",
"GALACTIC",
data.time
);
glm::dmat3 tm = SpiceManager::ref().frameTransformationMatrix(_instrumentName, "ECLIPJ2000", data.time);
//_positions[SourcePosition] = { 0.f, 0.f, 0.f, 0.f };
glm::dvec3 boresight;
//try {
SpiceManager::FieldOfViewResult res =
SpiceManager::ref().fieldOfView(_source);
boresight = res.boresightVector;
//}
//catch (const SpiceManager::SpiceException& e) {
//LERROR(e.what());
//}
glm::vec4 target(boresight[0], boresight[1], boresight[2], 12);
//target = glm::dmat4(tm) * target;
//_positions[TargetPosition] = target;
//_positions[TargetPosition] = {
// target.x * pow(10, target.w),
// target.y * pow(10, target.w),
// target.z * pow(10, target.w),
// 0
//};
VBOData vboData[2] = {
{
{ 0.f, 0.f, 0.f },
_lineColorBegin.r, _lineColorBegin.g, _lineColorBegin.b, _lineColorBegin.a
},
{
{ target.x * powf(10, target.w), target.y * powf(10, target.w), target.z * powf(10, target.w) },
{ _lineColorEnd.r, _lineColorEnd.g, _lineColorEnd.b, _lineColorEnd.a }
}
};
glBindBuffer(GL_ARRAY_BUFFER, _vbo);
glBufferSubData(
GL_ARRAY_BUFFER,
0,
2 * sizeof(VBOData),
vboData
);
//glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(psc) * 2, _positions);
if (ImageSequencer::ref().isReady()) {
_imageSequenceTime = ImageSequencer::ref().instrumentActiveTime(_instrumentName);
_drawLine = _imageSequenceTime != -1.f;
}
}
} // namespace openspace
<|endoftext|>
|
<commit_before>#include "xchainer/numeric.h"
#include <cmath>
#include <memory>
#include <string>
#include <vector>
#include <gtest/gtest.h>
#include <nonstd/optional.hpp>
#include "xchainer/array.h"
#include "xchainer/context.h"
#include "xchainer/error.h"
#include "xchainer/scalar.h"
#include "xchainer/shape.h"
#include "xchainer/testing/array.h"
#include "xchainer/testing/device_session.h"
namespace xchainer {
class NumericTest : public ::testing::TestWithParam<std::string> {
protected:
void SetUp() override { device_session_.emplace(DeviceId{GetParam(), 0}); }
void TearDown() override { device_session_.reset(); }
public:
template <typename T>
void CheckAllClose(
const Shape& shape,
std::initializer_list<T> adata,
std::initializer_list<T> bdata,
double rtol,
double atol,
bool equal_nan = false) {
Array a = testing::BuildArray<T>(shape, adata);
Array b = testing::BuildArray<T>(shape, bdata);
EXPECT_TRUE(AllClose(a, b, rtol, atol, equal_nan));
}
template <typename T>
void CheckNotAllClose(
const Shape& shape,
std::initializer_list<T> adata,
std::initializer_list<T> bdata,
double rtol,
double atol,
bool equal_nan = false) {
Array a = testing::BuildArray<T>(shape, adata);
Array b = testing::BuildArray<T>(shape, bdata);
EXPECT_FALSE(AllClose(a, b, rtol, atol, equal_nan));
}
template <typename T, typename U>
void CheckAllCloseThrow(
const Shape& shape,
std::initializer_list<T> adata,
std::initializer_list<U> bdata,
double rtol,
double atol,
bool equal_nan = false) {
Array a = testing::BuildArray<T>(shape, adata);
Array b = testing::BuildArray<U>(shape, bdata);
EXPECT_THROW(AllClose(a, b, rtol, atol, equal_nan), DtypeError);
}
private:
nonstd::optional<testing::DeviceSession> device_session_;
};
TEST_P(NumericTest, AllClose) {
CheckAllClose<bool>({2}, {true, false}, {true, false}, 0., 0.);
CheckAllClose<bool>({2}, {true, false}, {false, true}, 0., 1.);
CheckAllClose<bool>({2}, {false, false}, {true, true}, 1., 0.);
CheckAllClose<bool>({2}, {false, true}, {true, false}, 1., 1.);
CheckNotAllClose<bool>({2}, {true, false}, {false, true}, 0., 0.);
CheckNotAllClose<bool>({2}, {true, false}, {false, true}, 1., 0.);
CheckAllClose<int8_t>({2}, {1, 2}, {1, 2}, 0., 0.);
CheckAllClose<int8_t>({2}, {1, 2}, {3, 4}, 0., 2.);
CheckAllClose<int8_t>({2}, {1, 2}, {3, 4}, 2., 0.);
CheckAllClose<int8_t>({2}, {1, 2}, {3, 4}, 1., 1.);
CheckNotAllClose<int8_t>({2}, {1, 2}, {3, 4}, 0., 0.);
CheckNotAllClose<int8_t>({2}, {1, 2}, {3, 4}, 0., 1.);
CheckNotAllClose<int8_t>({2}, {3, 4}, {1, 2}, 1., 0.);
CheckAllClose<int16_t>({2}, {1, 2}, {1, 2}, 0., 0.);
CheckAllClose<int16_t>({2}, {1, 2}, {3, 4}, 0., 2.);
CheckAllClose<int16_t>({2}, {1, 2}, {3, 4}, 2., 0.);
CheckAllClose<int16_t>({2}, {1, 2}, {3, 4}, 1., 1.);
CheckNotAllClose<int16_t>({2}, {1, 2}, {3, 4}, 0., 0.);
CheckNotAllClose<int16_t>({2}, {1, 2}, {3, 4}, 0., 1.);
CheckNotAllClose<int16_t>({2}, {3, 4}, {1, 2}, 1., 0.);
CheckAllClose<int32_t>({2}, {1, 2}, {1, 2}, 0., 0.);
CheckAllClose<int32_t>({2}, {-1, 0}, {1, 2}, 0., 2.);
CheckAllClose<int32_t>({2}, {-1, 0}, {1, 2}, 2., 0.);
CheckAllClose<int32_t>({2}, {-1, 0}, {1, 2}, 1., 1.);
CheckNotAllClose<int32_t>({2}, {-1, 0}, {1, 2}, 0., 0.);
CheckNotAllClose<int32_t>({2}, {-1, 0}, {1, 2}, 0., 1.);
CheckNotAllClose<int32_t>({2}, {-1, 0}, {1, 2}, 1., 0.);
CheckAllClose<int64_t>({2}, {1, 2}, {1, 2}, 0., 0.);
CheckAllClose<int64_t>({2}, {-1, 0}, {1, 2}, 0., 2.);
CheckAllClose<int64_t>({2}, {-1, 0}, {1, 2}, 2., 0.);
CheckAllClose<int64_t>({2}, {-1, 0}, {1, 2}, 1., 1.);
CheckNotAllClose<int64_t>({2}, {-1, 0}, {1, 2}, 0., 0.);
CheckNotAllClose<int64_t>({2}, {-1, 0}, {1, 2}, 0., 1.);
CheckNotAllClose<int64_t>({2}, {-1, 0}, {1, 2}, 1., 0.);
CheckAllClose<uint8_t>({2}, {1, 2}, {1, 2}, 0., 0.);
CheckAllClose<uint8_t>({2}, {1, 2}, {3, 4}, 0., 2.);
CheckAllClose<uint8_t>({2}, {1, 2}, {3, 4}, 2., 0.);
CheckAllClose<uint8_t>({2}, {1, 2}, {3, 4}, 1., 1.);
CheckNotAllClose<uint8_t>({2}, {1, 2}, {3, 4}, 0., 0.);
CheckNotAllClose<uint8_t>({2}, {1, 2}, {3, 4}, 0., 1.);
CheckNotAllClose<uint8_t>({2}, {3, 4}, {1, 2}, 1., 0.);
{
float eps = 1e-5f;
CheckAllClose<float>({2}, {1.f, 2.f}, {1.f, 2.f}, 0., 0. + eps);
CheckAllClose<float>({2}, {1.f, 2.f}, {1.2f, 2.f}, 0., .2 + eps);
CheckAllClose<float>({2}, {1.f, 2.f}, {1.2f, 2.5f}, .3, 0. + eps);
CheckAllClose<float>({2}, {1.f, 2.f}, {1.2f, 2.2f}, .2, .2 + eps);
CheckNotAllClose<float>({2}, {1.f, 2.f}, {1.1f, 2.2f}, 0., 0. + eps);
CheckNotAllClose<float>({2}, {1.f, 2.f}, {1.1f, 2.2f}, 0., 1e-2 + eps);
CheckNotAllClose<float>({2}, {1.f, 2.f}, {1.1f, 2.2f}, 1e-2, 0. + eps);
}
{
double eps = 1e-8;
CheckAllClose<double>({2}, {1., 2.}, {1., 2.}, 0., 0. + eps);
CheckAllClose<double>({2}, {1., 2.}, {1.2, 2.}, 0., .2 + eps);
CheckAllClose<double>({2}, {1., 2.}, {1.2, 2.5}, .3, 0. + eps);
CheckAllClose<double>({2}, {1., 2.}, {1.2, 2.2}, .2, .2 + eps);
CheckNotAllClose<double>({2}, {1., 2.}, {1.1, 2.2}, 0., 0. + eps);
CheckNotAllClose<double>({2}, {1., 2.}, {1.1, 2.2}, 0., 1e-2 + eps);
CheckNotAllClose<double>({2}, {1., 2.}, {1.1, 2.2}, 1e-2, 0. + eps);
}
}
TEST_P(NumericTest, AllCloseMixed) {
CheckAllCloseThrow<bool, int8_t>({3}, {true, false, true}, {1, 2, 3}, 2., 1.);
CheckAllCloseThrow<int16_t, int8_t>({3}, {1, 2, 3}, {4, 5, 6}, 8., 7.);
CheckAllCloseThrow<int8_t, int32_t>({3}, {1, 2, 3}, {4, 5, 6}, 8., 7.);
CheckAllCloseThrow<int64_t, int8_t>({3}, {1, 2, 3}, {1, 2, 3}, 2., 1.);
CheckAllCloseThrow<int32_t, float>({3}, {1, 2, 3}, {1.f, 2.f, 3.f}, 2., 1.);
CheckAllCloseThrow<double, int32_t>({3}, {1., 2., 3.}, {1, 2, 3}, 2., 1.);
}
// Allowing NaN values and considering arrays close if corresponding elements are both or neither NaN.
TEST_P(NumericTest, AllCloseEqualNan) {
double eps = 1e-5;
CheckAllClose<double>({3}, {1., std::nan(""), 3.}, {1., std::nan(""), 3.}, 0., 0. + eps, true);
CheckAllClose<double>({3}, {1., 2., 3.}, {1., 2., 3.}, 0., 0. + eps, true);
CheckNotAllClose<double>({3}, {1., std::nan(""), 3.}, {1., 2., std::nan("")}, 0., 0. + eps, true);
CheckNotAllClose<double>({3}, {1., 2., 3.}, {1., std::nan(""), 3.}, 0., 0. + eps, true);
}
// Disallowing NaN values and do not consider arrays equals if any NaN is found.
TEST_P(NumericTest, AllCloseNotEqualNan) {
double eps = 1e-5;
CheckNotAllClose<double>({3}, {1., std::nan(""), 3.}, {1., 2., 3.}, 0., 0. + eps, false);
CheckNotAllClose<double>({3}, {1., std::nan(""), 2.}, {1., std::nan(""), 2.}, 0., 0. + eps, false);
}
INSTANTIATE_TEST_CASE_P(
ForEachBackend,
NumericTest,
::testing::Values(
#ifdef XCHAINER_ENABLE_CUDA
std::string{"cuda"},
#endif // XCHAINER_ENABLE_CUDA
std::string{"native"}));
} // namespace xchainer
<commit_msg>Remove redundant comments<commit_after>#include "xchainer/numeric.h"
#include <cmath>
#include <memory>
#include <string>
#include <vector>
#include <gtest/gtest.h>
#include <nonstd/optional.hpp>
#include "xchainer/array.h"
#include "xchainer/context.h"
#include "xchainer/error.h"
#include "xchainer/scalar.h"
#include "xchainer/shape.h"
#include "xchainer/testing/array.h"
#include "xchainer/testing/device_session.h"
namespace xchainer {
class NumericTest : public ::testing::TestWithParam<std::string> {
protected:
void SetUp() override { device_session_.emplace(DeviceId{GetParam(), 0}); }
void TearDown() override { device_session_.reset(); }
public:
template <typename T>
void CheckAllClose(
const Shape& shape,
std::initializer_list<T> adata,
std::initializer_list<T> bdata,
double rtol,
double atol,
bool equal_nan = false) {
Array a = testing::BuildArray<T>(shape, adata);
Array b = testing::BuildArray<T>(shape, bdata);
EXPECT_TRUE(AllClose(a, b, rtol, atol, equal_nan));
}
template <typename T>
void CheckNotAllClose(
const Shape& shape,
std::initializer_list<T> adata,
std::initializer_list<T> bdata,
double rtol,
double atol,
bool equal_nan = false) {
Array a = testing::BuildArray<T>(shape, adata);
Array b = testing::BuildArray<T>(shape, bdata);
EXPECT_FALSE(AllClose(a, b, rtol, atol, equal_nan));
}
template <typename T, typename U>
void CheckAllCloseThrow(
const Shape& shape,
std::initializer_list<T> adata,
std::initializer_list<U> bdata,
double rtol,
double atol,
bool equal_nan = false) {
Array a = testing::BuildArray<T>(shape, adata);
Array b = testing::BuildArray<U>(shape, bdata);
EXPECT_THROW(AllClose(a, b, rtol, atol, equal_nan), DtypeError);
}
private:
nonstd::optional<testing::DeviceSession> device_session_;
};
TEST_P(NumericTest, AllClose) {
CheckAllClose<bool>({2}, {true, false}, {true, false}, 0., 0.);
CheckAllClose<bool>({2}, {true, false}, {false, true}, 0., 1.);
CheckAllClose<bool>({2}, {false, false}, {true, true}, 1., 0.);
CheckAllClose<bool>({2}, {false, true}, {true, false}, 1., 1.);
CheckNotAllClose<bool>({2}, {true, false}, {false, true}, 0., 0.);
CheckNotAllClose<bool>({2}, {true, false}, {false, true}, 1., 0.);
CheckAllClose<int8_t>({2}, {1, 2}, {1, 2}, 0., 0.);
CheckAllClose<int8_t>({2}, {1, 2}, {3, 4}, 0., 2.);
CheckAllClose<int8_t>({2}, {1, 2}, {3, 4}, 2., 0.);
CheckAllClose<int8_t>({2}, {1, 2}, {3, 4}, 1., 1.);
CheckNotAllClose<int8_t>({2}, {1, 2}, {3, 4}, 0., 0.);
CheckNotAllClose<int8_t>({2}, {1, 2}, {3, 4}, 0., 1.);
CheckNotAllClose<int8_t>({2}, {3, 4}, {1, 2}, 1., 0.);
CheckAllClose<int16_t>({2}, {1, 2}, {1, 2}, 0., 0.);
CheckAllClose<int16_t>({2}, {1, 2}, {3, 4}, 0., 2.);
CheckAllClose<int16_t>({2}, {1, 2}, {3, 4}, 2., 0.);
CheckAllClose<int16_t>({2}, {1, 2}, {3, 4}, 1., 1.);
CheckNotAllClose<int16_t>({2}, {1, 2}, {3, 4}, 0., 0.);
CheckNotAllClose<int16_t>({2}, {1, 2}, {3, 4}, 0., 1.);
CheckNotAllClose<int16_t>({2}, {3, 4}, {1, 2}, 1., 0.);
CheckAllClose<int32_t>({2}, {1, 2}, {1, 2}, 0., 0.);
CheckAllClose<int32_t>({2}, {-1, 0}, {1, 2}, 0., 2.);
CheckAllClose<int32_t>({2}, {-1, 0}, {1, 2}, 2., 0.);
CheckAllClose<int32_t>({2}, {-1, 0}, {1, 2}, 1., 1.);
CheckNotAllClose<int32_t>({2}, {-1, 0}, {1, 2}, 0., 0.);
CheckNotAllClose<int32_t>({2}, {-1, 0}, {1, 2}, 0., 1.);
CheckNotAllClose<int32_t>({2}, {-1, 0}, {1, 2}, 1., 0.);
CheckAllClose<int64_t>({2}, {1, 2}, {1, 2}, 0., 0.);
CheckAllClose<int64_t>({2}, {-1, 0}, {1, 2}, 0., 2.);
CheckAllClose<int64_t>({2}, {-1, 0}, {1, 2}, 2., 0.);
CheckAllClose<int64_t>({2}, {-1, 0}, {1, 2}, 1., 1.);
CheckNotAllClose<int64_t>({2}, {-1, 0}, {1, 2}, 0., 0.);
CheckNotAllClose<int64_t>({2}, {-1, 0}, {1, 2}, 0., 1.);
CheckNotAllClose<int64_t>({2}, {-1, 0}, {1, 2}, 1., 0.);
CheckAllClose<uint8_t>({2}, {1, 2}, {1, 2}, 0., 0.);
CheckAllClose<uint8_t>({2}, {1, 2}, {3, 4}, 0., 2.);
CheckAllClose<uint8_t>({2}, {1, 2}, {3, 4}, 2., 0.);
CheckAllClose<uint8_t>({2}, {1, 2}, {3, 4}, 1., 1.);
CheckNotAllClose<uint8_t>({2}, {1, 2}, {3, 4}, 0., 0.);
CheckNotAllClose<uint8_t>({2}, {1, 2}, {3, 4}, 0., 1.);
CheckNotAllClose<uint8_t>({2}, {3, 4}, {1, 2}, 1., 0.);
{
float eps = 1e-5f;
CheckAllClose<float>({2}, {1.f, 2.f}, {1.f, 2.f}, 0., 0. + eps);
CheckAllClose<float>({2}, {1.f, 2.f}, {1.2f, 2.f}, 0., .2 + eps);
CheckAllClose<float>({2}, {1.f, 2.f}, {1.2f, 2.5f}, .3, 0. + eps);
CheckAllClose<float>({2}, {1.f, 2.f}, {1.2f, 2.2f}, .2, .2 + eps);
CheckNotAllClose<float>({2}, {1.f, 2.f}, {1.1f, 2.2f}, 0., 0. + eps);
CheckNotAllClose<float>({2}, {1.f, 2.f}, {1.1f, 2.2f}, 0., 1e-2 + eps);
CheckNotAllClose<float>({2}, {1.f, 2.f}, {1.1f, 2.2f}, 1e-2, 0. + eps);
}
{
double eps = 1e-8;
CheckAllClose<double>({2}, {1., 2.}, {1., 2.}, 0., 0. + eps);
CheckAllClose<double>({2}, {1., 2.}, {1.2, 2.}, 0., .2 + eps);
CheckAllClose<double>({2}, {1., 2.}, {1.2, 2.5}, .3, 0. + eps);
CheckAllClose<double>({2}, {1., 2.}, {1.2, 2.2}, .2, .2 + eps);
CheckNotAllClose<double>({2}, {1., 2.}, {1.1, 2.2}, 0., 0. + eps);
CheckNotAllClose<double>({2}, {1., 2.}, {1.1, 2.2}, 0., 1e-2 + eps);
CheckNotAllClose<double>({2}, {1., 2.}, {1.1, 2.2}, 1e-2, 0. + eps);
}
}
TEST_P(NumericTest, AllCloseMixed) {
CheckAllCloseThrow<bool, int8_t>({3}, {true, false, true}, {1, 2, 3}, 2., 1.);
CheckAllCloseThrow<int16_t, int8_t>({3}, {1, 2, 3}, {4, 5, 6}, 8., 7.);
CheckAllCloseThrow<int8_t, int32_t>({3}, {1, 2, 3}, {4, 5, 6}, 8., 7.);
CheckAllCloseThrow<int64_t, int8_t>({3}, {1, 2, 3}, {1, 2, 3}, 2., 1.);
CheckAllCloseThrow<int32_t, float>({3}, {1, 2, 3}, {1.f, 2.f, 3.f}, 2., 1.);
CheckAllCloseThrow<double, int32_t>({3}, {1., 2., 3.}, {1, 2, 3}, 2., 1.);
}
TEST_P(NumericTest, AllCloseEqualNan) {
double eps = 1e-5;
CheckAllClose<double>({3}, {1., std::nan(""), 3.}, {1., std::nan(""), 3.}, 0., 0. + eps, true);
CheckAllClose<double>({3}, {1., 2., 3.}, {1., 2., 3.}, 0., 0. + eps, true);
CheckNotAllClose<double>({3}, {1., std::nan(""), 3.}, {1., 2., std::nan("")}, 0., 0. + eps, true);
CheckNotAllClose<double>({3}, {1., 2., 3.}, {1., std::nan(""), 3.}, 0., 0. + eps, true);
}
TEST_P(NumericTest, AllCloseNotEqualNan) {
double eps = 1e-5;
CheckNotAllClose<double>({3}, {1., std::nan(""), 3.}, {1., 2., 3.}, 0., 0. + eps, false);
CheckNotAllClose<double>({3}, {1., std::nan(""), 2.}, {1., std::nan(""), 2.}, 0., 0. + eps, false);
}
INSTANTIATE_TEST_CASE_P(
ForEachBackend,
NumericTest,
::testing::Values(
#ifdef XCHAINER_ENABLE_CUDA
std::string{"cuda"},
#endif // XCHAINER_ENABLE_CUDA
std::string{"native"}));
} // namespace xchainer
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: unoDirectSql.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2005-09-08 16:52:50 $
*
* 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 DBAUI_UNODIRECTSQL_HXX
#define DBAUI_UNODIRECTSQL_HXX
#ifndef _SVT_GENERICUNODIALOG_HXX_
#include <svtools/genericunodialog.hxx>
#endif
#ifndef _DBAUI_MODULE_DBU_HXX_
#include "moduledbu.hxx"
#endif
#ifndef _DBASHARED_APITOOLS_HXX_
#include "apitools.hxx"
#endif
#ifndef _COM_SUN_STAR_SDB_XSQLQUERYCOMPOSER_HPP_
#include <com/sun/star/sdb/XSQLQueryComposer.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XROWSET_HPP_
#include <com/sun/star/sdbc/XRowSet.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XCONNECTION_HPP_
#include <com/sun/star/sdbc/XConnection.hpp>
#endif
//.........................................................................
namespace dbaui
{
//.........................................................................
//=====================================================================
//= ODirectSQLDialog
//=====================================================================
class ODirectSQLDialog;
typedef ::svt::OGenericUnoDialog ODirectSQLDialog_BASE;
typedef ::comphelper::OPropertyArrayUsageHelper< ODirectSQLDialog > ODirectSQLDialog_PBASE;
class ODirectSQLDialog
:public ODirectSQLDialog_BASE
,public ODirectSQLDialog_PBASE
,public OModuleClient
{
::rtl::OUString m_sInitialSelection;
::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection > m_xActiveConnection;
protected:
ODirectSQLDialog(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB);
virtual ~ODirectSQLDialog();
public:
DECLARE_IMPLEMENTATION_ID( );
DECLARE_SERVICE_INFO_STATIC( );
DECLARE_PROPERTYCONTAINER_DEFAULTS( );
protected:
// OGenericUnoDialog overridables
virtual Dialog* createDialog(Window* _pParent);
virtual void implInitialize(const com::sun::star::uno::Any& _rValue);
};
//.........................................................................
} // namespace dbaui
//.........................................................................
#endif // DBAUI_UNODIRECTSQL_HXX
<commit_msg>INTEGRATION: CWS oj14 (1.4.8); FILE MERGED 2006/04/25 13:03:21 oj 1.4.8.3: new include 2006/03/20 07:49:02 oj 1.4.8.2: use of module client helper 2006/01/03 07:49:30 oj 1.4.8.1: changed module client<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: unoDirectSql.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: rt $ $Date: 2007-07-06 08:45:52 $
*
* 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 DBAUI_UNODIRECTSQL_HXX
#define DBAUI_UNODIRECTSQL_HXX
#ifndef _SVT_GENERICUNODIALOG_HXX_
#include <svtools/genericunodialog.hxx>
#endif
#ifndef _DBASHARED_APITOOLS_HXX_
#include "apitools.hxx"
#endif
#ifndef _COM_SUN_STAR_SDB_XSQLQUERYCOMPOSER_HPP_
#include <com/sun/star/sdb/XSQLQueryComposer.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XROWSET_HPP_
#include <com/sun/star/sdbc/XRowSet.hpp>
#endif
#ifndef _DBAUI_MODULE_DBU_HXX_
#include "moduledbu.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBC_XCONNECTION_HPP_
#include <com/sun/star/sdbc/XConnection.hpp>
#endif
//.........................................................................
namespace dbaui
{
//.........................................................................
//=====================================================================
//= ODirectSQLDialog
//=====================================================================
class ODirectSQLDialog;
typedef ::svt::OGenericUnoDialog ODirectSQLDialog_BASE;
typedef ::comphelper::OPropertyArrayUsageHelper< ODirectSQLDialog > ODirectSQLDialog_PBASE;
class ODirectSQLDialog
:public ODirectSQLDialog_BASE
,public ODirectSQLDialog_PBASE
{
OModuleClient m_aModuleClient;
::rtl::OUString m_sInitialSelection;
::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection > m_xActiveConnection;
protected:
ODirectSQLDialog(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB);
virtual ~ODirectSQLDialog();
public:
DECLARE_IMPLEMENTATION_ID( );
DECLARE_SERVICE_INFO_STATIC( );
DECLARE_PROPERTYCONTAINER_DEFAULTS( );
protected:
// OGenericUnoDialog overridables
virtual Dialog* createDialog(Window* _pParent);
virtual void implInitialize(const com::sun::star::uno::Any& _rValue);
};
//.........................................................................
} // namespace dbaui
//.........................................................................
#endif // DBAUI_UNODIRECTSQL_HXX
<|endoftext|>
|
<commit_before>#include "augs/window_framework/platform_utils.h"
#include "augs/string/string_templates.h"
#include "augs/filesystem/file.h"
#include "augs/window_framework/shell.h"
#include "augs/window_framework/exec.h"
namespace augs {
bool is_character_newline(const unsigned i) {
return (i == 0x000A || i == 0x000D);
}
}
#if BUILD_WINDOW_FRAMEWORK
#if PLATFORM_WINDOWS
#include <Windows.h>
#undef min
#undef max
namespace augs {
bool set_display(const vec2i v, const int bpp) {
static DEVMODE screen;
ZeroMemory(&screen, sizeof(screen));
screen.dmSize = sizeof(screen);
screen.dmPelsWidth = v.x;
screen.dmPelsHeight = v.y;
screen.dmBitsPerPel = bpp;
screen.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;
return ChangeDisplaySettings(&screen, CDS_FULLSCREEN) == DISP_CHANGE_SUCCESSFUL;
}
xywhi get_display() {
static RECT rc;
GetWindowRect(GetDesktopWindow(), &rc);
return xywhi(rc.left, rc.top, rc.right - rc.left, rc.bottom - rc.top);
}
std::optional<vec2i> find_cursor_pos() {
POINT p;
if (GetCursorPos(&p)) {
return vec2i { p.x, p.y };
}
return std::nullopt;
}
void set_clipboard_data(const std::string&) {
}
std::string get_clipboard_data() {
return {};
}
}
#elif PLATFORM_UNIX
namespace augs {
bool set_display(const vec2i /* v */, const int /* bpp */) {
return true;
}
xywhi get_display() {
return {};
}
std::optional<vec2i> find_cursor_pos() {
return std::nullopt;
}
void set_clipboard_data(const std::string& abc) {
const auto p = augs::path_type("/tmp/augs_clipboard_data.txt");
augs::save_as_text(p, abc);
augs::shell("xclip -selection CLIPBOARD -in " + p.string());
}
std::string get_clipboard_data() {
return exec("xclip -selection CLIPBOARD -out");
}
}
#else
#error "Unsupported platform!"
#endif
#else
namespace augs {
bool set_display(const vec2i, const int) {
return true;
}
xywhi get_display() {
return {};
}
std::optional<vec2i> find_cursor_pos() {
return std::nullopt;
}
void set_clipboard_data(const std::string&) {
}
std::string get_clipboard_data() {
return {};
}
}
#endif
<commit_msg>get_display draft<commit_after>#include "augs/window_framework/platform_utils.h"
#include "augs/string/string_templates.h"
#include "augs/filesystem/file.h"
#include "augs/window_framework/shell.h"
#include "augs/window_framework/exec.h"
namespace augs {
bool is_character_newline(const unsigned i) {
return (i == 0x000A || i == 0x000D);
}
}
#if BUILD_WINDOW_FRAMEWORK
#if PLATFORM_WINDOWS
#include <Windows.h>
#undef min
#undef max
namespace augs {
bool set_display(const vec2i v, const int bpp) {
static DEVMODE screen;
ZeroMemory(&screen, sizeof(screen));
screen.dmSize = sizeof(screen);
screen.dmPelsWidth = v.x;
screen.dmPelsHeight = v.y;
screen.dmBitsPerPel = bpp;
screen.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;
return ChangeDisplaySettings(&screen, CDS_FULLSCREEN) == DISP_CHANGE_SUCCESSFUL;
}
xywhi get_display() {
static RECT rc;
GetWindowRect(GetDesktopWindow(), &rc);
return xywhi(rc.left, rc.top, rc.right - rc.left, rc.bottom - rc.top);
}
std::optional<vec2i> find_cursor_pos() {
POINT p;
if (GetCursorPos(&p)) {
return vec2i { p.x, p.y };
}
return std::nullopt;
}
void set_clipboard_data(const std::string&) {
}
std::string get_clipboard_data() {
return {};
}
}
#elif PLATFORM_UNIX
#if TODO
#include <X11/Xlib.h>
#endif
namespace augs {
bool set_display(const vec2i /* v */, const int /* bpp */) {
return true;
}
xywhi get_display() {
#if TODO
if (Display* d = XOpenDisplay(NULL)) {
if (Screen* s = DefaultScreenOfDisplay(d)) {
return { 0, 0, s->width, s->height };
}
}
#endif
return {};
}
std::optional<vec2i> find_cursor_pos() {
return std::nullopt;
}
void set_clipboard_data(const std::string& abc) {
const auto p = augs::path_type("/tmp/augs_clipboard_data.txt");
augs::save_as_text(p, abc);
augs::shell("xclip -selection CLIPBOARD -in " + p.string());
}
std::string get_clipboard_data() {
return exec("xclip -selection CLIPBOARD -out");
}
}
#else
#error "Unsupported platform!"
#endif
#else
namespace augs {
bool set_display(const vec2i, const int) {
return true;
}
xywhi get_display() {
return {};
}
std::optional<vec2i> find_cursor_pos() {
return std::nullopt;
}
void set_clipboard_data(const std::string&) {
}
std::string get_clipboard_data() {
return {};
}
}
#endif
<|endoftext|>
|
<commit_before>#include <igvc/SerialPort.h>
#include <igvc_msgs/velocity_pair.h>
#include <std_msgs/Bool.h>
#include <ros/publisher.h>
#include <ros/ros.h>
#include <ros/subscriber.h>
#include <std_msgs/Float64.h>
#include <string>
#include <vector>
#include <igvc/StringUtils.hpp>
#include <iomanip>
#include <sstream>
igvc_msgs::velocity_pair current_motor_command;
double battery_avg = 0;
double battery_avg_num = 100;
std::list<double> battery_vals;
bool enabled = false;
int precision;
void cmdCallback(const igvc_msgs::velocity_pair::ConstPtr& msg)
{
current_motor_command = *msg;
}
std::string toBoundedString(double input) {
std::stringstream stream;
stream << std::fixed << std::setprecision(precision) << input;
return stream.str();
}
int main(int argc, char** argv)
{
ros::init(argc, argv, "motor_controller");
ros::NodeHandle nh;
ros::NodeHandle nhp("~");
ros::Subscriber cmd_sub = nh.subscribe("/motors", 1, cmdCallback);
ros::Publisher enc_pub = nh.advertise<igvc_msgs::velocity_pair>("/encoders", 1000);
ros::Publisher enabled_pub = nh.advertise<std_msgs::Bool>("/robot_enabled", 1);
ros::Publisher battery_pub = nh.advertise<std_msgs::Float64>("/battery", 1);
std::string device_path;
nhp.param(std::string("device"), device_path, std::string("/dev/igvc_motor_board"));
int baud_rate;
nhp.param(std::string("baud_rate"), baud_rate, 9600);
int messages_to_read;
nhp.param(std::string("messages_to_read"), messages_to_read, 3);
nhp.param("precision", precision, 1);
double p_l, p_r, d_l, d_r, i_l, i_r;
nhp.param("p_l", p_l, 3.0);
nhp.param("p_r", p_r, 3.0);
nhp.param("d_l", d_l, 0.0);
nhp.param("d_r", d_r, 0.0);
nhp.param("i_r", i_r, 0.0);
nhp.param("i_l", i_l, 0.0);
SerialPort port(device_path, baud_rate);
if (!port.isOpen())
{
ROS_ERROR_STREAM("Motor Board serial port failed to open.");
return -1;
}
port.flush();
ROS_INFO_STREAM("Motor Board ready.");
ros::Rate rate(10);
std::string p_values = "#P" + toBoundedString(p_l) + "," + toBoundedString(p_r) + "\n";
std::string d_values = "#D" + toBoundedString(d_l) + "," + toBoundedString(d_r) + "\n";
std::string i_values = "#I" + toBoundedString(i_l) + "," + toBoundedString(i_r) + "\n";
bool valid_values_p = false;
bool valid_values_d = false;
bool valid_values_i = false;
while(ros::ok() && (!valid_values_p || !valid_values_d || !valid_values_i)) {
ros::spinOnce();
if(!valid_values_p) {
port.write(p_values);
}
if(!valid_values_d) {
port.write(d_values);
}
if(!valid_values_i) {
port.write(i_values);
}
for(int i = 0; i < 3; i++) {
std::string ret = port.readln();
if(!ret.empty() && ret.at(0) == '#' && ret.at(1) != 'E') {
size_t p_loc = ret.find('P');
size_t d_loc = ret.find('D');
size_t i_loc = ret.find('I');
size_t end = ret.find('\n');
if(p_loc != std::string::npos) {
std::vector<std::string> vals = split(ret.substr(p_loc + 1, end), ',');
ROS_INFO_STREAM("Successfully set p values");
if(vals.size() == 2) {
valid_values_p = true;
valid_values_p = (stod(vals.at(0)) == p_l) && valid_values_p;
valid_values_p = (stod(vals.at(1)) == p_r) && valid_values_p;
}
} else if(d_loc != std::string::npos) {
std::vector<std::string> vals = split(ret.substr(d_loc + 1, end), ',');
ROS_INFO_STREAM("Successfully set d values");
if(vals.size() == 2) {
valid_values_d = true;
valid_values_d = (stod(vals.at(0)) == d_l) && valid_values_d;
valid_values_d = (stod(vals.at(1)) == d_r) && valid_values_d;
}
} else if(i_loc != std::string::npos) {
std::vector<std::string> vals = split(ret.substr(i_loc + 1, end), ',');
ROS_INFO_STREAM("Successfully set i values");
if(vals.size() == 2) {
valid_values_i = true;
valid_values_i = (stod(vals.at(0)) == i_l) && valid_values_i;
valid_values_i = (stod(vals.at(1)) == i_r) && valid_values_i;
}
} else if(ret.at(1) != 'V') {
ROS_ERROR_STREAM("Recieved unknown string while setting PID values " << ret);
}
} else if(ret.empty()) {
ROS_ERROR_STREAM("Empty return from motor board while sending PID values.\t" << ret);
}
}
rate.sleep();
}
ROS_INFO_STREAM("Sucessfully set all PID values");
while (ros::ok() && port.isOpen()) {
ros::spinOnce();
std::string msg = "$" + (enabled ? toBoundedString(current_motor_command.left_velocity) : toBoundedString(0.0)) + "," +
(enabled ? toBoundedString(current_motor_command.right_velocity) : toBoundedString(0.0)) + "\n";
port.write(msg);
std::string ret = port.readln();
size_t dollar = ret.find('$');
size_t pound = ret.find('#');
int count = 0;
while ((dollar != std::string::npos || pound != std::string::npos) && count <= messages_to_read) {
count++;
size_t end = ret.find('\n');
std::vector<std::string> tokens;
if(dollar != std::string::npos) {
tokens = split(ret.substr(dollar + 1, end), ',');
}
if(pound != std::string::npos) {
tokens = split(ret.substr(pound + 2, end), ',');
}
if(tokens.size() <= 0) {
ROS_INFO_STREAM("Invalid number of tokens from motor board");
} else {
if(pound != std::string::npos) {
if(ret.at(1) == 'I') {
// imu message
} else if(ret.at(1) == 'V') {
std_msgs::Float64 battery_msg;
double voltage = atof(tokens.at(0).c_str());
battery_vals.push_back(voltage);
if(battery_vals.size() > battery_avg_num) {
battery_avg -= battery_vals.front() / battery_avg_num;
battery_vals.pop_front();
}
battery_avg += voltage / battery_avg_num;
battery_msg.data = battery_avg;
battery_pub.publish(battery_msg);
if(battery_avg < 24 && battery_vals.size() > battery_avg_num) {
ROS_ERROR_STREAM("Battery voltage dangerously low");
}
std_msgs::Bool enabled_msg;
enabled_msg.data = tokens.at(1) == "1";
enabled = enabled_msg.data;
enabled_pub.publish(enabled_msg);
} else if(ret.at(1) == 'E') {
ROS_ERROR_STREAM(ret);
count--;
}
} else if(dollar != std::string::npos) {
igvc_msgs::velocity_pair enc_msg;
enc_msg.left_velocity = atof(tokens.at(0).c_str());
enc_msg.right_velocity = atof(tokens.at(1).c_str());
enc_msg.duration = atof(tokens.at(2).c_str());
enc_msg.header.stamp = ros::Time::now();
enc_pub.publish(enc_msg);
} else {
ROS_ERROR_STREAM("Unknown message from motor board " << ret);
}
}
ret = port.readln();
dollar = ret.find('$');
pound = ret.find('#');
}
rate.sleep();
}
}
<commit_msg>fixed issue with low battery warning never publishing<commit_after>#include <igvc/SerialPort.h>
#include <igvc_msgs/velocity_pair.h>
#include <std_msgs/Bool.h>
#include <ros/publisher.h>
#include <ros/ros.h>
#include <ros/subscriber.h>
#include <std_msgs/Float64.h>
#include <string>
#include <vector>
#include <igvc/StringUtils.hpp>
#include <iomanip>
#include <sstream>
igvc_msgs::velocity_pair current_motor_command;
double battery_avg = 0;
double battery_avg_num = 100;
std::list<double> battery_vals;
bool enabled = false;
int precision;
void cmdCallback(const igvc_msgs::velocity_pair::ConstPtr& msg)
{
current_motor_command = *msg;
}
std::string toBoundedString(double input) {
std::stringstream stream;
stream << std::fixed << std::setprecision(precision) << input;
return stream.str();
}
int main(int argc, char** argv)
{
ros::init(argc, argv, "motor_controller");
ros::NodeHandle nh;
ros::NodeHandle nhp("~");
ros::Subscriber cmd_sub = nh.subscribe("/motors", 1, cmdCallback);
ros::Publisher enc_pub = nh.advertise<igvc_msgs::velocity_pair>("/encoders", 1000);
ros::Publisher enabled_pub = nh.advertise<std_msgs::Bool>("/robot_enabled", 1);
ros::Publisher battery_pub = nh.advertise<std_msgs::Float64>("/battery", 1);
std::string device_path;
nhp.param(std::string("device"), device_path, std::string("/dev/igvc_motor_board"));
int baud_rate;
nhp.param(std::string("baud_rate"), baud_rate, 9600);
int messages_to_read;
nhp.param(std::string("messages_to_read"), messages_to_read, 3);
nhp.param("precision", precision, 1);
double p_l, p_r, d_l, d_r, i_l, i_r;
nhp.param("p_l", p_l, 3.0);
nhp.param("p_r", p_r, 3.0);
nhp.param("d_l", d_l, 0.0);
nhp.param("d_r", d_r, 0.0);
nhp.param("i_r", i_r, 0.0);
nhp.param("i_l", i_l, 0.0);
SerialPort port(device_path, baud_rate);
if (!port.isOpen())
{
ROS_ERROR_STREAM("Motor Board serial port failed to open.");
return -1;
}
port.flush();
ROS_INFO_STREAM("Motor Board ready.");
ros::Rate rate(10);
std::string p_values = "#P" + toBoundedString(p_l) + "," + toBoundedString(p_r) + "\n";
std::string d_values = "#D" + toBoundedString(d_l) + "," + toBoundedString(d_r) + "\n";
std::string i_values = "#I" + toBoundedString(i_l) + "," + toBoundedString(i_r) + "\n";
bool valid_values_p = false;
bool valid_values_d = false;
bool valid_values_i = false;
while(ros::ok() && (!valid_values_p || !valid_values_d || !valid_values_i)) {
ros::spinOnce();
if(!valid_values_p) {
port.write(p_values);
}
if(!valid_values_d) {
port.write(d_values);
}
if(!valid_values_i) {
port.write(i_values);
}
for(int i = 0; i < 3; i++) {
std::string ret = port.readln();
if(!ret.empty() && ret.at(0) == '#' && ret.at(1) != 'E') {
size_t p_loc = ret.find('P');
size_t d_loc = ret.find('D');
size_t i_loc = ret.find('I');
size_t end = ret.find('\n');
if(p_loc != std::string::npos) {
std::vector<std::string> vals = split(ret.substr(p_loc + 1, end), ',');
ROS_INFO_STREAM("Successfully set p values");
if(vals.size() == 2) {
valid_values_p = true;
valid_values_p = (stod(vals.at(0)) == p_l) && valid_values_p;
valid_values_p = (stod(vals.at(1)) == p_r) && valid_values_p;
}
} else if(d_loc != std::string::npos) {
std::vector<std::string> vals = split(ret.substr(d_loc + 1, end), ',');
ROS_INFO_STREAM("Successfully set d values");
if(vals.size() == 2) {
valid_values_d = true;
valid_values_d = (stod(vals.at(0)) == d_l) && valid_values_d;
valid_values_d = (stod(vals.at(1)) == d_r) && valid_values_d;
}
} else if(i_loc != std::string::npos) {
std::vector<std::string> vals = split(ret.substr(i_loc + 1, end), ',');
ROS_INFO_STREAM("Successfully set i values");
if(vals.size() == 2) {
valid_values_i = true;
valid_values_i = (stod(vals.at(0)) == i_l) && valid_values_i;
valid_values_i = (stod(vals.at(1)) == i_r) && valid_values_i;
}
} else if(ret.at(1) != 'V') {
ROS_ERROR_STREAM("Recieved unknown string while setting PID values " << ret);
}
} else if(ret.empty()) {
ROS_ERROR_STREAM("Empty return from motor board while sending PID values.\t" << ret);
}
}
rate.sleep();
}
ROS_INFO_STREAM("Sucessfully set all PID values");
while (ros::ok() && port.isOpen()) {
ros::spinOnce();
std::string msg = "$" + (enabled ? toBoundedString(current_motor_command.left_velocity) : toBoundedString(0.0)) + "," +
(enabled ? toBoundedString(current_motor_command.right_velocity) : toBoundedString(0.0)) + "\n";
port.write(msg);
std::string ret = port.readln();
size_t dollar = ret.find('$');
size_t pound = ret.find('#');
int count = 0;
while ((dollar != std::string::npos || pound != std::string::npos) && count <= messages_to_read) {
count++;
size_t end = ret.find('\n');
std::vector<std::string> tokens;
if(dollar != std::string::npos) {
tokens = split(ret.substr(dollar + 1, end), ',');
}
if(pound != std::string::npos) {
tokens = split(ret.substr(pound + 2, end), ',');
}
if(tokens.size() <= 0) {
ROS_INFO_STREAM("Invalid number of tokens from motor board");
} else {
if(pound != std::string::npos) {
if(ret.at(1) == 'I') {
// imu message
} else if(ret.at(1) == 'V') {
std_msgs::Float64 battery_msg;
double voltage = atof(tokens.at(0).c_str());
battery_vals.push_back(voltage);
if(battery_vals.size() > battery_avg_num) {
battery_avg -= battery_vals.front() / battery_avg_num;
battery_vals.pop_front();
}
battery_avg += voltage / battery_avg_num;
battery_msg.data = battery_avg;
battery_pub.publish(battery_msg);
if(battery_avg < 23.5 && battery_vals.size() >= battery_avg_num) {
ROS_ERROR_STREAM("Battery voltage dangerously low");
}
std_msgs::Bool enabled_msg;
enabled_msg.data = tokens.at(1) == "1";
enabled = enabled_msg.data;
enabled_pub.publish(enabled_msg);
} else if(ret.at(1) == 'E') {
ROS_ERROR_STREAM(ret);
count--;
}
} else if(dollar != std::string::npos) {
igvc_msgs::velocity_pair enc_msg;
enc_msg.left_velocity = atof(tokens.at(0).c_str());
enc_msg.right_velocity = atof(tokens.at(1).c_str());
enc_msg.duration = atof(tokens.at(2).c_str());
enc_msg.header.stamp = ros::Time::now();
enc_pub.publish(enc_msg);
} else {
ROS_ERROR_STREAM("Unknown message from motor board " << ret);
}
}
ret = port.readln();
dollar = ret.find('$');
pound = ret.find('#');
}
rate.sleep();
}
}
<|endoftext|>
|
<commit_before>// Copyright 2010-2012 RethinkDB, all rights reserved.
#ifndef CLUSTERING_ADMINISTRATION_MAIN_SERVE_HPP_
#define CLUSTERING_ADMINISTRATION_MAIN_SERVE_HPP_
#include <set>
#include <string>
#include "clustering/administration/metadata.hpp"
#include "clustering/administration/persist.hpp"
#include "extproc/spawner.hpp"
#include "arch/address.hpp"
#define MAX_PORT 65536
inline void sanitize_port(int port, const char *name, int port_offset) {
if (port >= MAX_PORT) {
if (port_offset == 0) {
nice_crash("%s has a value (%d) above the maximum allowed port (%d).", name, port, MAX_PORT);
} else {
nice_crash("%s has a value (%d) above the maximum allowed port (%d). Note port_offset is set to %d which may cause this error.", name, port, MAX_PORT, port_offset);
}
}
}
struct service_address_ports_t {
service_address_ports_t() :
port(0),
client_port(0),
http_port(0),
reql_port(0),
port_offset(0) { }
service_address_ports_t(const std::set<ip_address_t> &_local_addresses,
int _port,
int _client_port,
bool _http_admin_is_disabled,
int _http_port,
int _reql_port,
int _port_offset) :
local_addresses(_local_addresses),
port(_port),
client_port(_client_port),
http_admin_is_disabled(_http_admin_is_disabled),
http_port(_http_port),
reql_port(_reql_port),
port_offset(_port_offset)
{
sanitize_port(port, "port", port_offset);
sanitize_port(client_port, "client_port", port_offset);
if (http_admin_is_disabled) sanitize_port(http_port, "http_port", port_offset);
sanitize_port(reql_port, "reql_port", port_offset);
}
std::string get_addresses_string() const;
std::set<ip_address_t> local_addresses;
int port;
int client_port;
bool http_admin_is_disabled;
int http_port;
int reql_port;
int port_offset;
};
/* This has been factored out from `command_line.hpp` because it takes a very
long time to compile. */
bool serve(extproc::spawner_t::info_t *spawner_info,
io_backender_t *io_backender,
const std::string &filepath,
metadata_persistence::persistent_file_t *persistent_file,
const peer_address_set_t &joins,
service_address_ports_t ports,
machine_id_t machine_id,
const cluster_semilattice_metadata_t &semilattice_metadata,
std::string web_assets,
signal_t *stop_cond);
bool serve_proxy(extproc::spawner_t::info_t *spawner_info,
const peer_address_set_t &joins,
service_address_ports_t ports,
machine_id_t machine_id,
const cluster_semilattice_metadata_t &semilattice_metadata,
std::string web_assets,
signal_t *stop_cond);
#endif /* CLUSTERING_ADMINISTRATION_MAIN_SERVE_HPP_ */
<commit_msg>Removed strange, extraneous if.<commit_after>// Copyright 2010-2012 RethinkDB, all rights reserved.
#ifndef CLUSTERING_ADMINISTRATION_MAIN_SERVE_HPP_
#define CLUSTERING_ADMINISTRATION_MAIN_SERVE_HPP_
#include <set>
#include <string>
#include "clustering/administration/metadata.hpp"
#include "clustering/administration/persist.hpp"
#include "extproc/spawner.hpp"
#include "arch/address.hpp"
#define MAX_PORT 65536
inline void sanitize_port(int port, const char *name, int port_offset) {
if (port >= MAX_PORT) {
if (port_offset == 0) {
nice_crash("%s has a value (%d) above the maximum allowed port (%d).", name, port, MAX_PORT);
} else {
nice_crash("%s has a value (%d) above the maximum allowed port (%d). Note port_offset is set to %d which may cause this error.", name, port, MAX_PORT, port_offset);
}
}
}
struct service_address_ports_t {
service_address_ports_t() :
port(0),
client_port(0),
http_port(0),
reql_port(0),
port_offset(0) { }
service_address_ports_t(const std::set<ip_address_t> &_local_addresses,
int _port,
int _client_port,
bool _http_admin_is_disabled,
int _http_port,
int _reql_port,
int _port_offset) :
local_addresses(_local_addresses),
port(_port),
client_port(_client_port),
http_admin_is_disabled(_http_admin_is_disabled),
http_port(_http_port),
reql_port(_reql_port),
port_offset(_port_offset)
{
sanitize_port(port, "port", port_offset);
sanitize_port(client_port, "client_port", port_offset);
sanitize_port(http_port, "http_port", port_offset);
sanitize_port(reql_port, "reql_port", port_offset);
}
std::string get_addresses_string() const;
std::set<ip_address_t> local_addresses;
int port;
int client_port;
bool http_admin_is_disabled;
int http_port;
int reql_port;
int port_offset;
};
/* This has been factored out from `command_line.hpp` because it takes a very
long time to compile. */
bool serve(extproc::spawner_t::info_t *spawner_info,
io_backender_t *io_backender,
const std::string &filepath,
metadata_persistence::persistent_file_t *persistent_file,
const peer_address_set_t &joins,
service_address_ports_t ports,
machine_id_t machine_id,
const cluster_semilattice_metadata_t &semilattice_metadata,
std::string web_assets,
signal_t *stop_cond);
bool serve_proxy(extproc::spawner_t::info_t *spawner_info,
const peer_address_set_t &joins,
service_address_ports_t ports,
machine_id_t machine_id,
const cluster_semilattice_metadata_t &semilattice_metadata,
std::string web_assets,
signal_t *stop_cond);
#endif /* CLUSTERING_ADMINISTRATION_MAIN_SERVE_HPP_ */
<|endoftext|>
|
<commit_before>// http://algospot.com/judge/problem/read/PREFIX
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
int N, M;
string in[3000];
class Tree {
public:
Tree(Tree* p = 0) : parent(p), depth(0), count(0), size(0) {
memset(child, 0, sizeof(Tree*) * 26);
buffer[0] = '\0';
}
//~Tree() { size_t s = child.size(); for (int i = 0; i < s; i++) delete child[i]; }
~Tree() { for (int i = 0; i < 26; i++) delete child[i]; }
Tree *parent;
int depth;
int count;
char buffer[201];
int size; // buffer size
Tree* child[26];
};
Tree *root = 0;
Tree *solution[201];
void getin(const string str) {
int s = min(M, (int)str.size());
Tree *node = root;
//int index = find(node, str);
for (int i = 0; i < s; i++) {
}
}
void getInput() {
root = new Tree();
cin >> N >> M;
cin.get();
char buffer[201];
for (int i = 0; i < N; i++) {
gets(buffer);
in[i] = buffer;
}
sort(in, in + N);
for (int i = 0; i < N; i++) {
getin(in[i]);
}
}
void printSolution(int i) {
}
void search(Tree *node) {
}
void solve() {
memset(solution, 0, sizeof(Tree*) * 201);
for (int i = 1; i <= M; i++) {
//search(root);
//printSolution(i);
}
}
void clear() {
delete root;
}
int main() {
int num;
cin >> num;
for (int i = 0; i < num; i++) {getInput(); solve(); clear();}
return 0;
}
<commit_msg>algospot prefix completed<commit_after>// http://algospot.com/judge/problem/read/PREFIX
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
int N, M;
string in[3000];
class Tree {
public:
Tree(Tree* p = 0) : parent(p), depth(0), count(0), size(0) {
memset(child, 0, sizeof(Tree*) * 26);
buffer[0] = '\0';
}
~Tree() { for (int i = 0; i < 26; i++) delete child[i]; }
Tree *parent;
int depth;
int count;
char buffer[201];
int size; // buffer size
Tree* child[26];
};
Tree *root = 0;
Tree *solution[201];
int findDiff(const char* str1, const char* str2) {
int pos = 0;
while (str1[pos] && str2[pos]) {
if(str1[pos] != str2[pos]) return pos;
pos++;
}
return pos;
}
void put(Tree *node, const char* str, int size, int index) {
if (!node->child[index]) { // put all
Tree* child = new Tree(node);
node->child[index] = child;
child->depth = node->depth + node->size;
child->count = 1;
strcpy(child->buffer, str);
child->size = size;
return;
}
Tree *child = node->child[index];
int pos = findDiff(child->buffer, str);
if (pos < child->size) { // split
Tree *temp = new Tree(node);
temp->depth = child->depth;
temp->count = child->count + 1;
strncpy(temp->buffer, child->buffer, pos);
temp->buffer[pos] = '\0';
temp->size = pos;
temp->child[child->buffer[pos] - 'a'] = child;
node->child[index] = temp;
child->parent = temp;
child->depth += pos;
char tb[201];
strcpy(tb, child->buffer + pos);
strcpy(child->buffer, tb);
child->size -= pos;
put(temp, str + pos, size - pos, str[pos] - 'a');
}
else { // put next
child->count++;
if (pos== size) return;
else put(child, str + pos, size - pos, str[pos] - 'a');
}
}
void getin(const string& str) {
int s = min(M, (int)str.size());
Tree *node = root;
put(root, str.c_str(), s, str[0] - 'a');
}
void getInput() {
root = new Tree();
cin >> N >> M;
cin.get();
char buffer[201];
for (int i = 0; i < N; i++) {
gets(buffer);
in[i] = buffer;
}
sort(in, in + N);
for (int i = 0; i < N; i++) {
getin(in[i]);
}
}
void printSolution(int i) {
char buffer [201];
buffer[200] = '\0';
Tree *node = solution[i];
int index = 200;
while (node->parent) {
int length = node->size;
if (node->depth + node-> size > i) {
length = i - node->depth;
}
index -= length;
strncpy(buffer + index, node->buffer, length);
node = node->parent;
}
cout << buffer + 200 - i << endl;
}
void search(Tree *node, int target) {
if (node->depth > target) return;
if (node->depth + node->size >= target) { // solution
if(!solution[target] || solution[target]->count < node->count) {
solution[target] = node;
}
return;
}
// else
for (int i = 0; i < 26; i++) {
if (node->child[i]) {
if (!solution[target] || solution[target]->count < node->child[i]->count) {
search(node->child[i], target);
}
}
}
}
void solve() {
memset(solution, 0, sizeof(Tree*) * 201);
for (int i = 1; i <= M; i++) {
search(root, i);
printSolution(i);
}
}
void clear() {
delete root;
}
int main(int argc, char* argv[]) {
int num;
cin >> num;
for (int i = 0; i < num; i++) {getInput(); solve(); clear();}
return 0;
}
<|endoftext|>
|
<commit_before>#include <fstream>
#include <functional>
#include <sstream>
#include <string>
#include <vector>
struct Color { unsigned char b, g, r, a; };
struct Vector2 { float u, v; };
struct Vector3 { float x, y, z; };
struct Index { int pos, uv, normal; };
struct Index3 { Index index[3]; };
struct Vertex { Vector3 pos, normal; Vector2 uv; };
struct Model {
std::vector<Vector3> posBuffer;
std::vector<Vector3> normalBuffer;
std::vector<Vector2> uvBuffer;
std::vector<Index3> indexBuffer;
Model (std::string str, char dummy = '/') {
float x, y, z;
std::ifstream is (str);
while (std::getline (is, str)) {
if (str.length () < 2) continue;
std::istringstream iss (str);
std::string token;
if (str[1] == 't' && str[0] == 'v') {
iss >> token >> x >> y;
uvBuffer.push_back ({ x, y });
}
else if (str[1] == 'n' && str[0] == 'v') {
iss >> token >> x >> y >> z;
normalBuffer.push_back ({ x, y, z });
}
else if (str[0] == 'v') {
iss >> token >> x >> y >> z;
posBuffer.push_back ({ x, y, z });
}
else if (str[0] == 'f') {
Index3 indexes;
iss >> token >> indexes.index[0].pos >> dummy >> indexes.index[0].uv >> dummy >> indexes.index[0].normal >>
indexes.index[1].pos >> dummy >> indexes.index[1].uv >> dummy >> indexes.index[1].normal >>
indexes.index[2].pos >> dummy >> indexes.index[2].uv >> dummy >> indexes.index[2].normal;
indexBuffer.push_back (indexes);
}
}
}
};
const int WIDTH = 1024, HEIGHT = 768;
struct Renderer {
std::vector<Color> frameBuffer;
std::vector<float> depthBuffer;
Renderer () : frameBuffer (WIDTH * HEIGHT, { 255, 255, 255, 0 }), depthBuffer (WIDTH * HEIGHT, std::numeric_limits<float>::max ()) { }
void DrawModel (Model &model) {
auto VertexShader = [] (const Vector3 &pos, const Vector3 &normal, const Vector2 &uv, Vertex &outVertex) {
outVertex.pos = pos;
outVertex.normal = normal;
outVertex.uv = uv;
};
for (auto &indexes : model.indexBuffer) {
Vertex ov[3];
for (int i = 0; i < 3; i++) {
VertexShader (model.posBuffer[indexes.index[i].pos - 1], model.normalBuffer[indexes.index[i].normal - 1], model.uvBuffer[indexes.index[i].uv - 1], ov[i]);
DrawTriangle (ov[0], ov[1], ov[2]);
}
}
}
void DrawTriangle (const Vertex &v0, const Vertex &v1, const Vertex &v2) {
DrawPoint (v0);
DrawPoint (v1);
DrawPoint (v2);
}
void DrawPoint (const Vertex &v) {
auto PixelShader = [] (const Vector2 &uv, Color &outColor) {
outColor = { 255, 0, 0, 0 };
};
Color c;
int x = (int)(v.pos.x * WIDTH / 2.0f), y = (int)(v.pos.y * HEIGHT / 2.0f);
int p = x + y * WIDTH;
if (x >= 0 && y >= 0 && p < frameBuffer.size ()) {
PixelShader (v.uv, c);
frameBuffer[p] = c;
}
}
};
void SaveBmp (std::vector<Color> &frameBuffer, int width, int height, std::string file) {
#define INT2CHAR_BIT(num, bit) (char)(((num) >> (bit)) & 0xff)
#define INT2CHAR(num) INT2CHAR_BIT((num),0), INT2CHAR_BIT((num),8), INT2CHAR_BIT((num),16), INT2CHAR_BIT((num),24)
const char header[54] = { 'B', 'M', INT2CHAR(54+width*height*sizeof(Color)), INT2CHAR(0), INT2CHAR(54), INT2CHAR(40), INT2CHAR(width), INT2CHAR (height), 1, 0, 32, 0 };
std::ofstream ofs (file, std::ios_base::out | std::ios_base::binary);
ofs.write (header, sizeof(header));
ofs.write (static_cast<const char *>(static_cast<const void *>(frameBuffer.data ())), width*height * sizeof (Color));
}
int main (int argc, char **argv) {
Model model (argc > 1 ? argv[1] : "cube.obj");
Renderer renderer;
renderer.DrawModel (model);
SaveBmp (renderer.frameBuffer, WIDTH, HEIGHT, "output.bmp");
//Matrix4 mvp = CreateProjectMatrix (1.57f, 1024.0f / 768.0f, 0.1f, 1000.0f) * CreateViewMatrix ({4.0f, 3.0f, 3.0f}, {0.0f, 0.0f, 0.0f}, {0.0f, 1.0f, 0.0f}) * CreateModelMatrix ();
return 0;
}
<commit_msg>some math support<commit_after>#include <fstream>
#include <functional>
#include <sstream>
#include <string>
#include <vector>
struct Vector3 {
float x, y, z;
Vector3 operator- (const Vector3 &rhs) const { return{ x - rhs.x, y - rhs.y, z - rhs.z }; }
Vector3 Cross (const Vector3 &rhs) const { return{ y * rhs.z - z * rhs.y, z * rhs.x - x * rhs.z, x * rhs.y - y * rhs.x }; }
float Length () const { return sqrtf (x * x + y * y + z * z); }
Vector3 Normalize () const { float rlen = 1.0f / Length (); return{ x * rlen, y * rlen, z * rlen }; };
};
struct Matrix4 {
float m[4][4];
Matrix4 () { memset (m, 0, sizeof (m)); };
void Invert () {
float tmp[12];
Matrix4 temm = *this;
tmp[0] = temm.m[2][2] * temm.m[3][3];
tmp[1] = temm.m[3][2] * temm.m[2][3];
tmp[2] = temm.m[1][2] * temm.m[3][3];
tmp[3] = temm.m[3][2] * temm.m[1][3];
tmp[4] = temm.m[1][2] * temm.m[2][3];
tmp[5] = temm.m[2][2] * temm.m[1][3];
tmp[6] = temm.m[0][2] * temm.m[3][3];
tmp[7] = temm.m[3][2] * temm.m[0][3];
tmp[8] = temm.m[0][2] * temm.m[2][3];
tmp[9] = temm.m[2][2] * temm.m[0][3];
tmp[10] = temm.m[0][2] * temm.m[1][3];
tmp[11] = temm.m[1][2] * temm.m[0][3];
m[0][0] = tmp[0] * temm.m[1][1] + tmp[3] * temm.m[2][1] + tmp[4] * temm.m[3][1];
m[0][0] -= tmp[1] * temm.m[1][1] + tmp[2] * temm.m[2][1] + tmp[5] * temm.m[3][1];
m[0][1] = tmp[1] * temm.m[0][1] + tmp[6] * temm.m[2][1] + tmp[9] * temm.m[3][1];
m[0][1] -= tmp[0] * temm.m[0][1] + tmp[7] * temm.m[2][1] + tmp[8] * temm.m[3][1];
m[0][2] = tmp[2] * temm.m[0][1] + tmp[7] * temm.m[1][1] + tmp[10] * temm.m[3][1];
m[0][2] -= tmp[3] * temm.m[0][1] + tmp[6] * temm.m[1][1] + tmp[11] * temm.m[3][1];
m[0][3] = tmp[5] * temm.m[0][1] + tmp[8] * temm.m[1][1] + tmp[11] * temm.m[2][1];
m[0][3] -= tmp[4] * temm.m[0][1] + tmp[9] * temm.m[1][1] + tmp[10] * temm.m[2][1];
m[1][0] = tmp[1] * temm.m[1][0] + tmp[2] * temm.m[2][0] + tmp[5] * temm.m[3][0];
m[1][0] -= tmp[0] * temm.m[1][0] + tmp[3] * temm.m[2][0] + tmp[4] * temm.m[3][0];
m[1][1] = tmp[0] * temm.m[0][0] + tmp[7] * temm.m[2][0] + tmp[8] * temm.m[3][0];
m[1][1] -= tmp[1] * temm.m[0][0] + tmp[6] * temm.m[2][0] + tmp[9] * temm.m[3][0];
m[1][2] = tmp[3] * temm.m[0][0] + tmp[6] * temm.m[1][0] + tmp[11] * temm.m[3][0];
m[1][2] -= tmp[2] * temm.m[0][0] + tmp[7] * temm.m[1][0] + tmp[10] * temm.m[3][0];
m[1][3] = tmp[4] * temm.m[0][0] + tmp[9] * temm.m[1][0] + tmp[10] * temm.m[2][0];
m[1][3] -= tmp[5] * temm.m[0][0] + tmp[8] * temm.m[1][0] + tmp[11] * temm.m[2][0];
tmp[0] = temm.m[2][0]*temm.m[3][1];
tmp[1] = temm.m[3][0]*temm.m[2][1];
tmp[2] = temm.m[1][0]*temm.m[3][1];
tmp[3] = temm.m[3][0]*temm.m[1][1];
tmp[4] = temm.m[1][0]*temm.m[2][1];
tmp[5] = temm.m[2][0]*temm.m[1][1];
tmp[6] = temm.m[0][0]*temm.m[3][1];
tmp[7] = temm.m[3][0]*temm.m[0][1];
tmp[8] = temm.m[0][0]*temm.m[2][1];
tmp[9] = temm.m[2][0]*temm.m[0][1];
tmp[10] = temm.m[0][0]*temm.m[1][1];
tmp[11] = temm.m[1][0]*temm.m[0][1];
m[2][0] = tmp[0] * temm.m[1][3] + tmp[3] * temm.m[2][3] + tmp[4] * temm.m[3][3];
m[2][0] -= tmp[1] * temm.m[1][3] + tmp[2] * temm.m[2][3] + tmp[5] * temm.m[3][3];
m[2][1] = tmp[1] * temm.m[0][3] + tmp[6] * temm.m[2][3] + tmp[9] * temm.m[3][3];
m[2][1] -= tmp[0] * temm.m[0][3] + tmp[7] * temm.m[2][3] + tmp[8] * temm.m[3][3];
m[2][2] = tmp[2] * temm.m[0][3] + tmp[7] * temm.m[1][3] + tmp[10] * temm.m[3][3];
m[2][2] -= tmp[3] * temm.m[0][3] + tmp[6] * temm.m[1][3] + tmp[11] * temm.m[3][3];
m[2][3] = tmp[5] * temm.m[0][3] + tmp[8] * temm.m[1][3] + tmp[11] * temm.m[2][3];
m[2][3] -= tmp[4] * temm.m[0][3] + tmp[9] * temm.m[1][3] + tmp[10] * temm.m[2][3];
m[3][0] = tmp[2] * temm.m[2][2] + tmp[5] * temm.m[3][2] + tmp[1] * temm.m[1][2];
m[3][0] -= tmp[4] * temm.m[3][2] + tmp[0] * temm.m[1][2] + tmp[3] * temm.m[2][2];
m[3][1] = tmp[8] * temm.m[3][2] + tmp[0] * temm.m[0][2] + tmp[7] * temm.m[2][2];
m[3][1] -= tmp[6] * temm.m[2][2] + tmp[9] * temm.m[3][2] + tmp[1] * temm.m[0][2];
m[3][2] = tmp[6] * temm.m[1][2] + tmp[11] * temm.m[3][2] + tmp[3] * temm.m[0][2];
m[3][2] -= tmp[10] * temm.m[3][2] + tmp[2] * temm.m[0][2] + tmp[7] * temm.m[1][2];
m[3][3] = tmp[10] * temm.m[2][2] + tmp[4] * temm.m[0][2] + tmp[9] * temm.m[1][2];
m[3][3] -= tmp[8] * temm.m[1][2] + tmp[11] * temm.m[2][2] + tmp[5] * temm.m[0][2];
float det = (temm.m[0][0]*m[0][0] + temm.m[1][0]*m[0][1] + temm.m[2][0]*m[0][2] + temm.m[3][0]*m[0][3]);
float idet = 1.0f / det;
m[0][0] *= idet; m[0][1] *= idet; m[0][2] *= idet; m[0][3] *= idet;
m[1][0] *= idet; m[1][1] *= idet; m[1][2] *= idet; m[1][3] *= idet;
m[2][0] *= idet; m[2][1] *= idet; m[2][2] *= idet; m[2][3] *= idet;
m[3][0] *= idet; m[3][1] *= idet; m[3][2] *= idet; m[3][3] *= idet;
}
static Matrix4 LookAt (const Vector3 &eye, const Vector3 &at, const Vector3 &up) {
Vector3 dir = (eye - at).Normalize ();
Vector3 left = up.Cross (dir).Normalize ();
Vector3 newUp = dir.Cross (left);
Matrix4 t;
t.m[0][0] = left.x; t.m[1][0] = left.y; t.m[2][0] = left.z; t.m[3][0] = 0.0f;
t.m[0][1] = newUp.x; t.m[1][1] = newUp.y; t.m[2][1] = newUp.z; t.m[3][2] = 0.0f;
t.m[0][2] = dir.x; t.m[1][2] = dir.y; t.m[2][2] = dir.z; t.m[3][2] = 0.0f;
t.m[0][3] = eye.x; t.m[1][3] = eye.y; t.m[2][3] = eye.z; t.m[3][3] = 1.0f;
t.Invert ();
return t;
}
};
struct Color { unsigned char b, g, r, a; };
struct Index { int pos, uv, normal; };
struct Index3 { Index index[3]; };
struct Vector2 { float u, v; };
struct Vertex { Vector3 pos, normal; Vector2 uv; };
struct Model {
std::vector<Vector3> posBuffer;
std::vector<Vector3> normalBuffer;
std::vector<Vector2> uvBuffer;
std::vector<Index3> indexBuffer;
Model (std::string str, char dummy = '/') {
float x, y, z;
std::ifstream is (str);
while (std::getline (is, str)) {
if (str.length () < 2) continue;
std::istringstream iss (str);
std::string token;
if (str[1] == 't' && str[0] == 'v') {
iss >> token >> x >> y;
uvBuffer.push_back ({ x, y });
}
else if (str[1] == 'n' && str[0] == 'v') {
iss >> token >> x >> y >> z;
normalBuffer.push_back ({ x, y, z });
}
else if (str[0] == 'v') {
iss >> token >> x >> y >> z;
posBuffer.push_back ({ x, y, z });
}
else if (str[0] == 'f') {
Index3 indexes;
iss >> token >> indexes.index[0].pos >> dummy >> indexes.index[0].uv >> dummy >> indexes.index[0].normal >>
indexes.index[1].pos >> dummy >> indexes.index[1].uv >> dummy >> indexes.index[1].normal >>
indexes.index[2].pos >> dummy >> indexes.index[2].uv >> dummy >> indexes.index[2].normal;
indexBuffer.push_back (indexes);
}
}
}
};
const int WIDTH = 1024, HEIGHT = 768;
struct Renderer {
std::vector<Color> frameBuffer;
std::vector<float> depthBuffer;
Matrix4 camMat;
Matrix4 projMat;
Renderer (const Vector3 &eye, const Vector3 &at, const Vector3 &up) : frameBuffer (WIDTH * HEIGHT, { 255, 255, 255, 0 }), depthBuffer (WIDTH * HEIGHT, std::numeric_limits<float>::max ()) {
camMat = Matrix4::LookAt (eye, at, up);
}
void DrawModel (Model &model) {
auto VertexShader = [] (const Vector3 &pos, const Vector3 &normal, const Vector2 &uv, Vertex &outVertex) {
outVertex.pos = pos;
outVertex.normal = normal;
outVertex.uv = uv;
};
for (auto &indexes : model.indexBuffer) {
Vertex ov[3];
for (int i = 0; i < 3; i++) {
VertexShader (model.posBuffer[indexes.index[i].pos - 1], model.normalBuffer[indexes.index[i].normal - 1], model.uvBuffer[indexes.index[i].uv - 1], ov[i]);
DrawTriangle (ov[0], ov[1], ov[2]);
}
}
}
void DrawTriangle (const Vertex &v0, const Vertex &v1, const Vertex &v2) {
DrawPoint (v0);
DrawPoint (v1);
DrawPoint (v2);
}
void DrawPoint (const Vertex &v) {
auto PixelShader = [] (const Vector2 &uv, Color &outColor) {
outColor = { 255, 0, 0, 0 };
};
Color c;
int x = (int)(v.pos.x * WIDTH / 2.0f), y = (int)(v.pos.y * HEIGHT / 2.0f);
int p = x + y * WIDTH;
if (x >= 0 && y >= 0 && p < frameBuffer.size ()) {
PixelShader (v.uv, c);
frameBuffer[p] = c;
}
}
};
void SaveBmp (std::vector<Color> &frameBuffer, int width, int height, std::string file) {
#define INT2CHAR_BIT(num, bit) (char)(((num) >> (bit)) & 0xff)
#define INT2CHAR(num) INT2CHAR_BIT((num),0), INT2CHAR_BIT((num),8), INT2CHAR_BIT((num),16), INT2CHAR_BIT((num),24)
const char header[54] = { 'B', 'M', INT2CHAR(54+width*height*sizeof(Color)), INT2CHAR(0), INT2CHAR(54), INT2CHAR(40), INT2CHAR(width), INT2CHAR (height), 1, 0, 32, 0 };
std::ofstream ofs (file, std::ios_base::out | std::ios_base::binary);
ofs.write (header, sizeof(header));
ofs.write (static_cast<const char *>(static_cast<const void *>(frameBuffer.data ())), width*height * sizeof (Color));
}
int main (int argc, char **argv) {
Model model (argc > 1 ? argv[1] : "cube.obj");
Renderer renderer ({ 4.0f, 3.0f, 3.0f }, { 0.0f, 0.0f, 0.0f }, { 0.0f, 1.0f, 0.0f });
renderer.DrawModel (model);
SaveBmp (renderer.frameBuffer, WIDTH, HEIGHT, "output.bmp");
//Matrix4 mvp = CreateProjectMatrix (1.57f, 1024.0f / 768.0f, 0.1f, 1000.0f) * CreateViewMatrix ({4.0f, 3.0f, 3.0f}, {0.0f, 0.0f, 0.0f}, {0.0f, 1.0f, 0.0f}) * CreateModelMatrix ();
return 0;
}
<|endoftext|>
|
<commit_before>#include <algorithm>
#include <glog/logging.h>
#include "simple_allocator.hpp"
using std::max;
using std::sort;
using namespace nexus;
using namespace nexus::internal;
using namespace nexus::internal::master;
void SimpleAllocator::frameworkAdded(Framework* framework)
{
LOG(INFO) << "Added " << framework;
makeNewOffers();
}
void SimpleAllocator::frameworkRemoved(Framework* framework)
{
LOG(INFO) << "Removed " << framework;
foreachpair (Slave* s, unordered_set<Framework*>& refs, refusers)
refs.erase(framework);
// TODO: Re-offer just the slaves that the framework had tasks on?
// Alternatively, comment this out and wait for a timer tick
makeNewOffers();
}
void SimpleAllocator::slaveAdded(Slave* slave)
{
LOG(INFO) << "Added " << slave;
refusers[slave] = unordered_set<Framework*>();
totalResources += slave->resources;
makeNewOffers(slave);
}
void SimpleAllocator::slaveRemoved(Slave* slave)
{
LOG(INFO) << "Removed " << slave;
totalResources -= slave->resources;
refusers.erase(slave);
}
void SimpleAllocator::taskRemoved(Task* task, TaskRemovalReason reason)
{
LOG(INFO) << "Removed " << task;
// Remove all refusers from this slave since it has more resources free
Slave* slave = master->lookupSlave(task->slaveId);
CHECK(slave != 0);
refusers[slave].clear();
// Re-offer the resources, unless this task was removed due to a lost
// slave or a lost framework (in which case we'll get another callback)
if (reason == TRR_TASK_ENDED || reason == TRR_EXECUTOR_LOST)
makeNewOffers(slave);
}
void SimpleAllocator::offerReturned(SlotOffer* offer,
OfferReturnReason reason,
const vector<SlaveResources>& resLeft)
{
LOG(INFO) << "Offer returned: " << offer << ", reason = " << reason;
// If this offer returned due to the framework replying, add it to refusers
if (reason == ORR_FRAMEWORK_REPLIED) {
Framework* framework = master->lookupFramework(offer->frameworkId);
CHECK(framework != 0);
foreach (const SlaveResources& r, resLeft) {
LOG(INFO) << "Framework reply leaves " << r.resources
<< " free on " << r.slave;
if (r.resources.cpus > 0 || r.resources.mem > 0) {
LOG(INFO) << "Inserting " << framework << " as refuser for " << r.slave;
refusers[r.slave].insert(framework);
}
}
}
// Make new offers, unless the offer returned due to a lost framework or slave
// (in those cases, frameworkRemoved and slaveRemoved will be called later)
if (reason != ORR_SLAVE_LOST && reason != ORR_FRAMEWORK_LOST) {
vector<Slave*> slaves;
foreach (const SlaveResources& r, resLeft)
slaves.push_back(r.slave);
makeNewOffers(slaves);
}
}
void SimpleAllocator::offersRevived(Framework* framework)
{
LOG(INFO) << "Filters removed for " << framework;
makeNewOffers();
}
void SimpleAllocator::timerTick()
{
// TODO: Is this necessary?
makeNewOffers();
}
namespace {
struct DominantShareComparator
{
Resources total;
DominantShareComparator(Resources _total) : total(_total)
{
if (total.cpus == 0) // Prevent division by zero if there are no slaves
total.cpus = 1;
if (total.mem == 0)
total.mem = 1;
}
bool operator() (Framework* f1, Framework* f2)
{
double share1 = max(f1->resources.cpus / (double) total.cpus,
f1->resources.mem / (double) total.mem);
double share2 = max(f2->resources.cpus / (double) total.cpus,
f2->resources.mem / (double) total.mem);
if (share1 == share2)
return f1->id < f2->id; // Make the sort deterministic for unit testing
else
return share1 < share2;
}
};
}
vector<Framework*> SimpleAllocator::getAllocationOrdering()
{
vector<Framework*> frameworks = master->getActiveFrameworks();
DominantShareComparator comp(totalResources);
sort(frameworks.begin(), frameworks.end(), comp);
return frameworks;
}
void SimpleAllocator::makeNewOffers()
{
// TODO: Create a method in master so that we don't return the whole list of slaves
vector<Slave*> slaves = master->getActiveSlaves();
makeNewOffers(slaves);
}
void SimpleAllocator::makeNewOffers(Slave* slave)
{
vector<Slave*> slaves;
slaves.push_back(slave);
makeNewOffers(slaves);
}
void SimpleAllocator::makeNewOffers(const vector<Slave*>& slaves)
{
// Get an ordering of frameworks to send offers to
vector<Framework*> ordering = getAllocationOrdering();
if (ordering.size() == 0)
return;
// Find all the free resources that can be allocated
unordered_map<Slave* , Resources> freeResources;
foreach (Slave* slave, slaves) {
if (slave->active) {
Resources res = slave->resourcesFree();
if (res.cpus >= MIN_CPUS && res.mem >= MIN_MEM) {
VLOG(1) << "Found free resources: " << res << " on " << slave;
freeResources[slave] = res;
}
}
}
if (freeResources.size() == 0)
return;
// Clear refusers on any slave that has been refused by everyone
foreachpair (Slave* slave, _, freeResources) {
unordered_set<Framework*>& refs = refusers[slave];
if (refs.size() == ordering.size()) {
VLOG(1) << "Clearing refusers for " << slave
<< " because everyone refused it";
refs.clear();
}
}
foreach (Framework* framework, ordering) {
// See which resources this framework can take (given filters & refusals)
vector<SlaveResources> offerable;
foreachpair (Slave* slave, Resources resources, freeResources) {
if (refusers[slave].find(framework) == refusers[slave].end() &&
!framework->filters(slave, resources)) {
VLOG(1) << "Offering " << resources << " on " << slave
<< " to framework " << framework->id;
offerable.push_back(SlaveResources(slave, resources));
}
}
if (offerable.size() > 0) {
foreach (SlaveResources& r, offerable) {
freeResources.erase(r.slave);
}
master->makeOffer(framework, offerable);
}
}
}
<commit_msg>Changing some verbose log statements in SimpleAllocator to VLOG. Fixes #62.<commit_after>#include <algorithm>
#include <glog/logging.h>
#include "simple_allocator.hpp"
using std::max;
using std::sort;
using namespace nexus;
using namespace nexus::internal;
using namespace nexus::internal::master;
void SimpleAllocator::frameworkAdded(Framework* framework)
{
LOG(INFO) << "Added " << framework;
makeNewOffers();
}
void SimpleAllocator::frameworkRemoved(Framework* framework)
{
LOG(INFO) << "Removed " << framework;
foreachpair (Slave* s, unordered_set<Framework*>& refs, refusers)
refs.erase(framework);
// TODO: Re-offer just the slaves that the framework had tasks on?
// Alternatively, comment this out and wait for a timer tick
makeNewOffers();
}
void SimpleAllocator::slaveAdded(Slave* slave)
{
LOG(INFO) << "Added " << slave;
refusers[slave] = unordered_set<Framework*>();
totalResources += slave->resources;
makeNewOffers(slave);
}
void SimpleAllocator::slaveRemoved(Slave* slave)
{
LOG(INFO) << "Removed " << slave;
totalResources -= slave->resources;
refusers.erase(slave);
}
void SimpleAllocator::taskRemoved(Task* task, TaskRemovalReason reason)
{
LOG(INFO) << "Removed " << task;
// Remove all refusers from this slave since it has more resources free
Slave* slave = master->lookupSlave(task->slaveId);
CHECK(slave != 0);
refusers[slave].clear();
// Re-offer the resources, unless this task was removed due to a lost
// slave or a lost framework (in which case we'll get another callback)
if (reason == TRR_TASK_ENDED || reason == TRR_EXECUTOR_LOST)
makeNewOffers(slave);
}
void SimpleAllocator::offerReturned(SlotOffer* offer,
OfferReturnReason reason,
const vector<SlaveResources>& resLeft)
{
LOG(INFO) << "Offer returned: " << offer << ", reason = " << reason;
// If this offer returned due to the framework replying, add it to refusers
if (reason == ORR_FRAMEWORK_REPLIED) {
Framework* framework = master->lookupFramework(offer->frameworkId);
CHECK(framework != 0);
foreach (const SlaveResources& r, resLeft) {
VLOG(1) << "Framework reply leaves " << r.resources
<< " free on " << r.slave;
if (r.resources.cpus > 0 || r.resources.mem > 0) {
VLOG(1) << "Inserting " << framework << " as refuser for " << r.slave;
refusers[r.slave].insert(framework);
}
}
}
// Make new offers, unless the offer returned due to a lost framework or slave
// (in those cases, frameworkRemoved and slaveRemoved will be called later)
if (reason != ORR_SLAVE_LOST && reason != ORR_FRAMEWORK_LOST) {
vector<Slave*> slaves;
foreach (const SlaveResources& r, resLeft)
slaves.push_back(r.slave);
makeNewOffers(slaves);
}
}
void SimpleAllocator::offersRevived(Framework* framework)
{
LOG(INFO) << "Filters removed for " << framework;
makeNewOffers();
}
void SimpleAllocator::timerTick()
{
// TODO: Is this necessary?
makeNewOffers();
}
namespace {
struct DominantShareComparator
{
Resources total;
DominantShareComparator(Resources _total) : total(_total)
{
if (total.cpus == 0) // Prevent division by zero if there are no slaves
total.cpus = 1;
if (total.mem == 0)
total.mem = 1;
}
bool operator() (Framework* f1, Framework* f2)
{
double share1 = max(f1->resources.cpus / (double) total.cpus,
f1->resources.mem / (double) total.mem);
double share2 = max(f2->resources.cpus / (double) total.cpus,
f2->resources.mem / (double) total.mem);
if (share1 == share2)
return f1->id < f2->id; // Make the sort deterministic for unit testing
else
return share1 < share2;
}
};
}
vector<Framework*> SimpleAllocator::getAllocationOrdering()
{
vector<Framework*> frameworks = master->getActiveFrameworks();
DominantShareComparator comp(totalResources);
sort(frameworks.begin(), frameworks.end(), comp);
return frameworks;
}
void SimpleAllocator::makeNewOffers()
{
// TODO: Create a method in master so that we don't return the whole list of slaves
vector<Slave*> slaves = master->getActiveSlaves();
makeNewOffers(slaves);
}
void SimpleAllocator::makeNewOffers(Slave* slave)
{
vector<Slave*> slaves;
slaves.push_back(slave);
makeNewOffers(slaves);
}
void SimpleAllocator::makeNewOffers(const vector<Slave*>& slaves)
{
// Get an ordering of frameworks to send offers to
vector<Framework*> ordering = getAllocationOrdering();
if (ordering.size() == 0)
return;
// Find all the free resources that can be allocated
unordered_map<Slave* , Resources> freeResources;
foreach (Slave* slave, slaves) {
if (slave->active) {
Resources res = slave->resourcesFree();
if (res.cpus >= MIN_CPUS && res.mem >= MIN_MEM) {
VLOG(1) << "Found free resources: " << res << " on " << slave;
freeResources[slave] = res;
}
}
}
if (freeResources.size() == 0)
return;
// Clear refusers on any slave that has been refused by everyone
foreachpair (Slave* slave, _, freeResources) {
unordered_set<Framework*>& refs = refusers[slave];
if (refs.size() == ordering.size()) {
VLOG(1) << "Clearing refusers for " << slave
<< " because everyone refused it";
refs.clear();
}
}
foreach (Framework* framework, ordering) {
// See which resources this framework can take (given filters & refusals)
vector<SlaveResources> offerable;
foreachpair (Slave* slave, Resources resources, freeResources) {
if (refusers[slave].find(framework) == refusers[slave].end() &&
!framework->filters(slave, resources)) {
VLOG(1) << "Offering " << resources << " on " << slave
<< " to framework " << framework->id;
offerable.push_back(SlaveResources(slave, resources));
}
}
if (offerable.size() > 0) {
foreach (SlaveResources& r, offerable) {
freeResources.erase(r.slave);
}
master->makeOffer(framework, offerable);
}
}
}
<|endoftext|>
|
<commit_before><commit_msg>Planning: disaable stop_over_line test for now<commit_after><|endoftext|>
|
<commit_before>//=======================================================================
// Copyright 2014-2015 David Simmons-Duffin.
// Distributed under the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#pragma once
#include "Vector.hxx"
#include <El.hpp>
// A univariate polynomial
//
// p(x) = a_0 + a_1 x + a_2 x^2 + ... + a_n x^n
//
class Polynomial
{
public:
// Coefficients {a_0, a_1, ..., a_n} in increasing order of degree
Vector coefficients;
std::vector<El::BigFloat> coefficients_elemental;
// The zero polynomial
Polynomial() : coefficients(1, 0) {}
// Degree of p(x)
int degree() const { return coefficients.size() - 1; };
// Evaluate p(x) for some x using horner's method
Real operator()(const Real &x) const
{
assert(!coefficients.empty());
auto coefficient(coefficients.rbegin());
Real result(*coefficient);
++coefficient;
for(; coefficient != coefficients.rend(); ++coefficient)
{
result *= x;
result += *coefficient;
}
return result;
}
El::BigFloat operator()(const El::BigFloat &x) const
{
assert(!coefficients_elemental.empty());
auto coefficient(coefficients_elemental.rbegin());
El::BigFloat result(*coefficient);
++coefficient;
for(; coefficient != coefficients_elemental.rend(); ++coefficient)
{
result *= x;
result += *coefficient;
}
return result;
}
// Print p(x), for debugging purposes
friend std::ostream &operator<<(std::ostream &os, const Polynomial &p)
{
for(int i = p.degree(); i >= 0; i--)
{
os << p.coefficients[i];
if(i > 1)
os << "x^" << i << " + ";
else if(i == 1)
os << "x + ";
}
return os;
}
};
<commit_msg>Replace some use of coefficients with coefficients_elemental<commit_after>//=======================================================================
// Copyright 2014-2015 David Simmons-Duffin.
// Distributed under the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#pragma once
#include "Vector.hxx"
#include <El.hpp>
// A univariate polynomial
//
// p(x) = a_0 + a_1 x + a_2 x^2 + ... + a_n x^n
//
class Polynomial
{
public:
// Coefficients {a_0, a_1, ..., a_n} in increasing order of degree
Vector coefficients;
std::vector<El::BigFloat> coefficients_elemental;
// The zero polynomial
Polynomial() : coefficients(1, 0), coefficients_elemental(1, 0) {}
// Degree of p(x)
int degree() const { return coefficients_elemental.size() - 1; };
// Evaluate p(x) for some x using horner's method
Real operator()(const Real &x) const
{
assert(!coefficients.empty());
auto coefficient(coefficients.rbegin());
Real result(*coefficient);
++coefficient;
for(; coefficient != coefficients.rend(); ++coefficient)
{
result *= x;
result += *coefficient;
}
return result;
}
El::BigFloat operator()(const El::BigFloat &x) const
{
assert(!coefficients_elemental.empty());
auto coefficient(coefficients_elemental.rbegin());
El::BigFloat result(*coefficient);
++coefficient;
for(; coefficient != coefficients_elemental.rend(); ++coefficient)
{
result *= x;
result += *coefficient;
}
return result;
}
// Print p(x), for debugging purposes
friend std::ostream &operator<<(std::ostream &os, const Polynomial &p)
{
for(int i = p.degree(); i >= 0; i--)
{
os << p.coefficients_elemental[i];
if(i > 1)
{
os << "x^" << i << " + ";
}
else if(i == 1)
{
os << "x + ";
}
}
return os;
}
};
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2008 James Molloy, Jörg Pfähler, Matthew Iselin
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <BootstrapInfo.h>
#include <Log.h>
#include <panic.h>
#include <machine/Timer.h>
#include <machine/Machine.h>
#include <utilities/utility.h>
#include <processor/Processor.h>
extern BootstrapStruct_t *g_pBootstrapInfo;
#define LOG_TO_SERIAL 0
Log Log::m_Instance;
BootProgressFn g_BootProgress = 0;
BootProgressTotalFn g_BootProgressTotal = 0;
Log::Log () :
m_Lock(),
m_StaticEntries(0),
m_StaticEntryStart(0),
m_StaticEntryEnd(0),
m_Buffer(),
m_NumberType(Dec),
m_EchoToSerial(LOG_TO_SERIAL)
{
// Disabled because of initialisation problems
/*
char *cmdline = g_pBootstrapInfo->getCommandLine();
if(cmdline)
{
List<String*> cmds = String(cmdline).tokenise(' ');
for (List<String*>::Iterator it = cmds.begin();
it != cmds.end();
it++)
{
String *cmd = *it;
if(*cmd == String("--disable-log-to-serial"))
{
m_EchoToSerial = false;
break;
}
else if(*cmd == String("--enable-log-to-serial"))
{
m_EchoToSerial = true;
break;
}
}
}*/
}
Log::~Log ()
{
}
Log &Log::operator<< (const char *str)
{
m_Buffer.str.append(str);
return *this;
}
Log &Log::operator<< (String str)
{
m_Buffer.str.append(str);
return *this;
}
Log &Log::operator<< (bool b)
{
if (b)
return *this << "true";
return *this << "false";
}
template<class T>
Log &Log::operator << (T n)
{
size_t radix = 10;
if (m_NumberType == Hex)
{
radix = 16;
m_Buffer.str.append("0x");
}
m_Buffer.str.append(n, radix);
return *this;
}
// NOTE: Make sure that the templated << operator gets only instantiated for
// integer types.
template Log &Log::operator << (char);
template Log &Log::operator << (unsigned char);
template Log &Log::operator << (short);
template Log &Log::operator << (unsigned short);
template Log &Log::operator << (int);
template Log &Log::operator << (unsigned int);
template Log &Log::operator << (long);
template Log &Log::operator << (unsigned long);
// NOTE: Instantiating these for MIPS32 requires __udiv3di, but we only have
// __udiv3ti (??) in libgcc.a for mips.
#ifndef MIPS32
template Log &Log::operator << (long long);
template Log &Log::operator << (unsigned long long);
#endif
Log &Log::operator<< (Modifier type)
{
// Flush the buffer.
if (type == Flush)
{
if (m_StaticEntries >= LOG_ENTRIES)
{
m_StaticEntryStart = (m_StaticEntryStart+1) % LOG_ENTRIES;
}
else
m_StaticEntries ++;
m_StaticLog[m_StaticEntryEnd] = m_Buffer;
m_StaticEntryEnd = (m_StaticEntryEnd+1) % LOG_ENTRIES;
if (Machine::instance().isInitialised() == true && m_EchoToSerial == true)
{
switch (m_Buffer.type)
{
case Notice:
Machine::instance().getSerial(0)->write("(NN) ");
break;
case Warning:
Machine::instance().getSerial(0)->write("(WW) ");
break;
case Error:
Machine::instance().getSerial(0)->write("(EE) ");
break;
case Fatal:
Machine::instance().getSerial(0)->write("(FF) ");
break;
}
Machine::instance().getSerial(0)->write ( static_cast<const char *> (m_Buffer.str) );
Machine::instance().getSerial(0)->write ("\n");
}
}
return *this;
}
Log &Log::operator<< (NumberType type)
{
m_NumberType = type;
return *this;
}
Log &Log::operator<< (SeverityLevel level)
{
// Zero the buffer.
m_Buffer.str.clear();
m_Buffer.type = level;
Machine &machine = Machine::instance();
if (machine.isInitialised() == true &&
machine.getTimer() != 0)
{
Timer &timer = *machine.getTimer();
m_Buffer.timestamp = timer.getTickCount();
}
else
m_Buffer.timestamp = 0;
return *this;
}
<commit_msg>#define'd LOG_TO_SERIAL wrong, oops<commit_after>/*
* Copyright (c) 2008 James Molloy, Jörg Pfähler, Matthew Iselin
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <BootstrapInfo.h>
#include <Log.h>
#include <panic.h>
#include <machine/Timer.h>
#include <machine/Machine.h>
#include <utilities/utility.h>
#include <processor/Processor.h>
extern BootstrapStruct_t *g_pBootstrapInfo;
#define LOG_TO_SERIAL 1
Log Log::m_Instance;
BootProgressFn g_BootProgress = 0;
BootProgressTotalFn g_BootProgressTotal = 0;
Log::Log () :
m_Lock(),
m_StaticEntries(0),
m_StaticEntryStart(0),
m_StaticEntryEnd(0),
m_Buffer(),
m_NumberType(Dec),
m_EchoToSerial(LOG_TO_SERIAL)
{
// Disabled because of initialisation problems
/*
char *cmdline = g_pBootstrapInfo->getCommandLine();
if(cmdline)
{
List<String*> cmds = String(cmdline).tokenise(' ');
for (List<String*>::Iterator it = cmds.begin();
it != cmds.end();
it++)
{
String *cmd = *it;
if(*cmd == String("--disable-log-to-serial"))
{
m_EchoToSerial = false;
break;
}
else if(*cmd == String("--enable-log-to-serial"))
{
m_EchoToSerial = true;
break;
}
}
}*/
}
Log::~Log ()
{
}
Log &Log::operator<< (const char *str)
{
m_Buffer.str.append(str);
return *this;
}
Log &Log::operator<< (String str)
{
m_Buffer.str.append(str);
return *this;
}
Log &Log::operator<< (bool b)
{
if (b)
return *this << "true";
return *this << "false";
}
template<class T>
Log &Log::operator << (T n)
{
size_t radix = 10;
if (m_NumberType == Hex)
{
radix = 16;
m_Buffer.str.append("0x");
}
m_Buffer.str.append(n, radix);
return *this;
}
// NOTE: Make sure that the templated << operator gets only instantiated for
// integer types.
template Log &Log::operator << (char);
template Log &Log::operator << (unsigned char);
template Log &Log::operator << (short);
template Log &Log::operator << (unsigned short);
template Log &Log::operator << (int);
template Log &Log::operator << (unsigned int);
template Log &Log::operator << (long);
template Log &Log::operator << (unsigned long);
// NOTE: Instantiating these for MIPS32 requires __udiv3di, but we only have
// __udiv3ti (??) in libgcc.a for mips.
#ifndef MIPS32
template Log &Log::operator << (long long);
template Log &Log::operator << (unsigned long long);
#endif
Log &Log::operator<< (Modifier type)
{
// Flush the buffer.
if (type == Flush)
{
if (m_StaticEntries >= LOG_ENTRIES)
{
m_StaticEntryStart = (m_StaticEntryStart+1) % LOG_ENTRIES;
}
else
m_StaticEntries ++;
m_StaticLog[m_StaticEntryEnd] = m_Buffer;
m_StaticEntryEnd = (m_StaticEntryEnd+1) % LOG_ENTRIES;
if (Machine::instance().isInitialised() == true && m_EchoToSerial == true)
{
switch (m_Buffer.type)
{
case Notice:
Machine::instance().getSerial(0)->write("(NN) ");
break;
case Warning:
Machine::instance().getSerial(0)->write("(WW) ");
break;
case Error:
Machine::instance().getSerial(0)->write("(EE) ");
break;
case Fatal:
Machine::instance().getSerial(0)->write("(FF) ");
break;
}
Machine::instance().getSerial(0)->write ( static_cast<const char *> (m_Buffer.str) );
Machine::instance().getSerial(0)->write ("\n");
}
}
return *this;
}
Log &Log::operator<< (NumberType type)
{
m_NumberType = type;
return *this;
}
Log &Log::operator<< (SeverityLevel level)
{
// Zero the buffer.
m_Buffer.str.clear();
m_Buffer.type = level;
Machine &machine = Machine::instance();
if (machine.isInitialised() == true &&
machine.getTimer() != 0)
{
Timer &timer = *machine.getTimer();
m_Buffer.timestamp = timer.getTickCount();
}
else
m_Buffer.timestamp = 0;
return *this;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: current.cxx,v $
*
* $Revision: 1.13 $
*
* last change: $Author: rt $ $Date: 2005-09-08 08:45:15 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#include "rtl/uuid.h"
#include "osl/thread.h"
#include "osl/mutex.hxx"
#include "uno/environment.hxx"
#include "uno/mapping.h"
#include "uno/lbnames.h"
#include "typelib/typedescription.h"
#include "current.hxx"
using namespace ::osl;
using namespace ::rtl;
using namespace ::cppu;
using namespace ::com::sun::star::uno;
namespace cppu
{
//--------------------------------------------------------------------------------------------------
class SAL_NO_VTABLE XInterface
{
public:
virtual void SAL_CALL slot_queryInterface() = 0;
virtual void SAL_CALL acquire() throw () = 0;
virtual void SAL_CALL release() throw () = 0;
};
//--------------------------------------------------------------------------------------------------
static typelib_InterfaceTypeDescription * get_type_XCurrentContext()
{
static typelib_InterfaceTypeDescription * s_type_XCurrentContext = 0;
if (0 == s_type_XCurrentContext)
{
::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );
if (0 == s_type_XCurrentContext)
{
OUString sTypeName( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.uno.XCurrentContext") );
typelib_InterfaceTypeDescription * pTD = 0;
typelib_TypeDescriptionReference * pMembers[1] = { 0 };
OUString sMethodName0(
RTL_CONSTASCII_USTRINGPARAM("com.sun.star.uno.XCurrentContext::getValueByName") );
typelib_typedescriptionreference_new(
&pMembers[0],
typelib_TypeClass_INTERFACE_METHOD,
sMethodName0.pData );
typelib_typedescription_newInterface(
&pTD,
sTypeName.pData, 0x00000000, 0x0000, 0x0000, 0x00000000, 0x00000000,
* typelib_static_type_getByTypeClass( typelib_TypeClass_INTERFACE ),
1,
pMembers );
typelib_typedescription_register( (typelib_TypeDescription**)&pTD );
typelib_typedescriptionreference_release( pMembers[0] );
typelib_InterfaceMethodTypeDescription * pMethod = 0;
typelib_Parameter_Init aParameters[1];
OUString sParamName0( RTL_CONSTASCII_USTRINGPARAM("Name") );
OUString sParamType0( RTL_CONSTASCII_USTRINGPARAM("string") );
aParameters[0].pParamName = sParamName0.pData;
aParameters[0].eTypeClass = typelib_TypeClass_STRING;
aParameters[0].pTypeName = sParamType0.pData;
aParameters[0].bIn = sal_True;
aParameters[0].bOut = sal_False;
rtl_uString * pExceptions[1];
OUString sExceptionName0(
RTL_CONSTASCII_USTRINGPARAM("com.sun.star.uno.RuntimeException") );
pExceptions[0] = sExceptionName0.pData;
OUString sReturnType0( RTL_CONSTASCII_USTRINGPARAM("any") );
typelib_typedescription_newInterfaceMethod(
&pMethod,
3, sal_False,
sMethodName0.pData,
typelib_TypeClass_ANY, sReturnType0.pData,
1, aParameters, 1, pExceptions );
typelib_typedescription_register( (typelib_TypeDescription**)&pMethod );
typelib_typedescription_release( (typelib_TypeDescription*)pMethod );
#if ! defined CPPU_LEAK_STATIC_DATA
// another static ref
++reinterpret_cast< typelib_TypeDescription * >( pTD )->
nStaticRefCount;
#endif
s_type_XCurrentContext = pTD;
}
}
return s_type_XCurrentContext;
}
//##################################################################################################
//==================================================================================================
class ThreadKey
{
sal_Bool _bInit;
oslThreadKey _hThreadKey;
oslThreadKeyCallbackFunction _pCallback;
public:
inline oslThreadKey getThreadKey() SAL_THROW( () );
inline ThreadKey( oslThreadKeyCallbackFunction pCallback ) SAL_THROW( () );
inline ~ThreadKey() SAL_THROW( () );
};
//__________________________________________________________________________________________________
inline ThreadKey::ThreadKey( oslThreadKeyCallbackFunction pCallback ) SAL_THROW( () )
: _bInit( sal_False )
, _pCallback( pCallback )
{
}
//__________________________________________________________________________________________________
inline ThreadKey::~ThreadKey() SAL_THROW( () )
{
if (_bInit)
{
::osl_destroyThreadKey( _hThreadKey );
}
}
//__________________________________________________________________________________________________
inline oslThreadKey ThreadKey::getThreadKey() SAL_THROW( () )
{
if (! _bInit)
{
MutexGuard aGuard( Mutex::getGlobalMutex() );
if (! _bInit)
{
_hThreadKey = ::osl_createThreadKey( _pCallback );
_bInit = sal_True;
}
}
return _hThreadKey;
}
//==================================================================================================
extern "C" void SAL_CALL delete_IdContainer( void * p )
{
if (p)
{
IdContainer * pId = reinterpret_cast< IdContainer * >( p );
if (pId->pCurrentContext)
{
if (pId->pCurrentContextEnv)
{
(*pId->pCurrentContextEnv->releaseInterface)(
pId->pCurrentContextEnv, pId->pCurrentContext );
(*((uno_Environment *)pId->pCurrentContextEnv)->release)(
(uno_Environment *)pId->pCurrentContextEnv );
}
else // current compiler used for context interface implementation
{
reinterpret_cast< ::cppu::XInterface * >( pId->pCurrentContext )->release();
}
}
if (pId->bInit)
{
::rtl_byte_sequence_release( pId->pLocalThreadId );
::rtl_byte_sequence_release( pId->pCurrentId );
}
delete pId;
}
}
//==================================================================================================
IdContainer * getIdContainer() SAL_THROW( () )
{
static ThreadKey s_key( delete_IdContainer );
oslThreadKey aKey = s_key.getThreadKey();
IdContainer * pId = reinterpret_cast< IdContainer * >( ::osl_getThreadKeyData( aKey ) );
if (! pId)
{
pId = new IdContainer();
pId->pCurrentContext = 0;
pId->pCurrentContextEnv = 0;
pId->bInit = sal_False;
::osl_setThreadKeyData( aKey, pId );
}
return pId;
}
}
//##################################################################################################
extern "C" sal_Bool SAL_CALL uno_setCurrentContext(
void * pCurrentContext,
rtl_uString * pEnvTypeName, void * pEnvContext )
SAL_THROW_EXTERN_C()
{
IdContainer * pId = getIdContainer();
OSL_ASSERT( pId );
// free old one
if (pId->pCurrentContext)
{
if (pId->pCurrentContextEnv)
{
(*pId->pCurrentContextEnv->releaseInterface)(
pId->pCurrentContextEnv, pId->pCurrentContext );
(*((uno_Environment *)pId->pCurrentContextEnv)->release)(
(uno_Environment *)pId->pCurrentContextEnv );
pId->pCurrentContextEnv = 0;
}
else // current compiler used for context interface implementation
{
reinterpret_cast< ::cppu::XInterface * >( pId->pCurrentContext )->release();
}
pId->pCurrentContext = 0;
}
if (pCurrentContext)
{
OUString const & rEnvTypeName = * reinterpret_cast< OUString const * >( &pEnvTypeName );
if (rEnvTypeName.equalsAsciiL(
RTL_CONSTASCII_STRINGPARAM(CPPU_CURRENT_LANGUAGE_BINDING_NAME) ))
{
reinterpret_cast< ::cppu::XInterface * >( pCurrentContext )->acquire();
pId->pCurrentContext = pCurrentContext;
pId->pCurrentContextEnv = 0; // special for this compiler env
}
else
{
uno_Environment * pEnv = 0;
::uno_getEnvironment( &pEnv, pEnvTypeName, pEnvContext );
OSL_ASSERT( pEnv && pEnv->pExtEnv );
if (pEnv)
{
if (pEnv->pExtEnv)
{
pId->pCurrentContextEnv = pEnv->pExtEnv;
(*pId->pCurrentContextEnv->acquireInterface)(
pId->pCurrentContextEnv, pCurrentContext );
pId->pCurrentContext = pCurrentContext;
}
else
{
(*pEnv->release)( pEnv );
return sal_False;
}
}
else
{
return sal_False;
}
}
}
return sal_True;
}
//##################################################################################################
extern "C" sal_Bool SAL_CALL uno_getCurrentContext(
void ** ppCurrentContext, rtl_uString * pEnvTypeName, void * pEnvContext )
SAL_THROW_EXTERN_C()
{
IdContainer * pId = getIdContainer();
OSL_ASSERT( pId );
::com::sun::star::uno::Environment target_env;
OUString const & rEnvTypeName = * reinterpret_cast< OUString const * >( &pEnvTypeName );
// release inout parameter
if (*ppCurrentContext)
{
if (rEnvTypeName.equalsAsciiL(
RTL_CONSTASCII_STRINGPARAM(CPPU_CURRENT_LANGUAGE_BINDING_NAME) ))
{
reinterpret_cast< ::cppu::XInterface * >( *ppCurrentContext )->release();
}
else
{
uno_getEnvironment( (uno_Environment **) &target_env, pEnvTypeName, pEnvContext );
OSL_ASSERT( target_env.is() );
if (! target_env.is())
return sal_False;
uno_ExtEnvironment * pEnv = target_env.get()->pExtEnv;
OSL_ASSERT( 0 != pEnv );
if (0 == pEnv)
return sal_False;
(*pEnv->releaseInterface)( pEnv, *ppCurrentContext );
}
*ppCurrentContext = 0;
}
// case: null-ref
if (0 == pId->pCurrentContext)
return sal_True;
// case: same env (current compiler env)
if ((0 == pId->pCurrentContextEnv) &&
rEnvTypeName.equalsAsciiL(
RTL_CONSTASCII_STRINGPARAM(CPPU_CURRENT_LANGUAGE_BINDING_NAME) ) &&
(0 == pEnvContext))
{
reinterpret_cast< ::cppu::XInterface * >( pId->pCurrentContext )->acquire();
*ppCurrentContext = pId->pCurrentContext;
return sal_True;
}
// case: same env (!= current compiler env)
if ((0 != pId->pCurrentContextEnv) &&
(0 == ::rtl_ustr_compare(
((uno_Environment *) pId->pCurrentContextEnv)->pTypeName->buffer,
pEnvTypeName->buffer )) &&
((uno_Environment *) pId->pCurrentContextEnv)->pContext == pEnvContext)
{
// target env == current env
(*pId->pCurrentContextEnv->acquireInterface)(
pId->pCurrentContextEnv, pId->pCurrentContext );
*ppCurrentContext = pId->pCurrentContext;
return sal_True;
}
// else: mapping needed
if (! target_env.is())
{
uno_getEnvironment( (uno_Environment **) &target_env, pEnvTypeName, pEnvContext );
OSL_ASSERT( target_env.is() );
if (! target_env.is())
return sal_False;
}
::com::sun::star::uno::Environment source_env;
uno_Environment * p_source_env = (uno_Environment *) pId->pCurrentContextEnv;
if (0 == p_source_env)
{
OUString current_env_name(
RTL_CONSTASCII_USTRINGPARAM(CPPU_CURRENT_LANGUAGE_BINDING_NAME) );
uno_getEnvironment( (uno_Environment **) &source_env, current_env_name.pData, 0 );
OSL_ASSERT( source_env.is() );
if (! source_env.is())
return sal_False;
p_source_env = source_env.get();
}
uno_Mapping * mapping = 0;
uno_getMapping( &mapping, p_source_env, target_env.get(), 0 );
OSL_ASSERT( mapping != 0 );
if (! mapping)
return sal_False;
(*mapping->mapInterface)(
mapping,
ppCurrentContext, pId->pCurrentContext, ::cppu::get_type_XCurrentContext() );
(*mapping->release)( mapping );
return sal_True;
}
<commit_msg>INTEGRATION: CWS pchfix02 (1.13.60); FILE MERGED 2006/09/01 17:23:01 kaib 1.13.60.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: current.cxx,v $
*
* $Revision: 1.14 $
*
* last change: $Author: obo $ $Date: 2006-09-17 00:19:17 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_cppu.hxx"
#include "rtl/uuid.h"
#include "osl/thread.h"
#include "osl/mutex.hxx"
#include "uno/environment.hxx"
#include "uno/mapping.h"
#include "uno/lbnames.h"
#include "typelib/typedescription.h"
#include "current.hxx"
using namespace ::osl;
using namespace ::rtl;
using namespace ::cppu;
using namespace ::com::sun::star::uno;
namespace cppu
{
//--------------------------------------------------------------------------------------------------
class SAL_NO_VTABLE XInterface
{
public:
virtual void SAL_CALL slot_queryInterface() = 0;
virtual void SAL_CALL acquire() throw () = 0;
virtual void SAL_CALL release() throw () = 0;
};
//--------------------------------------------------------------------------------------------------
static typelib_InterfaceTypeDescription * get_type_XCurrentContext()
{
static typelib_InterfaceTypeDescription * s_type_XCurrentContext = 0;
if (0 == s_type_XCurrentContext)
{
::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );
if (0 == s_type_XCurrentContext)
{
OUString sTypeName( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.uno.XCurrentContext") );
typelib_InterfaceTypeDescription * pTD = 0;
typelib_TypeDescriptionReference * pMembers[1] = { 0 };
OUString sMethodName0(
RTL_CONSTASCII_USTRINGPARAM("com.sun.star.uno.XCurrentContext::getValueByName") );
typelib_typedescriptionreference_new(
&pMembers[0],
typelib_TypeClass_INTERFACE_METHOD,
sMethodName0.pData );
typelib_typedescription_newInterface(
&pTD,
sTypeName.pData, 0x00000000, 0x0000, 0x0000, 0x00000000, 0x00000000,
* typelib_static_type_getByTypeClass( typelib_TypeClass_INTERFACE ),
1,
pMembers );
typelib_typedescription_register( (typelib_TypeDescription**)&pTD );
typelib_typedescriptionreference_release( pMembers[0] );
typelib_InterfaceMethodTypeDescription * pMethod = 0;
typelib_Parameter_Init aParameters[1];
OUString sParamName0( RTL_CONSTASCII_USTRINGPARAM("Name") );
OUString sParamType0( RTL_CONSTASCII_USTRINGPARAM("string") );
aParameters[0].pParamName = sParamName0.pData;
aParameters[0].eTypeClass = typelib_TypeClass_STRING;
aParameters[0].pTypeName = sParamType0.pData;
aParameters[0].bIn = sal_True;
aParameters[0].bOut = sal_False;
rtl_uString * pExceptions[1];
OUString sExceptionName0(
RTL_CONSTASCII_USTRINGPARAM("com.sun.star.uno.RuntimeException") );
pExceptions[0] = sExceptionName0.pData;
OUString sReturnType0( RTL_CONSTASCII_USTRINGPARAM("any") );
typelib_typedescription_newInterfaceMethod(
&pMethod,
3, sal_False,
sMethodName0.pData,
typelib_TypeClass_ANY, sReturnType0.pData,
1, aParameters, 1, pExceptions );
typelib_typedescription_register( (typelib_TypeDescription**)&pMethod );
typelib_typedescription_release( (typelib_TypeDescription*)pMethod );
#if ! defined CPPU_LEAK_STATIC_DATA
// another static ref
++reinterpret_cast< typelib_TypeDescription * >( pTD )->
nStaticRefCount;
#endif
s_type_XCurrentContext = pTD;
}
}
return s_type_XCurrentContext;
}
//##################################################################################################
//==================================================================================================
class ThreadKey
{
sal_Bool _bInit;
oslThreadKey _hThreadKey;
oslThreadKeyCallbackFunction _pCallback;
public:
inline oslThreadKey getThreadKey() SAL_THROW( () );
inline ThreadKey( oslThreadKeyCallbackFunction pCallback ) SAL_THROW( () );
inline ~ThreadKey() SAL_THROW( () );
};
//__________________________________________________________________________________________________
inline ThreadKey::ThreadKey( oslThreadKeyCallbackFunction pCallback ) SAL_THROW( () )
: _bInit( sal_False )
, _pCallback( pCallback )
{
}
//__________________________________________________________________________________________________
inline ThreadKey::~ThreadKey() SAL_THROW( () )
{
if (_bInit)
{
::osl_destroyThreadKey( _hThreadKey );
}
}
//__________________________________________________________________________________________________
inline oslThreadKey ThreadKey::getThreadKey() SAL_THROW( () )
{
if (! _bInit)
{
MutexGuard aGuard( Mutex::getGlobalMutex() );
if (! _bInit)
{
_hThreadKey = ::osl_createThreadKey( _pCallback );
_bInit = sal_True;
}
}
return _hThreadKey;
}
//==================================================================================================
extern "C" void SAL_CALL delete_IdContainer( void * p )
{
if (p)
{
IdContainer * pId = reinterpret_cast< IdContainer * >( p );
if (pId->pCurrentContext)
{
if (pId->pCurrentContextEnv)
{
(*pId->pCurrentContextEnv->releaseInterface)(
pId->pCurrentContextEnv, pId->pCurrentContext );
(*((uno_Environment *)pId->pCurrentContextEnv)->release)(
(uno_Environment *)pId->pCurrentContextEnv );
}
else // current compiler used for context interface implementation
{
reinterpret_cast< ::cppu::XInterface * >( pId->pCurrentContext )->release();
}
}
if (pId->bInit)
{
::rtl_byte_sequence_release( pId->pLocalThreadId );
::rtl_byte_sequence_release( pId->pCurrentId );
}
delete pId;
}
}
//==================================================================================================
IdContainer * getIdContainer() SAL_THROW( () )
{
static ThreadKey s_key( delete_IdContainer );
oslThreadKey aKey = s_key.getThreadKey();
IdContainer * pId = reinterpret_cast< IdContainer * >( ::osl_getThreadKeyData( aKey ) );
if (! pId)
{
pId = new IdContainer();
pId->pCurrentContext = 0;
pId->pCurrentContextEnv = 0;
pId->bInit = sal_False;
::osl_setThreadKeyData( aKey, pId );
}
return pId;
}
}
//##################################################################################################
extern "C" sal_Bool SAL_CALL uno_setCurrentContext(
void * pCurrentContext,
rtl_uString * pEnvTypeName, void * pEnvContext )
SAL_THROW_EXTERN_C()
{
IdContainer * pId = getIdContainer();
OSL_ASSERT( pId );
// free old one
if (pId->pCurrentContext)
{
if (pId->pCurrentContextEnv)
{
(*pId->pCurrentContextEnv->releaseInterface)(
pId->pCurrentContextEnv, pId->pCurrentContext );
(*((uno_Environment *)pId->pCurrentContextEnv)->release)(
(uno_Environment *)pId->pCurrentContextEnv );
pId->pCurrentContextEnv = 0;
}
else // current compiler used for context interface implementation
{
reinterpret_cast< ::cppu::XInterface * >( pId->pCurrentContext )->release();
}
pId->pCurrentContext = 0;
}
if (pCurrentContext)
{
OUString const & rEnvTypeName = * reinterpret_cast< OUString const * >( &pEnvTypeName );
if (rEnvTypeName.equalsAsciiL(
RTL_CONSTASCII_STRINGPARAM(CPPU_CURRENT_LANGUAGE_BINDING_NAME) ))
{
reinterpret_cast< ::cppu::XInterface * >( pCurrentContext )->acquire();
pId->pCurrentContext = pCurrentContext;
pId->pCurrentContextEnv = 0; // special for this compiler env
}
else
{
uno_Environment * pEnv = 0;
::uno_getEnvironment( &pEnv, pEnvTypeName, pEnvContext );
OSL_ASSERT( pEnv && pEnv->pExtEnv );
if (pEnv)
{
if (pEnv->pExtEnv)
{
pId->pCurrentContextEnv = pEnv->pExtEnv;
(*pId->pCurrentContextEnv->acquireInterface)(
pId->pCurrentContextEnv, pCurrentContext );
pId->pCurrentContext = pCurrentContext;
}
else
{
(*pEnv->release)( pEnv );
return sal_False;
}
}
else
{
return sal_False;
}
}
}
return sal_True;
}
//##################################################################################################
extern "C" sal_Bool SAL_CALL uno_getCurrentContext(
void ** ppCurrentContext, rtl_uString * pEnvTypeName, void * pEnvContext )
SAL_THROW_EXTERN_C()
{
IdContainer * pId = getIdContainer();
OSL_ASSERT( pId );
::com::sun::star::uno::Environment target_env;
OUString const & rEnvTypeName = * reinterpret_cast< OUString const * >( &pEnvTypeName );
// release inout parameter
if (*ppCurrentContext)
{
if (rEnvTypeName.equalsAsciiL(
RTL_CONSTASCII_STRINGPARAM(CPPU_CURRENT_LANGUAGE_BINDING_NAME) ))
{
reinterpret_cast< ::cppu::XInterface * >( *ppCurrentContext )->release();
}
else
{
uno_getEnvironment( (uno_Environment **) &target_env, pEnvTypeName, pEnvContext );
OSL_ASSERT( target_env.is() );
if (! target_env.is())
return sal_False;
uno_ExtEnvironment * pEnv = target_env.get()->pExtEnv;
OSL_ASSERT( 0 != pEnv );
if (0 == pEnv)
return sal_False;
(*pEnv->releaseInterface)( pEnv, *ppCurrentContext );
}
*ppCurrentContext = 0;
}
// case: null-ref
if (0 == pId->pCurrentContext)
return sal_True;
// case: same env (current compiler env)
if ((0 == pId->pCurrentContextEnv) &&
rEnvTypeName.equalsAsciiL(
RTL_CONSTASCII_STRINGPARAM(CPPU_CURRENT_LANGUAGE_BINDING_NAME) ) &&
(0 == pEnvContext))
{
reinterpret_cast< ::cppu::XInterface * >( pId->pCurrentContext )->acquire();
*ppCurrentContext = pId->pCurrentContext;
return sal_True;
}
// case: same env (!= current compiler env)
if ((0 != pId->pCurrentContextEnv) &&
(0 == ::rtl_ustr_compare(
((uno_Environment *) pId->pCurrentContextEnv)->pTypeName->buffer,
pEnvTypeName->buffer )) &&
((uno_Environment *) pId->pCurrentContextEnv)->pContext == pEnvContext)
{
// target env == current env
(*pId->pCurrentContextEnv->acquireInterface)(
pId->pCurrentContextEnv, pId->pCurrentContext );
*ppCurrentContext = pId->pCurrentContext;
return sal_True;
}
// else: mapping needed
if (! target_env.is())
{
uno_getEnvironment( (uno_Environment **) &target_env, pEnvTypeName, pEnvContext );
OSL_ASSERT( target_env.is() );
if (! target_env.is())
return sal_False;
}
::com::sun::star::uno::Environment source_env;
uno_Environment * p_source_env = (uno_Environment *) pId->pCurrentContextEnv;
if (0 == p_source_env)
{
OUString current_env_name(
RTL_CONSTASCII_USTRINGPARAM(CPPU_CURRENT_LANGUAGE_BINDING_NAME) );
uno_getEnvironment( (uno_Environment **) &source_env, current_env_name.pData, 0 );
OSL_ASSERT( source_env.is() );
if (! source_env.is())
return sal_False;
p_source_env = source_env.get();
}
uno_Mapping * mapping = 0;
uno_getMapping( &mapping, p_source_env, target_env.get(), 0 );
OSL_ASSERT( mapping != 0 );
if (! mapping)
return sal_False;
(*mapping->mapInterface)(
mapping,
ppCurrentContext, pId->pCurrentContext, ::cppu::get_type_XCurrentContext() );
(*mapping->release)( mapping );
return sal_True;
}
<|endoftext|>
|
<commit_before>/*
* Copyright 2004-2014 Cray Inc.
* Other additional copyright holders may be indicated within.
*
* The entirety of this work is 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 "optimizations.h"
#include "astutil.h"
#include "bb.h"
#include "expr.h"
#include "passes.h"
#include "stlUtil.h"
#include "stmt.h"
#include "view.h"
#include <queue>
#include <set>
//
// Static function declarations.
//
static void deadBlockElimination(FnSymbol* fn);
static void postPassCleanup();
// Static variables.
static unsigned int deadBlockCount;
static unsigned int deadModuleCount;
// Determines if an expr is used inside of the header for a c for loop. c for
// loop header is of the form '"c for loop" {inits}, {test}, {incrs}'
//
// Only returns true for exprs in the init, test, incr blocks, not for the
// blocks themselves.
//
// TODO should this be updated to only look for exprs in the test segment that
// are conditional primitives?
static bool isInCForLoopHeader(Expr* expr) {
if (expr->parentExpr && expr->parentExpr->parentExpr) {
if (CallExpr* call = toCallExpr(expr->parentExpr->parentExpr)) {
if (call->isPrimitive(PRIM_BLOCK_C_FOR_LOOP)) {
return true;
}
}
}
return false;
}
//
// Removes local variables that are only targets for moves, but are
// never used anywhere.
//
static bool isDeadVariable(Symbol* var,
Map<Symbol*,Vec<SymExpr*>*>& defMap,
Map<Symbol*,Vec<SymExpr*>*>& useMap) {
if (var->type->symbol->hasFlag(FLAG_REF)) {
Vec<SymExpr*>* uses = useMap.get(var);
Vec<SymExpr*>* defs = defMap.get(var);
return (!uses || uses->n == 0) && (!defs || defs->n <= 1);
} else {
Vec<SymExpr*>* uses = useMap.get(var);
return !uses || uses->n == 0;
}
}
void deadVariableElimination(FnSymbol* fn) {
Vec<Symbol*> symSet;
Vec<SymExpr*> symExprs;
collectSymbolSetSymExprVec(fn, symSet, symExprs);
Map<Symbol*,Vec<SymExpr*>*> defMap;
Map<Symbol*,Vec<SymExpr*>*> useMap;
buildDefUseMaps(symSet, symExprs, defMap, useMap);
forv_Vec(Symbol, sym, symSet)
{
// We're interested only in VarSymbols.
if (!isVarSymbol(sym))
continue;
// A method must have a _this symbol, even if it is not used.
if (sym == fn->_this)
continue;
if (isDeadVariable(sym, defMap, useMap)) {
for_defs(se, defMap, sym) {
CallExpr* call = toCallExpr(se->parentExpr);
INT_ASSERT(call &&
(call->isPrimitive(PRIM_MOVE) ||
call->isPrimitive(PRIM_ASSIGN)));
Expr* rhs = call->get(2)->remove();
if (!isSymExpr(rhs))
call->replace(rhs);
else
call->remove();
}
sym->defPoint->remove();
}
}
freeDefUseMaps(defMap, useMap);
}
//
// Removes expression statements that have no effect.
//
void deadExpressionElimination(FnSymbol* fn) {
Vec<BaseAST*> asts;
collect_asts(fn, asts);
forv_Vec(BaseAST, ast, asts) {
Expr *expr = toExpr(ast);
if (expr && expr->parentExpr == NULL) // expression already removed
continue;
if (SymExpr* expr = toSymExpr(ast)) {
if (isInCForLoopHeader(expr)) {
continue;
}
if (expr == expr->getStmtExpr())
expr->remove();
} else if (CallExpr* expr = toCallExpr(ast)) {
if (expr->isPrimitive(PRIM_CAST) ||
expr->isPrimitive(PRIM_GET_MEMBER_VALUE) ||
expr->isPrimitive(PRIM_GET_MEMBER) ||
expr->isPrimitive(PRIM_DEREF) ||
expr->isPrimitive(PRIM_ADDR_OF))
if (expr == expr->getStmtExpr())
expr->remove();
if (expr->isPrimitive(PRIM_MOVE) || expr->isPrimitive(PRIM_ASSIGN))
if (SymExpr* lhs = toSymExpr(expr->get(1)))
if (SymExpr* rhs = toSymExpr(expr->get(2)))
if (lhs->var == rhs->var)
expr->remove();
} else if (CondStmt* cond = toCondStmt(ast)) {
cond->fold_cond_stmt();
}
}
}
void deadCodeElimination(FnSymbol* fn)
{
// TODO: Factor this long function?
buildBasicBlocks(fn);
std::map<SymExpr*,Vec<SymExpr*>*> DU;
std::map<SymExpr*,Vec<SymExpr*>*> UD;
buildDefUseChains(fn, DU, UD);
std::map<Expr*,Expr*> exprMap;
Vec<Expr*> liveCode;
Vec<Expr*> workSet;
for_vector(BasicBlock, bb, *fn->basicBlocks) {
for_vector(Expr, expr, bb->exprs) {
bool essential = false;
Vec<BaseAST*> asts;
collect_asts(expr, asts);
forv_Vec(BaseAST, ast, asts) {
if (isInCForLoopHeader(expr)) {
essential = true;
}
if (CallExpr* call = toCallExpr(ast)) {
// mark function calls and essential primitives as essential
if (call->isResolved() ||
(call->primitive && call->primitive->isEssential))
essential = true;
// mark assignments to global variables as essential
if (call->isPrimitive(PRIM_MOVE) || call->isPrimitive(PRIM_ASSIGN))
if (SymExpr* se = toSymExpr(call->get(1)))
if (DU.count(se) == 0 || // DU chain only contains locals
!se->var->type->refType) // reference issue
essential = true;
}
if (Expr* sub = toExpr(ast)) {
exprMap[sub] = expr;
if (BlockStmt* block = toBlockStmt(sub->parentExpr))
if (block->blockInfoGet() == sub)
essential = true;
if (CondStmt* cond = toCondStmt(sub->parentExpr))
if (cond->condExpr == sub)
essential = true;
}
}
if (essential) {
liveCode.set_add(expr);
workSet.add(expr);
}
}
}
forv_Vec(Expr, expr, workSet) {
Vec<SymExpr*> symExprs;
collectSymExprs(expr, symExprs);
forv_Vec(SymExpr, se, symExprs) {
if (UD.count(se) != 0) {
Vec<SymExpr*>* defs = UD[se];
forv_Vec(SymExpr, def, *defs) {
INT_ASSERT(exprMap.count(def) != 0);
Expr* expr = exprMap[def];
if (!liveCode.set_in(expr)) {
liveCode.set_add(expr);
workSet.add(expr);
}
}
}
}
}
// This removes dead expressions from each block.
for_vector(BasicBlock, bb1, *fn->basicBlocks) {
for_vector(Expr, expr, bb1->exprs) {
if (isSymExpr(expr) || isCallExpr(expr))
if (!liveCode.set_in(expr))
expr->remove();
}
}
freeDefUseChains(DU, UD);
}
// Determines if a module is dead. A module is dead if the module's init
// function can only be called from module code, and the init function
// is empty, and the init function is the only thing in the module, and the
// module is not a nested module.
static bool isDeadModule(ModuleSymbol* mod) {
// The main module and any module whose init function is exported
// should never be considered dead, as the init function can be
// explicitly called from the runtime, or other c code
if (mod == mainModule || mod->hasFlag(FLAG_EXPORT_INIT)) return false;
// because of the way modules are initialized, we don't want to consider a
// nested function as dead as its outer module and all of its uses should
// have their initializer called by the inner module.
if (mod->defPoint->getModule() != theProgram &&
mod->defPoint->getModule() != rootModule)
return false;
// if there is only one thing in the module
if (mod->block->body.length == 1) {
// and that thing is the init function
if (mod->block->body.only() == mod->initFn->defPoint) {
// and the init function is empty (only has a return)
if (mod->initFn->body->body.length == 1) {
// then the module is dead
return true;
}
}
}
return false;
}
// Eliminates all dead modules
static void deadModuleElimination() {
forv_Vec(ModuleSymbol, mod, allModules) {
if (isDeadModule(mod) == true) {
deadModuleCount++;
// remove the dead module and its initFn
mod->defPoint->remove();
mod->initFn->defPoint->remove();
// Inform every module about the dead module
forv_Vec(ModuleSymbol, modThatMightUse, allModules) {
if (modThatMightUse != mod) {
modThatMightUse->moduleUseRemove(mod);
}
}
}
}
}
void deadCodeElimination() {
if (!fNoDeadCodeElimination) {
deadBlockCount = 0;
deadModuleCount = 0;
forv_Vec(FnSymbol, fn, gFnSymbols) {
deadBlockElimination(fn);
deadCodeElimination(fn);
deadVariableElimination(fn);
deadExpressionElimination(fn);
}
deadModuleElimination();
postPassCleanup();
if (fReportDeadBlocks)
printf("\tRemoved %d dead blocks.\n", deadBlockCount);
if (fReportDeadModules)
printf("Removed %d dead modules.\n", deadModuleCount);
}
}
// Look for and remove unreachable blocks.
// Muchnick says we can enumerate the unreachable blocks first and then just
// remove them. We only need to do this once, because removal of an
// unreachable block cannot possibly make any reachable block unreachable.
static void deadBlockElimination(FnSymbol* fn)
{
// We need the basic block information to be correct, so recompute it.
buildBasicBlocks(fn);
// Find the reachable basic blocks within this function.
std::set<BasicBlock*> reachable;
// We set up a work queue to perform a BFS on reachable blocks, and seed it
// with the first block in the function.
std::queue<BasicBlock*> work_queue;
work_queue.push((*fn->basicBlocks)[0]);
// Then we iterate until there are no more blocks to visit.
while (!work_queue.empty())
{
// Fetch and remove the next block.
BasicBlock* bb = work_queue.front();
work_queue.pop();
// Ignore it if we've already seen it.
if (reachable.count(bb))
continue;
// Otherwise, mark it as reachable, and append all of its successors to the
// work queue.
reachable.insert(bb);
for_vector(BasicBlock, out, bb->outs)
work_queue.push(out);
}
// Now we simply visit all the blocks, deleting all those that are not
// rechable.
for_vector(BasicBlock, bb, *fn->basicBlocks)
{
if (reachable.count(bb))
continue;
++deadBlockCount;
// Remove all of its expressions.
for_vector(Expr, expr, bb->exprs)
{
if (! expr->parentExpr)
continue; // This node is no longer in the tree.
// Do not remove def expressions (for now)
// In some cases (associated with iterator code), defs appear in dead
// blocks but are used in later blocks, so removing the defs results
// in a verify error.
// TODO: Perhaps this reformulation of unreachable block removal does a better
// job and those blocks are now removed as well. If so, this IF can be removed.
if (toDefExpr(expr))
continue;
CondStmt* cond = toCondStmt(expr->parentExpr);
if (cond && cond->condExpr == expr)
// If expr is the condition expression in an if statement,
// then remove the entire if.
cond->remove();
else
expr->remove();
}
}
}
//
// See if any iterator resume labels have been remove (and not re-inserted).
// If so, remove the matching gotos, if they haven't been yet.
//
void removeDeadIterResumeGotos() {
forv_Vec(LabelSymbol, labsym, removedIterResumeLabels) {
if (!isAlive(labsym) && isAlive(labsym->iterResumeGoto))
labsym->iterResumeGoto->remove();
}
removedIterResumeLabels.clear();
}
//
// Make sure there are no iterResumeGotos to remove.
// Reset removedIterResumeLabels.
//
void verifyNcleanRemovedIterResumeGotos() {
forv_Vec(LabelSymbol, labsym, removedIterResumeLabels) {
if (!isAlive(labsym) && isAlive(labsym->iterResumeGoto))
INT_FATAL("unexpected live goto for a dead removedIterResumeLabels label - missing a call to removeDeadIterResumeGotos?");
}
removedIterResumeLabels.clear();
}
//
// Dead code elimination can create a handful of degenerate nodes.
// This is a place to sweep those away.
//
static void postPassCleanup() {
// Remove degenerate C-For loops. These could be misinterpreted
// as Infinite loops and currently break the LLVM backend
forv_Vec(BlockStmt, stmt, gBlockStmts) {
if (CallExpr* loop = stmt->blockInfoGet()) {
if (loop->isPrimitive(PRIM_BLOCK_C_FOR_LOOP)) {
if (BlockStmt* test = toBlockStmt(loop->get(2))) {
if (test->body.length == 0) {
stmt->remove();
}
}
}
}
}
}
// Look for pointless gotos and remove them.
// Probably the best way to do this is to scan the AST and remove gotos
// whose target labels follow immediately.
#if 0
static void deadGotoElimination(FnSymbol* fn)
{
// We recompute basic blocks because deadBlockElimination may cause them
// to be out of sequence.
buildBasicBlocks(fn);
forv_Vec(BasicBlock, bb, *fn->basicBlocks)
{
// Get the last expression in the block as a goto.
int last = bb->exprs.length() - 1;
if (last < 0)
continue;
Expr* e = bb->exprs.v[last];
GotoStmt* s = toGotoStmt(e);
if (!s)
continue;
// If there is only one successor to this block and it is the next block,
// then the goto must point to it and is therefore pointless [sts].
// This test should be more foolproof using the structure of the AST.
if (bb->outs.n == 1 && bb->outs.v[0]->id == bb->id + 1)
e->remove();
}
}
#endif
<commit_msg>Perform C-For loop cleanup after every Function<commit_after>/*
* Copyright 2004-2014 Cray Inc.
* Other additional copyright holders may be indicated within.
*
* The entirety of this work is 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 "optimizations.h"
#include "astutil.h"
#include "bb.h"
#include "expr.h"
#include "passes.h"
#include "stlUtil.h"
#include "stmt.h"
#include "view.h"
#include <queue>
#include <set>
//
// Static function declarations.
//
static void deadBlockElimination(FnSymbol* fn);
static void cleanupCForLoopBlocks(FnSymbol* fn);
// Static variables.
static unsigned deadBlockCount;
static unsigned deadModuleCount;
// Determines if an expr is used inside of the header for a c for loop. c for
// loop header is of the form '"c for loop" {inits}, {test}, {incrs}'
//
// Only returns true for exprs in the init, test, incr blocks, not for the
// blocks themselves.
//
// TODO should this be updated to only look for exprs in the test segment that
// are conditional primitives?
static bool isInCForLoopHeader(Expr* expr) {
if (expr->parentExpr && expr->parentExpr->parentExpr) {
if (CallExpr* call = toCallExpr(expr->parentExpr->parentExpr)) {
if (call->isPrimitive(PRIM_BLOCK_C_FOR_LOOP)) {
return true;
}
}
}
return false;
}
//
// Removes local variables that are only targets for moves, but are
// never used anywhere.
//
static bool isDeadVariable(Symbol* var,
Map<Symbol*,Vec<SymExpr*>*>& defMap,
Map<Symbol*,Vec<SymExpr*>*>& useMap) {
if (var->type->symbol->hasFlag(FLAG_REF)) {
Vec<SymExpr*>* uses = useMap.get(var);
Vec<SymExpr*>* defs = defMap.get(var);
return (!uses || uses->n == 0) && (!defs || defs->n <= 1);
} else {
Vec<SymExpr*>* uses = useMap.get(var);
return !uses || uses->n == 0;
}
}
void deadVariableElimination(FnSymbol* fn) {
Vec<Symbol*> symSet;
Vec<SymExpr*> symExprs;
collectSymbolSetSymExprVec(fn, symSet, symExprs);
Map<Symbol*,Vec<SymExpr*>*> defMap;
Map<Symbol*,Vec<SymExpr*>*> useMap;
buildDefUseMaps(symSet, symExprs, defMap, useMap);
forv_Vec(Symbol, sym, symSet)
{
// We're interested only in VarSymbols.
if (!isVarSymbol(sym))
continue;
// A method must have a _this symbol, even if it is not used.
if (sym == fn->_this)
continue;
if (isDeadVariable(sym, defMap, useMap)) {
for_defs(se, defMap, sym) {
CallExpr* call = toCallExpr(se->parentExpr);
INT_ASSERT(call &&
(call->isPrimitive(PRIM_MOVE) ||
call->isPrimitive(PRIM_ASSIGN)));
Expr* rhs = call->get(2)->remove();
if (!isSymExpr(rhs))
call->replace(rhs);
else
call->remove();
}
sym->defPoint->remove();
}
}
freeDefUseMaps(defMap, useMap);
}
//
// Removes expression statements that have no effect.
//
void deadExpressionElimination(FnSymbol* fn) {
Vec<BaseAST*> asts;
collect_asts(fn, asts);
forv_Vec(BaseAST, ast, asts) {
Expr *expr = toExpr(ast);
if (expr && expr->parentExpr == NULL) // expression already removed
continue;
if (SymExpr* expr = toSymExpr(ast)) {
if (isInCForLoopHeader(expr)) {
continue;
}
if (expr == expr->getStmtExpr())
expr->remove();
} else if (CallExpr* expr = toCallExpr(ast)) {
if (expr->isPrimitive(PRIM_CAST) ||
expr->isPrimitive(PRIM_GET_MEMBER_VALUE) ||
expr->isPrimitive(PRIM_GET_MEMBER) ||
expr->isPrimitive(PRIM_DEREF) ||
expr->isPrimitive(PRIM_ADDR_OF))
if (expr == expr->getStmtExpr())
expr->remove();
if (expr->isPrimitive(PRIM_MOVE) || expr->isPrimitive(PRIM_ASSIGN))
if (SymExpr* lhs = toSymExpr(expr->get(1)))
if (SymExpr* rhs = toSymExpr(expr->get(2)))
if (lhs->var == rhs->var)
expr->remove();
} else if (CondStmt* cond = toCondStmt(ast)) {
cond->fold_cond_stmt();
}
}
}
void deadCodeElimination(FnSymbol* fn)
{
// TODO: Factor this long function?
buildBasicBlocks(fn);
std::map<SymExpr*,Vec<SymExpr*>*> DU;
std::map<SymExpr*,Vec<SymExpr*>*> UD;
buildDefUseChains(fn, DU, UD);
std::map<Expr*,Expr*> exprMap;
Vec<Expr*> liveCode;
Vec<Expr*> workSet;
for_vector(BasicBlock, bb, *fn->basicBlocks) {
for_vector(Expr, expr, bb->exprs) {
bool essential = false;
Vec<BaseAST*> asts;
collect_asts(expr, asts);
forv_Vec(BaseAST, ast, asts) {
if (isInCForLoopHeader(expr)) {
essential = true;
}
if (CallExpr* call = toCallExpr(ast)) {
// mark function calls and essential primitives as essential
if (call->isResolved() ||
(call->primitive && call->primitive->isEssential))
essential = true;
// mark assignments to global variables as essential
if (call->isPrimitive(PRIM_MOVE) || call->isPrimitive(PRIM_ASSIGN))
if (SymExpr* se = toSymExpr(call->get(1)))
if (DU.count(se) == 0 || // DU chain only contains locals
!se->var->type->refType) // reference issue
essential = true;
}
if (Expr* sub = toExpr(ast)) {
exprMap[sub] = expr;
if (BlockStmt* block = toBlockStmt(sub->parentExpr))
if (block->blockInfoGet() == sub)
essential = true;
if (CondStmt* cond = toCondStmt(sub->parentExpr))
if (cond->condExpr == sub)
essential = true;
}
}
if (essential) {
liveCode.set_add(expr);
workSet.add(expr);
}
}
}
forv_Vec(Expr, expr, workSet) {
Vec<SymExpr*> symExprs;
collectSymExprs(expr, symExprs);
forv_Vec(SymExpr, se, symExprs) {
if (UD.count(se) != 0) {
Vec<SymExpr*>* defs = UD[se];
forv_Vec(SymExpr, def, *defs) {
INT_ASSERT(exprMap.count(def) != 0);
Expr* expr = exprMap[def];
if (!liveCode.set_in(expr)) {
liveCode.set_add(expr);
workSet.add(expr);
}
}
}
}
}
// This removes dead expressions from each block.
for_vector(BasicBlock, bb1, *fn->basicBlocks) {
for_vector(Expr, expr, bb1->exprs) {
if (isSymExpr(expr) || isCallExpr(expr))
if (!liveCode.set_in(expr))
expr->remove();
}
}
freeDefUseChains(DU, UD);
}
// Determines if a module is dead. A module is dead if the module's init
// function can only be called from module code, and the init function
// is empty, and the init function is the only thing in the module, and the
// module is not a nested module.
static bool isDeadModule(ModuleSymbol* mod) {
// The main module and any module whose init function is exported
// should never be considered dead, as the init function can be
// explicitly called from the runtime, or other c code
if (mod == mainModule || mod->hasFlag(FLAG_EXPORT_INIT)) return false;
// because of the way modules are initialized, we don't want to consider a
// nested function as dead as its outer module and all of its uses should
// have their initializer called by the inner module.
if (mod->defPoint->getModule() != theProgram &&
mod->defPoint->getModule() != rootModule)
return false;
// if there is only one thing in the module
if (mod->block->body.length == 1) {
// and that thing is the init function
if (mod->block->body.only() == mod->initFn->defPoint) {
// and the init function is empty (only has a return)
if (mod->initFn->body->body.length == 1) {
// then the module is dead
return true;
}
}
}
return false;
}
// Eliminates all dead modules
static void deadModuleElimination() {
forv_Vec(ModuleSymbol, mod, allModules) {
if (isDeadModule(mod) == true) {
deadModuleCount++;
// remove the dead module and its initFn
mod->defPoint->remove();
mod->initFn->defPoint->remove();
// Inform every module about the dead module
forv_Vec(ModuleSymbol, modThatMightUse, allModules) {
if (modThatMightUse != mod) {
modThatMightUse->moduleUseRemove(mod);
}
}
}
}
}
void deadCodeElimination() {
if (!fNoDeadCodeElimination) {
deadBlockCount = 0;
deadModuleCount = 0;
forv_Vec(FnSymbol, fn, gFnSymbols) {
deadBlockElimination(fn);
deadCodeElimination(fn);
deadVariableElimination(fn);
deadExpressionElimination(fn);
cleanupCForLoopBlocks(fn);
}
deadModuleElimination();
if (fReportDeadBlocks)
printf("\tRemoved %d dead blocks.\n", deadBlockCount);
if (fReportDeadModules)
printf("Removed %d dead modules.\n", deadModuleCount);
}
}
// Look for and remove unreachable blocks.
// Muchnick says we can enumerate the unreachable blocks first and then just
// remove them. We only need to do this once, because removal of an
// unreachable block cannot possibly make any reachable block unreachable.
static void deadBlockElimination(FnSymbol* fn)
{
// We need the basic block information to be correct, so recompute it.
buildBasicBlocks(fn);
// Find the reachable basic blocks within this function.
std::set<BasicBlock*> reachable;
// We set up a work queue to perform a BFS on reachable blocks, and seed it
// with the first block in the function.
std::queue<BasicBlock*> work_queue;
work_queue.push((*fn->basicBlocks)[0]);
// Then we iterate until there are no more blocks to visit.
while (!work_queue.empty())
{
// Fetch and remove the next block.
BasicBlock* bb = work_queue.front();
work_queue.pop();
// Ignore it if we've already seen it.
if (reachable.count(bb))
continue;
// Otherwise, mark it as reachable, and append all of its successors to the
// work queue.
reachable.insert(bb);
for_vector(BasicBlock, out, bb->outs)
work_queue.push(out);
}
// Now we simply visit all the blocks, deleting all those that are not
// rechable.
for_vector(BasicBlock, bb, *fn->basicBlocks)
{
if (reachable.count(bb))
continue;
++deadBlockCount;
// Remove all of its expressions.
for_vector(Expr, expr, bb->exprs)
{
if (! expr->parentExpr)
continue; // This node is no longer in the tree.
// Do not remove def expressions (for now)
// In some cases (associated with iterator code), defs appear in dead
// blocks but are used in later blocks, so removing the defs results
// in a verify error.
// TODO: Perhaps this reformulation of unreachable block removal does a better
// job and those blocks are now removed as well. If so, this IF can be removed.
if (toDefExpr(expr))
continue;
CondStmt* cond = toCondStmt(expr->parentExpr);
if (cond && cond->condExpr == expr)
// If expr is the condition expression in an if statement,
// then remove the entire if.
cond->remove();
else
expr->remove();
}
}
}
//
// See if any iterator resume labels have been remove (and not re-inserted).
// If so, remove the matching gotos, if they haven't been yet.
//
void removeDeadIterResumeGotos() {
forv_Vec(LabelSymbol, labsym, removedIterResumeLabels) {
if (!isAlive(labsym) && isAlive(labsym->iterResumeGoto))
labsym->iterResumeGoto->remove();
}
removedIterResumeLabels.clear();
}
//
// Make sure there are no iterResumeGotos to remove.
// Reset removedIterResumeLabels.
//
void verifyNcleanRemovedIterResumeGotos() {
forv_Vec(LabelSymbol, labsym, removedIterResumeLabels) {
if (!isAlive(labsym) && isAlive(labsym->iterResumeGoto))
INT_FATAL("unexpected live goto for a dead removedIterResumeLabels label - missing a call to removeDeadIterResumeGotos?");
}
removedIterResumeLabels.clear();
}
// 2014/10/15
//
//
// Dead code elimination can create a variety of degenerate statements.
// These include
//
// blockStmts with empty bodies
// condStmts with empty then and/or else clauses
// loops with empty bodies
//
// etc.
//
// Most of these are currently allowed to clutter the AST and are assumed
// to be cleaned up the by C compiler. There is an expectation that this
// will be improved in the future.
//
// Howevever it can lead to C-For loops where the body is empty and each
// of the loop clauses is an empty blockStmt. This logically corresponds
// to
//
// for ( ; ; ) {
// }
//
// which is technically valid C that would implement an infinite loop.
// However this AST causes a seg-fault in the LLVM code generator and
// so must be hacked out now.
//
static void cleanupCForLoopBlocks(FnSymbol* fn) {
std::vector<Expr*> stmts;
collect_stmts_STL(fn, stmts);
for (size_t i = 0; i < stmts.size(); i++) {
if (BlockStmt* stmt = toBlockStmt(stmts[i])) {
if (CallExpr* loop = stmt->blockInfoGet()) {
if (loop->isPrimitive(PRIM_BLOCK_C_FOR_LOOP)) {
if (BlockStmt* test = toBlockStmt(loop->get(2))) {
if (test->body.length == 0) {
stmt->remove();
}
}
}
}
}
}
}
// Look for pointless gotos and remove them.
// Probably the best way to do this is to scan the AST and remove gotos
// whose target labels follow immediately.
#if 0
static void deadGotoElimination(FnSymbol* fn)
{
// We recompute basic blocks because deadBlockElimination may cause them
// to be out of sequence.
buildBasicBlocks(fn);
forv_Vec(BasicBlock, bb, *fn->basicBlocks)
{
// Get the last expression in the block as a goto.
int last = bb->exprs.length() - 1;
if (last < 0)
continue;
Expr* e = bb->exprs.v[last];
GotoStmt* s = toGotoStmt(e);
if (!s)
continue;
// If there is only one successor to this block and it is the next block,
// then the goto must point to it and is therefore pointless [sts].
// This test should be more foolproof using the structure of the AST.
if (bb->outs.n == 1 && bb->outs.v[0]->id == bb->id + 1)
e->remove();
}
}
#endif
<|endoftext|>
|
<commit_before>// @(#)root/g3d:$Id$
// Author: Rene Brun 14/09/95
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#include "TVirtualPad.h"
#include "TNodeDiv.h"
ClassImp(TNodeDiv)
//______________________________________________________________________________
/* Begin_Html
<center><h2>The TNodeDiv class</h2></center>
Description of parameters to divide a 3-D geometry object.
End_Html */
//______________________________________________________________________________
TNodeDiv::TNodeDiv()
{
// NodeDiv default constructor.
fNdiv = 0;
fAxis = 0;
}
//______________________________________________________________________________
TNodeDiv::TNodeDiv(const char *name, const char *title, const char *shapename, Int_t ndiv, Int_t axis, Option_t *option)
:TNode(name,title,shapename,0,0,0,0,option)
{
// NodeDiv normal constructor.
//
// name is the name of the node
// title is title
// shapename is the name of the referenced shape
// x,y,z are the offsets of the volume with respect to his mother
// matrixname is the name of the rotation matrix
//
// This new node is added into the list of sons of the current node
fNdiv = ndiv;
fAxis = axis;
}
//______________________________________________________________________________
TNodeDiv::TNodeDiv(const char *name, const char *title, TShape *shape, Int_t ndiv, Int_t axis, Option_t *option)
:TNode(name,title,shape,0,0,0,0,option)
{
// NodeDiv normal constructor.
//
// name is the name of the node
// title is title
// shape is the pointer to the shape definition
// ndiv number of divisions
// axis number of the axis for the division
//
// This new node is added into the list of sons of the current node
fNdiv = ndiv;
fAxis = axis;
}
//______________________________________________________________________________
TNodeDiv::~TNodeDiv()
{
// NodeDiv default destructor.
}
//______________________________________________________________________________
void TNodeDiv::Draw(Option_t *)
{
// Draw Referenced node with current parameters.
}
//______________________________________________________________________________
void TNodeDiv::Paint(Option_t *)
{
// Paint Referenced node with current parameters.
}
<commit_msg>Coverity CID 34189: the TNodeDiv ctor was passing 0 for const char * parameter (matrix name) which was later used in strlen function. Actually, not clear who must be fixed - call to strlen without check or code which passes 0.<commit_after>// @(#)root/g3d:$Id$
// Author: Rene Brun 14/09/95
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#include "TVirtualPad.h"
#include "TNodeDiv.h"
ClassImp(TNodeDiv)
//______________________________________________________________________________
/* Begin_Html
<center><h2>The TNodeDiv class</h2></center>
Description of parameters to divide a 3-D geometry object.
End_Html */
//______________________________________________________________________________
TNodeDiv::TNodeDiv()
{
// NodeDiv default constructor.
fNdiv = 0;
fAxis = 0;
}
//______________________________________________________________________________
TNodeDiv::TNodeDiv(const char *name, const char *title, const char *shapename, Int_t ndiv, Int_t axis, Option_t *option)
:TNode(name, title, shapename, 0, 0, 0, "", option)
{
// NodeDiv normal constructor.
//
// name is the name of the node
// title is title
// shapename is the name of the referenced shape
// x,y,z are the offsets of the volume with respect to his mother
// matrixname is the name of the rotation matrix
//
// This new node is added into the list of sons of the current node
fNdiv = ndiv;
fAxis = axis;
}
//______________________________________________________________________________
TNodeDiv::TNodeDiv(const char *name, const char *title, TShape *shape, Int_t ndiv, Int_t axis, Option_t *option)
:TNode(name, title, shape, 0, 0, 0, 0, option)
{
// NodeDiv normal constructor.
//
// name is the name of the node
// title is title
// shape is the pointer to the shape definition
// ndiv number of divisions
// axis number of the axis for the division
//
// This new node is added into the list of sons of the current node
fNdiv = ndiv;
fAxis = axis;
}
//______________________________________________________________________________
TNodeDiv::~TNodeDiv()
{
// NodeDiv default destructor.
}
//______________________________________________________________________________
void TNodeDiv::Draw(Option_t *)
{
// Draw Referenced node with current parameters.
}
//______________________________________________________________________________
void TNodeDiv::Paint(Option_t *)
{
// Paint Referenced node with current parameters.
}
<|endoftext|>
|
<commit_before>/**
* @file
*/
#pragma once
#include "libbirch/type.hpp"
#include "libbirch/Nil.hpp"
namespace libbirch {
/**
* Optional.
*
* @ingroup libbirch
*
* @tparam T Type type.
*/
template<class T, class Enable = void>
class Optional {
template<class U, class Enable1> friend class Optional;
public:
/**
* Constructor.
*/
Optional(const Nil& = nil) :
value(),
hasValue(false) {
//
}
/**
* Constructor.
*/
template<IS_NOT_VALUE(T)>
Optional(Label* context, const Nil& = nil) :
value(),
hasValue(false) {
//
}
/**
* Constructor.
*/
Optional(const T& value) :
value(value),
hasValue(true) {
//
}
/**
* Constructor.
*/
template<class U, IS_CONVERTIBLE(U,T)>
Optional(const U& value) :
value(value),
hasValue(true) {
//
}
/**
* Constructor.
*/
template<IS_NOT_VALUE(T), class U, IS_CONVERTIBLE(U,T)>
Optional(Label* context, const U& value) :
value(context, value),
hasValue(true) {
//
}
/**
* Constructor.
*/
Optional(T&& value) :
value(std::move(value)),
hasValue(true) {
//
}
/**
* Constructor.
*/
template<class U, IS_CONVERTIBLE(U,T)>
Optional(U&& value) :
value(std::move(value)),
hasValue(true) {
//
}
/**
* Constructor.
*/
template<IS_NOT_VALUE(T), class U, IS_CONVERTIBLE(U,T)>
Optional(Label* context, U&& value) :
value(context, std::move(value)),
hasValue(true) {
//
}
/**
* Copy constructor.
*/
Optional(const Optional<T>& o) :
value(o.value),
hasValue(o.hasValue) {
//
}
/**
* Copy constructor.
*/
template<class U, IS_CONVERTIBLE(U,T)>
Optional(const Optional<U>& o) :
value(o.value),
hasValue(o.hasValue) {
//
}
/**
* Copy constructor.
*/
template<IS_NOT_VALUE(T), class U, IS_CONVERTIBLE(U,T)>
Optional(Label* context, const Optional<U>& o) :
value(context, o.value),
hasValue(o.hasValue) {
//
}
/**
* Move constructor.
*/
Optional(Optional<T>&& o) :
value(std::move(o.value)),
hasValue(o.hasValue) {
//
}
/**
* Move constructor.
*/
template<class U, IS_CONVERTIBLE(U,T)>
Optional(Optional<U>&& o) :
value(std::move(o.value)),
hasValue(o.hasValue) {
//
}
/**
* Move constructor.
*/
template<IS_NOT_VALUE(T), class U, IS_CONVERTIBLE(U,T)>
Optional(Label* context, Optional<U>&& o) :
value(context, std::move(o.value)),
hasValue(o.hasValue) {
//
}
/**
* Deep copy constructor.
*/
template<IS_NOT_VALUE(T)>
Optional(Label* context, Label* label, const Optional& o) :
value(context, label, o.value),
hasValue(o.hasValue) {
//
}
/**
* Nil assignment operator.
*/
Optional& operator=(const Nil& nil) {
return assign(nil);
}
/**
* Copy assignment operator.
*/
Optional& operator=(const Optional<T>& o) {
return assign(o);
}
/**
* Copy assignment operator.
*/
template<IS_VALUE(T)>
Optional& operator=(const T& value) {
return assign(value);
}
/**
* Move assignment operator.
*/
Optional& operator=(Optional<T>&& o) {
return assign(std::move(o));
}
/**
* Move assignment operator.
*/
template<IS_VALUE(T)>
Optional& operator=(T&& value) {
return assign(std::move(value));
}
/**
* Is there a value?
*/
bool query() const {
return hasValue;
}
/**
* Get the value.
*/
T& get() {
libbirch_assert_msg_(hasValue, "optional has no value");
return value;
}
/**
* Get the value.
*/
const T& get() const {
libbirch_assert_msg_(hasValue, "optional has no value");
return value;
}
/**
* Copy assignment.
*/
template<IS_VALUE(T)>
Optional& assign(const Optional<T>& o) {
this->value = o.value;
this->hasValue = o.hasValue;
return *this;
}
/**
* Copy assignment.
*/
template<IS_NOT_VALUE(T)>
Optional& assign(Label* context, const Optional<T>& o) {
this->value.assign(context, o.value);
this->hasValue = o.hasValue;
return *this;
}
/**
* Move assignment.
*/
template<IS_VALUE(T)>
Optional& assign(Optional<T>&& o) {
this->value = std::move(o.value);
this->hasValue = o.hasValue;
return *this;
}
/**
* Move assignment.
*/
template<IS_NOT_VALUE(T)>
Optional& assign(Label* context, Optional<T>&& o) {
this->value.assign(context, std::move(o.value));
this->hasValue = o.hasValue;
return *this;
}
template<IS_VALUE(T)>
void freeze() {
//
}
template<IS_NOT_VALUE(T)>
void freeze() {
if (hasValue) {
value.freeze();
}
}
template<IS_VALUE(T)>
void thaw(Label* label) {
//
}
template<IS_NOT_VALUE(T)>
void thaw(Label* label) {
if (hasValue) {
value.thaw(label);
}
}
template<IS_VALUE(T)>
void finish() {
//
}
template<IS_NOT_VALUE(T)>
void finish() {
if (hasValue) {
value.finish();
}
}
private:
/**
* The contained value, if any.
*/
T value;
/**
* Is there a value?
*/
bool hasValue;
};
/**
* Optional for pointer types. Uses a null pointer, rather than a flag, to
* indicate no value.
*
* @ingroup libbirch
*
* @tparam T Type type.
*/
template<class T>
class Optional<T,std::enable_if_t<is_pointer<T>::value>> {
template<class U, class Enable1> friend class Optional;
public:
/**
* Constructor.
*/
Optional(const Nil& = nil) :
value() {
//
}
/**
* Constructor.
*/
Optional(Label* context, const Nil& = nil) :
value() {
//
}
/**
* Constructor.
*/
Optional(const T& value) :
value(value) {
//
}
/**
* Constructor.
*/
template<class U, IS_CONVERTIBLE(U,T)>
Optional(const U& value) :
value(value) {
//
}
/**
* Constructor.
*/
template<class U, IS_CONVERTIBLE(U,T)>
Optional(Label* context, const U& value) :
value(context, value) {
//
}
/**
* Constructor.
*/
Optional(T&& value) :
value(std::move(value)) {
//
}
/**
* Constructor.
*/
template<class U, IS_CONVERTIBLE(U,T)>
Optional(U&& value) :
value(std::move(value)) {
//
}
/**
* Constructor.
*/
template<class U, IS_CONVERTIBLE(U,T)>
Optional(Label* context, U&& value) :
value(context, std::move(value)) {
//
}
/**
* Copy constructor.
*/
Optional(const Optional<T>& o) :
value(o.value) {
//
}
/**
* Copy constructor.
*/
template<class U, IS_CONVERTIBLE(U,T)>
Optional(const Optional<U>& o) :
value(o.value) {
//
}
/**
* Copy constructor.
*/
template<class U, IS_CONVERTIBLE(U,T)>
Optional(Label* context, const Optional<U>& o) :
value(context, o.value) {
//
}
/**
* Move constructor.
*/
Optional(Optional<T>&& o) :
value(std::move(o.value)) {
//
}
/**
* Move constructor.
*/
template<class U, IS_CONVERTIBLE(U,T)>
Optional(Optional<U>&& o) :
value(std::move(o.value)) {
//
}
/**
* Move constructor.
*/
template<class U, IS_CONVERTIBLE(U,T)>
Optional(Label* context, Optional<U>&& o) :
value(context, std::move(o.value)) {
//
}
/**
* Deep copy constructor.
*/
Optional(Label* context, Label* label, const Optional& o) :
value(context, label, o.value) {
//
}
/**
* Nil assignment operator.
*/
Optional& operator=(const Nil& nil) {
return assign(nil);
}
/**
* Copy assignment operator.
*/
Optional& operator=(const Optional<T>& o) {
return assign(o);
}
/**
* Move assignment operator.
*/
Optional& operator=(Optional<T>&& o) {
return assign(std::move(o));
}
/**
* Is there a value?
*/
bool query() const {
return value.query();
}
/**
* Get the value.
*/
T& get() {
libbirch_assert_msg_(query(), "optional has no value");
return value;
}
/**
* Get the value.
*/
const T& get() const {
libbirch_assert_msg_(query(), "optional has no value");
return value;
}
/**
* Copy assignment.
*/
Optional& assign(Label* context, const Optional<T>& o) {
this->value.assign(context, o.value);
return *this;
}
/**
* Move assignment.
*/
Optional& assign(Label* context, Optional<T>&& o) {
this->value.assign(context, std::move(o.value));
return *this;
}
void freeze() {
if (query()) {
get().freeze();
}
}
void thaw(Label* label) {
if (query()) {
get().thaw(label);
}
}
void finish() {
if (query()) {
get().finish();
}
}
private:
/**
* The pointer.
*/
T value;
};
template<class T>
struct is_value<Optional<T>> {
static const bool value = is_value<T>::value;
};
template<class T>
struct is_value<Optional<T>&> {
static const bool value = is_value<T>::value;
};
}
<commit_msg>Fixed erroneous move due to universal reference. [skip ci]<commit_after>/**
* @file
*/
#pragma once
#include "libbirch/type.hpp"
#include "libbirch/Nil.hpp"
namespace libbirch {
/**
* Optional.
*
* @ingroup libbirch
*
* @tparam T Type type.
*/
template<class T, class Enable = void>
class Optional {
template<class U, class Enable1> friend class Optional;
static_assert(!std::is_lvalue_reference<T>::value,
"Optional does not support lvalue reference types.");
public:
/**
* Constructor.
*/
Optional(const Nil& = nil) :
value(),
hasValue(false) {
//
}
/**
* Constructor.
*/
template<IS_NOT_VALUE(T)>
Optional(Label* context, const Nil& = nil) :
value(),
hasValue(false) {
//
}
/**
* Value copy constructor.
*/
template<class U, IS_CONVERTIBLE(U,T)>
Optional(const U& value) :
value(value),
hasValue(true) {
//
}
/**
* Value copy constructor.
*/
template<class U, IS_NOT_VALUE(T), IS_CONVERTIBLE(U,T)>
Optional(Label* context, const U& value) :
value(context, value),
hasValue(true) {
//
}
/**
* Value move constructor.
*
* @todo Make generic while avoiding use of universal reference.
*/
Optional(T&& value) :
value(std::move(value)),
hasValue(true) {
//
}
/**
* Value move constructor.
*
* @todo Make generic while avoiding use of universal reference.
*/
template<IS_VALUE(T)>
Optional(T&& value) :
value(std::move(value)),
hasValue(true) {
//
}
/**
* Value move constructor.
*
* @todo Make generic while avoiding use of universal reference.
*/
template<IS_NOT_VALUE(T)>
Optional(Label* context, T&& value) :
value(context, std::move(value)),
hasValue(true) {
//
}
/**
* Copy constructor.
*/
Optional(const Optional<T>& o) :
value(o.value),
hasValue(o.hasValue) {
//
}
/**
* Copy constructor.
*/
template<class U, IS_CONVERTIBLE(U,T)>
Optional(const Optional<U>& o) :
value(o.value),
hasValue(o.hasValue) {
//
}
/**
* Copy constructor.
*/
template<IS_NOT_VALUE(T), class U, IS_CONVERTIBLE(U,T)>
Optional(Label* context, const Optional<U>& o) :
value(context, o.value),
hasValue(o.hasValue) {
//
}
/**
* Move constructor.
*/
Optional(Optional<T>&& o) :
value(std::move(o.value)),
hasValue(o.hasValue) {
//
}
/**
* Move constructor.
*/
template<class U, IS_CONVERTIBLE(U,T)>
Optional(Optional<U>&& o) :
value(std::move(o.value)),
hasValue(o.hasValue) {
//
}
/**
* Move constructor.
*/
template<IS_NOT_VALUE(T), class U, IS_CONVERTIBLE(U,T)>
Optional(Label* context, Optional<U>&& o) :
value(context, std::move(o.value)),
hasValue(o.hasValue) {
//
}
/**
* Deep copy constructor.
*/
template<IS_NOT_VALUE(T)>
Optional(Label* context, Label* label, const Optional& o) :
value(context, label, o.value),
hasValue(o.hasValue) {
//
}
/**
* Nil assignment operator.
*/
Optional& operator=(const Nil& nil) {
return assign(nil);
}
/**
* Copy assignment operator.
*/
Optional& operator=(const Optional<T>& o) {
return assign(o);
}
/**
* Copy assignment operator.
*/
template<IS_VALUE(T)>
Optional& operator=(const T& value) {
return assign(value);
}
/**
* Move assignment operator.
*/
Optional& operator=(Optional<T>&& o) {
return assign(std::move(o));
}
/**
* Move assignment operator.
*/
template<IS_VALUE(T)>
Optional& operator=(T&& value) {
return assign(std::move(value));
}
/**
* Is there a value?
*/
bool query() const {
return hasValue;
}
/**
* Get the value.
*/
T& get() {
libbirch_assert_msg_(hasValue, "optional has no value");
return value;
}
/**
* Get the value.
*/
const T& get() const {
libbirch_assert_msg_(hasValue, "optional has no value");
return value;
}
/**
* Copy assignment.
*/
template<IS_VALUE(T)>
Optional& assign(const Optional<T>& o) {
this->value = o.value;
this->hasValue = o.hasValue;
return *this;
}
/**
* Copy assignment.
*/
template<IS_NOT_VALUE(T)>
Optional& assign(Label* context, const Optional<T>& o) {
this->value.assign(context, o.value);
this->hasValue = o.hasValue;
return *this;
}
/**
* Move assignment.
*/
template<IS_VALUE(T)>
Optional& assign(Optional<T>&& o) {
this->value = std::move(o.value);
this->hasValue = o.hasValue;
return *this;
}
/**
* Move assignment.
*/
template<IS_NOT_VALUE(T)>
Optional& assign(Label* context, Optional<T>&& o) {
this->value.assign(context, std::move(o.value));
this->hasValue = o.hasValue;
return *this;
}
template<IS_VALUE(T)>
void freeze() {
//
}
template<IS_NOT_VALUE(T)>
void freeze() {
if (hasValue) {
value.freeze();
}
}
template<IS_VALUE(T)>
void thaw(Label* label) {
//
}
template<IS_NOT_VALUE(T)>
void thaw(Label* label) {
if (hasValue) {
value.thaw(label);
}
}
template<IS_VALUE(T)>
void finish() {
//
}
template<IS_NOT_VALUE(T)>
void finish() {
if (hasValue) {
value.finish();
}
}
private:
/**
* The contained value, if any.
*/
T value;
/**
* Is there a value?
*/
bool hasValue;
};
/**
* Optional for pointer types. Uses a null pointer, rather than a flag, to
* indicate no value.
*
* @ingroup libbirch
*
* @tparam T Type type.
*/
template<class T>
class Optional<T,std::enable_if_t<is_pointer<T>::value>> {
template<class U, class Enable1> friend class Optional;
static_assert(!std::is_lvalue_reference<T>::value,
"Optional does not support lvalue reference types.");
public:
/**
* Constructor.
*/
Optional(const Nil& = nil) :
value() {
//
}
/**
* Constructor.
*/
Optional(Label* context, const Nil& = nil) :
value() {
//
}
/**
* Value copy constructor.
*/
template<class U, IS_CONVERTIBLE(U,T)>
Optional(const U& value) :
value(value) {
//
}
/**
* Value copy constructor.
*/
template<class U, IS_CONVERTIBLE(U,T)>
Optional(Label* context, const U& value) :
value(context, value) {
//
}
/**
* Value move constructor.
*
* @todo Make generic while avoiding use of universal reference.
*/
Optional(T&& value) :
value(std::move(value)) {
//
}
/**
* Value move constructor.
*
* @todo Make generic while avoiding use of universal reference.
*/
Optional(Label* context, T&& value) :
value(context, std::move(value)) {
//
}
/**
* Copy constructor.
*/
Optional(const Optional<T>& o) :
value(o.value) {
//
}
/**
* Copy constructor.
*/
template<class U, IS_CONVERTIBLE(U,T)>
Optional(const Optional<U>& o) :
value(o.value) {
//
}
/**
* Copy constructor.
*/
template<class U, IS_CONVERTIBLE(U,T)>
Optional(Label* context, const Optional<U>& o) :
value(context, o.value) {
//
}
/**
* Move constructor.
*/
Optional(Optional<T>&& o) :
value(std::move(o.value)) {
//
}
/**
* Move constructor.
*/
template<class U, IS_CONVERTIBLE(U,T)>
Optional(Optional<U>&& o) :
value(std::move(o.value)) {
//
}
/**
* Move constructor.
*/
template<class U, IS_CONVERTIBLE(U,T)>
Optional(Label* context, Optional<U>&& o) :
value(context, std::move(o.value)) {
//
}
/**
* Deep copy constructor.
*/
Optional(Label* context, Label* label, const Optional& o) :
value(context, label, o.value) {
//
}
/**
* Nil assignment operator.
*/
Optional& operator=(const Nil& nil) {
return assign(nil);
}
/**
* Copy assignment operator.
*/
Optional& operator=(const Optional<T>& o) {
return assign(o);
}
/**
* Move assignment operator.
*/
Optional& operator=(Optional<T>&& o) {
return assign(std::move(o));
}
/**
* Is there a value?
*/
bool query() const {
return value.query();
}
/**
* Get the value.
*/
T& get() {
libbirch_assert_msg_(query(), "optional has no value");
return value;
}
/**
* Get the value.
*/
const T& get() const {
libbirch_assert_msg_(query(), "optional has no value");
return value;
}
/**
* Copy assignment.
*/
Optional& assign(Label* context, const Optional<T>& o) {
this->value.assign(context, o.value);
return *this;
}
/**
* Move assignment.
*/
Optional& assign(Label* context, Optional<T>&& o) {
this->value.assign(context, std::move(o.value));
return *this;
}
void freeze() {
if (query()) {
get().freeze();
}
}
void thaw(Label* label) {
if (query()) {
get().thaw(label);
}
}
void finish() {
if (query()) {
get().finish();
}
}
private:
/**
* The pointer.
*/
T value;
};
template<class T>
struct is_value<Optional<T>> {
static const bool value = is_value<T>::value;
};
template<class T>
struct is_value<Optional<T>&> {
static const bool value = is_value<T>::value;
};
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2018 Red Hat, Inc.
*
* Licensed under the GNU Lesser General Public License Version 2.1
*
* 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
*/
#ifndef _LIBDNF_CONFIG_CONST_HPP
#define _LIBDNF_CONFIG_CONST_HPP
namespace libdnf {
constexpr const char * PERSISTDIR = "/var/lib/dnf";
constexpr const char * SYSTEM_CACHEDIR = "/var/cache/dnf";
constexpr const char * URL_REGEX = "(https?|ftp|file):\\/\\/[-a-zA-Z0-9_.\\/?=&#\\$;%@+~|!:,]+$";
constexpr const char * PROXY_URL_REGEX = "^((https?|ftp|socks5h?|socks4a?):\\/\\/[-a-zA-Z0-9_.\\/?=&#\\$;%@+~|!:,]+)?$";
constexpr const char * CONF_FILENAME = "/etc/dnf/dnf.conf";
const std::vector<std::string> GROUP_PACKAGE_TYPES{"mandatory", "default", "conditional"};
const std::vector<std::string> INSTALLONLYPKGS{"kernel", "kernel-PAE",
"installonlypkg(kernel)",
"installonlypkg(kernel-module)",
"installonlypkg(vm)"};
constexpr const char * BUGTRACKER="https://bugzilla.redhat.com/enter_bug.cgi?product=Fedora&component=dnf";
}
#endif
<commit_msg>Adds one kernel provide into libdnf/conf<commit_after>/*
* Copyright (C) 2018 Red Hat, Inc.
*
* Licensed under the GNU Lesser General Public License Version 2.1
*
* 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
*/
#ifndef _LIBDNF_CONFIG_CONST_HPP
#define _LIBDNF_CONFIG_CONST_HPP
namespace libdnf {
constexpr const char * PERSISTDIR = "/var/lib/dnf";
constexpr const char * SYSTEM_CACHEDIR = "/var/cache/dnf";
constexpr const char * URL_REGEX = "(https?|ftp|file):\\/\\/[-a-zA-Z0-9_.\\/?=&#\\$;%@+~|!:,]+$";
constexpr const char * PROXY_URL_REGEX = "^((https?|ftp|socks5h?|socks4a?):\\/\\/[-a-zA-Z0-9_.\\/?=&#\\$;%@+~|!:,]+)?$";
constexpr const char * CONF_FILENAME = "/etc/dnf/dnf.conf";
const std::vector<std::string> GROUP_PACKAGE_TYPES{"mandatory", "default", "conditional"};
const std::vector<std::string> INSTALLONLYPKGS{"kernel", "kernel-PAE",
"installonlypkg(kernel)",
"installonlypkg(kernel-module)",
"installonlypkg(vm)",
"multiversion(kernel)"};
constexpr const char * BUGTRACKER="https://bugzilla.redhat.com/enter_bug.cgi?product=Fedora&component=dnf";
}
#endif
<|endoftext|>
|
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "remoting/host/disconnect_window.h"
#include <gtk/gtk.h>
#include "base/compiler_specific.h"
#include "base/logging.h"
#include "remoting/host/chromoting_host.h"
#include "ui/base/gtk/gtk_signal.h"
namespace {
const char kDisconnectWindowTitle[] = "Remoting";
const char kDisconnectWindowShareText[] = "Sharing with: ";
const char kDisconnectWindowButtonText[] = "Disconnect";
class DisconnectWindowLinux : public remoting::DisconnectWindow {
public:
DisconnectWindowLinux();
virtual void Show(remoting::ChromotingHost* host,
const std::string& username) OVERRIDE;
virtual void Hide() OVERRIDE;
private:
CHROMEGTK_CALLBACK_1(DisconnectWindowLinux, gboolean, OnWindowDelete,
GdkEvent*);
CHROMEG_CALLBACK_0(DisconnectWindowLinux, void, OnDisconnectClicked,
GtkButton*);
void CreateWindow();
remoting::ChromotingHost* host_;
GtkWidget* disconnect_window_;
GtkWidget* user_label_;
DISALLOW_COPY_AND_ASSIGN(DisconnectWindowLinux);
};
} // namespace
DisconnectWindowLinux::DisconnectWindowLinux()
: host_(NULL),
disconnect_window_(NULL) {
}
void DisconnectWindowLinux::CreateWindow() {
if (disconnect_window_) return;
disconnect_window_ = gtk_window_new(GTK_WINDOW_TOPLEVEL);
GtkWindow* window = GTK_WINDOW(disconnect_window_);
gtk_window_set_title(window, kDisconnectWindowTitle);
gtk_window_set_resizable(window, FALSE);
// Try to keep the window always visible.
gtk_window_stick(window);
gtk_window_set_keep_above(window, TRUE);
g_signal_connect(disconnect_window_, "delete-event",
G_CALLBACK(OnWindowDeleteThunk), this);
GtkWidget* main_area = gtk_vbox_new(FALSE, 0);
gtk_container_add(GTK_CONTAINER(disconnect_window_), main_area);
GtkWidget* username_row = gtk_hbox_new(FALSE, 0);
gtk_container_add(GTK_CONTAINER(main_area), username_row);
GtkWidget* share_label = gtk_label_new(kDisconnectWindowShareText);
gtk_container_add(GTK_CONTAINER(username_row), share_label);
user_label_ = gtk_label_new(NULL);
gtk_container_add(GTK_CONTAINER(username_row), user_label_);
GtkWidget* disconnect_box = gtk_hbox_new(FALSE, 0);
gtk_container_add(GTK_CONTAINER(main_area), disconnect_box);
GtkWidget* disconnect_button = gtk_button_new_with_label(
kDisconnectWindowButtonText);
gtk_box_pack_start(GTK_BOX(disconnect_box), disconnect_button,
TRUE, FALSE, 0);
g_signal_connect(disconnect_button, "clicked",
G_CALLBACK(OnDisconnectClickedThunk), this);
gtk_widget_show_all(main_area);
}
void DisconnectWindowLinux::Show(remoting::ChromotingHost* host,
const std::string& username) {
host_ = host;
CreateWindow();
gtk_label_set_text(GTK_LABEL(user_label_), username.c_str());
gtk_window_present(GTK_WINDOW(disconnect_window_));
}
void DisconnectWindowLinux::Hide() {
DCHECK(disconnect_window_);
gtk_widget_hide(disconnect_window_);
}
gboolean DisconnectWindowLinux::OnWindowDelete(GtkWidget* widget,
GdkEvent* event) {
// Don't allow the window to be closed.
return TRUE;
}
void DisconnectWindowLinux::OnDisconnectClicked(GtkButton* sender) {
DCHECK(host_);
host_->Shutdown();
}
remoting::DisconnectWindow* remoting::DisconnectWindow::Create() {
return new DisconnectWindowLinux;
}
<commit_msg>Remove minimize/close buttons from DisconnectWindowLinux.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "remoting/host/disconnect_window.h"
#include <gtk/gtk.h>
#include "base/compiler_specific.h"
#include "base/logging.h"
#include "remoting/host/chromoting_host.h"
#include "ui/base/gtk/gtk_signal.h"
namespace {
const char kDisconnectWindowTitle[] = "Remoting";
const char kDisconnectWindowShareText[] = "Sharing with: ";
const char kDisconnectWindowButtonText[] = "Disconnect";
class DisconnectWindowLinux : public remoting::DisconnectWindow {
public:
DisconnectWindowLinux();
virtual void Show(remoting::ChromotingHost* host,
const std::string& username) OVERRIDE;
virtual void Hide() OVERRIDE;
private:
CHROMEGTK_CALLBACK_1(DisconnectWindowLinux, gboolean, OnWindowDelete,
GdkEvent*);
CHROMEG_CALLBACK_0(DisconnectWindowLinux, void, OnDisconnectClicked,
GtkButton*);
void CreateWindow();
remoting::ChromotingHost* host_;
GtkWidget* disconnect_window_;
GtkWidget* user_label_;
DISALLOW_COPY_AND_ASSIGN(DisconnectWindowLinux);
};
} // namespace
DisconnectWindowLinux::DisconnectWindowLinux()
: host_(NULL),
disconnect_window_(NULL) {
}
void DisconnectWindowLinux::CreateWindow() {
if (disconnect_window_) return;
disconnect_window_ = gtk_window_new(GTK_WINDOW_TOPLEVEL);
GtkWindow* window = GTK_WINDOW(disconnect_window_);
gtk_window_set_title(window, kDisconnectWindowTitle);
gtk_window_set_resizable(window, FALSE);
// Try to keep the window always visible.
gtk_window_stick(window);
gtk_window_set_keep_above(window, TRUE);
// Utility windows have no minimize button or taskbar presence.
gtk_window_set_type_hint(window, GDK_WINDOW_TYPE_HINT_UTILITY);
gtk_window_set_deletable(window, FALSE);
g_signal_connect(disconnect_window_, "delete-event",
G_CALLBACK(OnWindowDeleteThunk), this);
GtkWidget* main_area = gtk_vbox_new(FALSE, 0);
gtk_container_add(GTK_CONTAINER(disconnect_window_), main_area);
GtkWidget* username_row = gtk_hbox_new(FALSE, 0);
gtk_container_add(GTK_CONTAINER(main_area), username_row);
GtkWidget* share_label = gtk_label_new(kDisconnectWindowShareText);
gtk_container_add(GTK_CONTAINER(username_row), share_label);
user_label_ = gtk_label_new(NULL);
gtk_container_add(GTK_CONTAINER(username_row), user_label_);
GtkWidget* disconnect_box = gtk_hbox_new(FALSE, 0);
gtk_container_add(GTK_CONTAINER(main_area), disconnect_box);
GtkWidget* disconnect_button = gtk_button_new_with_label(
kDisconnectWindowButtonText);
gtk_box_pack_start(GTK_BOX(disconnect_box), disconnect_button,
TRUE, FALSE, 0);
g_signal_connect(disconnect_button, "clicked",
G_CALLBACK(OnDisconnectClickedThunk), this);
gtk_widget_show_all(main_area);
}
void DisconnectWindowLinux::Show(remoting::ChromotingHost* host,
const std::string& username) {
host_ = host;
CreateWindow();
gtk_label_set_text(GTK_LABEL(user_label_), username.c_str());
gtk_window_present(GTK_WINDOW(disconnect_window_));
}
void DisconnectWindowLinux::Hide() {
DCHECK(disconnect_window_);
gtk_widget_hide(disconnect_window_);
}
gboolean DisconnectWindowLinux::OnWindowDelete(GtkWidget* widget,
GdkEvent* event) {
// Don't allow the window to be closed.
return TRUE;
}
void DisconnectWindowLinux::OnDisconnectClicked(GtkButton* sender) {
DCHECK(host_);
host_->Shutdown();
}
remoting::DisconnectWindow* remoting::DisconnectWindow::Create() {
return new DisconnectWindowLinux;
}
<|endoftext|>
|
<commit_before>/*=========================================================================
*
* Copyright Insight Software Consortium
*
* 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.txt
*
* 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 <itkImage.h>
#include <itkMetaDataDictionary.h>
#include <itkMetaDataObject.h>
#include <itkImageRegionIterator.h>
#include <itkImageFileWriter.h>
#include <itkImageFileReader.h>
using ImageType = itk::Image<unsigned char, 2>;
static void CreateImage(ImageType::Pointer image);
int main(int, char*[])
{
// Create an image
ImageType::Pointer image = ImageType::New();
CreateImage(image);
// Store some data in it
itk::MetaDataDictionary dictionary;
itk::EncapsulateMetaData<float>(dictionary,"ASimpleFloat",1.2);
image->SetMetaDataDictionary(dictionary);
// View all of the data
dictionary.Print(std::cout);
// View the data individually
itk::MetaDataDictionary::Iterator itr = dictionary.Begin();
while( itr != dictionary.End() )
{
std::cout << "Key = " << itr->first << std::endl;
std::cout << "Value = ";
itr->second->Print( std::cout );
std::cout << std::endl;
++itr;
}
// Write the image (and the data) to a file
using WriterType = itk::ImageFileWriter< ImageType >;
WriterType::Pointer writer = WriterType::New();
writer->SetFileName("test.mhd");
writer->SetInput(image);
writer->Update();
// Read the image (and data) from the file
using ReaderType = itk::ImageFileReader<ImageType>;
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName("test.mhd");
// Display the data
std::cout << "Data read from file:" << std::endl;
reader->GetMetaDataDictionary().Print(std::cout);
return EXIT_SUCCESS;
}
void CreateImage(ImageType::Pointer image)
{
ImageType::IndexType start;
start.Fill(0);
ImageType::SizeType size;
size.Fill(10);
ImageType::RegionType region;
region.SetSize(size);
region.SetIndex(start);
image->SetRegions(region);
image->Allocate();
itk::ImageRegionIterator<ImageType> imageIterator(image,image->GetLargestPossibleRegion());
while(!imageIterator.IsAtEnd())
{
imageIterator.Set(20);
++imageIterator;
}
}
<commit_msg>STYLE: Use auto for variable type<commit_after>/*=========================================================================
*
* Copyright Insight Software Consortium
*
* 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.txt
*
* 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 <itkImage.h>
#include <itkMetaDataDictionary.h>
#include <itkMetaDataObject.h>
#include <itkImageRegionIterator.h>
#include <itkImageFileWriter.h>
#include <itkImageFileReader.h>
using ImageType = itk::Image<unsigned char, 2>;
static void CreateImage(ImageType::Pointer image);
int main(int, char*[])
{
// Create an image
ImageType::Pointer image = ImageType::New();
CreateImage(image);
// Store some data in it
itk::MetaDataDictionary dictionary;
itk::EncapsulateMetaData<float>(dictionary,"ASimpleFloat",1.2);
image->SetMetaDataDictionary(dictionary);
// View all of the data
dictionary.Print(std::cout);
// View the data individually
auto itr = dictionary.Begin();
while( itr != dictionary.End() )
{
std::cout << "Key = " << itr->first << std::endl;
std::cout << "Value = ";
itr->second->Print( std::cout );
std::cout << std::endl;
++itr;
}
// Write the image (and the data) to a file
using WriterType = itk::ImageFileWriter< ImageType >;
WriterType::Pointer writer = WriterType::New();
writer->SetFileName("test.mhd");
writer->SetInput(image);
writer->Update();
// Read the image (and data) from the file
using ReaderType = itk::ImageFileReader<ImageType>;
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName("test.mhd");
// Display the data
std::cout << "Data read from file:" << std::endl;
reader->GetMetaDataDictionary().Print(std::cout);
return EXIT_SUCCESS;
}
void CreateImage(ImageType::Pointer image)
{
ImageType::IndexType start;
start.Fill(0);
ImageType::SizeType size;
size.Fill(10);
ImageType::RegionType region;
region.SetSize(size);
region.SetIndex(start);
image->SetRegions(region);
image->Allocate();
itk::ImageRegionIterator<ImageType> imageIterator(image,image->GetLargestPossibleRegion());
while(!imageIterator.IsAtEnd())
{
imageIterator.Set(20);
++imageIterator;
}
}
<|endoftext|>
|
<commit_before>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2009-2010, Image Engine Design Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of Image Engine Design nor the names of any
// other contributors to this software may be used to endorse or
// promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////
#include "boost/python.hpp"
#include "boost/tokenizer.hpp"
#include "IECore/FileSequenceParameter.h"
#include "IECore/CompoundObject.h"
#include "IECore/Exception.h"
#include "IECorePython/IECoreBinding.h"
#include "IECorePython/RunTimeTypedBinding.h"
#include "IECorePython/FileSequenceParameterBinding.h"
#include "IECorePython/ParameterBinding.h"
#include "IECorePython/Wrapper.h"
using namespace boost::python;
using namespace IECore;
namespace IECorePython
{
class FileSequenceParameterWrap : public FileSequenceParameter, public Wrapper< FileSequenceParameter >
{
public:
IE_CORE_DECLAREMEMBERPTR( FileSequenceParameterWrap );
protected:
static FileSequenceParameter::ExtensionList makeExtensions( object extensions )
{
FileSequenceParameter::ExtensionList result;
extract<list> ee( extensions );
if ( ee.check() )
{
list ext = ee();
for ( long i = 0; i < IECorePython::len( ext ); i++ )
{
extract< std::string > ex( ext[i] );
if ( !ex.check() )
{
throw InvalidArgumentException( "FileSequenceParameter: Invalid extensions value" );
}
result.push_back( ex() );
}
}
else
{
extract<std::string> ee( extensions );
if ( ee.check() )
{
std::string ext = ee();
boost::tokenizer< boost::char_separator<char> > t( ext, boost::char_separator<char>( " " ) );
for ( boost::tokenizer<boost::char_separator<char> >::const_iterator it = t.begin(); it != t.end(); ++it )
{
result.push_back( *it );
}
}
else
{
throw InvalidArgumentException( "FileSequenceParameter: Invalid extensions value" );
}
}
return result;
}
/// Allow construction from either a string, StringData, or a FileSequence
static std::string makeDefault( object defaultValue )
{
extract<std::string> de( defaultValue );
if( de.check() )
{
return de();
}
else
{
extract<StringData *> de( defaultValue );
if( de.check() )
{
return de()->readable();
}
else
{
extract<FileSequence *> de( defaultValue );
if( de.check() )
{
return de()->asString();
}
else
{
throw InvalidArgumentException( "FileSequenceParameter: Invalid default value" );
}
}
}
}
public :
FileSequenceParameterWrap( PyObject *self, const std::string &n, const std::string &d, object dv = object( std::string("") ), bool allowEmptyString = true, FileSequenceParameter::CheckType check = FileSequenceParameter::DontCare, const object &p = boost::python::tuple(), bool po = false, CompoundObjectPtr ud = 0, object extensions = list(), size_t minSequenceSize = 2 )
: FileSequenceParameter( n, d, makeDefault( dv ), allowEmptyString, check, parameterPresets<FileSequenceParameter::PresetsContainer>( p ), po, ud, makeExtensions( extensions ), minSequenceSize ), Wrapper< FileSequenceParameter >( self, this ) {};
list getExtensionsWrap()
{
FileSequenceParameter::ExtensionList extensions = FileSequenceParameter::getExtensions();
list result;
for ( FileSequenceParameter::ExtensionList::const_iterator it = extensions.begin(); it != extensions.end(); ++it )
{
result.append( *it );
}
return result;
}
void setExtensionsWrap( object ext )
{
for ( long i = 0; i < IECorePython::len( ext ); i++)
{
FileSequenceParameter::setExtensions( makeExtensions( ext ) );
}
}
IECOREPYTHON_PARAMETERWRAPPERFNS( FileSequenceParameter );
};
void bindFileSequenceParameter()
{
RunTimeTypedClass<FileSequenceParameter, FileSequenceParameterWrap::Ptr>()
.def(
init< const std::string &, const std::string &, boost::python::optional< object, bool, FileSequenceParameter::CheckType, const object &, bool, CompoundObjectPtr, object, int > >
(
(
arg( "name" ),
arg( "description" ),
arg( "defaultValue" ) = object( std::string("") ),
arg( "allowEmptyString" ) = true,
arg( "check" ) = FileSequenceParameter::DontCare,
arg( "presets" ) = boost::python::tuple(),
arg( "presetsOnly" ) = false ,
arg( "userData" ) = CompoundObject::Ptr( 0 ),
arg( "extensions" ) = list(),
arg( "minSequenceSize" ) = 2
)
)
)
.def( "getFileSequenceValue", &FileSequenceParameter::getFileSequenceValue )
.def( "setFileSequenceValue", &FileSequenceParameter::setFileSequenceValue )
.def( "setMinSequenceSize", &FileSequenceParameter::setMinSequenceSize )
.def( "getMinSequenceSize", &FileSequenceParameter::getMinSequenceSize )
.add_property( "extensions",&FileSequenceParameterWrap::getExtensionsWrap, &FileSequenceParameterWrap::setExtensionsWrap )
.IECOREPYTHON_DEFPARAMETERWRAPPERFNS( FileSequenceParameter )
;
}
}
<commit_msg>Fixing an issue where the .extensions attribute wouldn't be available for parameters created in c++.<commit_after>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2009-2010, Image Engine Design Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of Image Engine Design nor the names of any
// other contributors to this software may be used to endorse or
// promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////
#include "boost/python.hpp"
#include "boost/tokenizer.hpp"
#include "IECore/FileSequenceParameter.h"
#include "IECore/CompoundObject.h"
#include "IECore/Exception.h"
#include "IECorePython/IECoreBinding.h"
#include "IECorePython/RunTimeTypedBinding.h"
#include "IECorePython/FileSequenceParameterBinding.h"
#include "IECorePython/ParameterBinding.h"
#include "IECorePython/Wrapper.h"
using namespace boost::python;
using namespace IECore;
namespace IECorePython
{
class FileSequenceParameterWrap : public FileSequenceParameter, public Wrapper< FileSequenceParameter >
{
public:
IE_CORE_DECLAREMEMBERPTR( FileSequenceParameterWrap );
static FileSequenceParameter::ExtensionList makeExtensions( object extensions )
{
FileSequenceParameter::ExtensionList result;
extract<list> ee( extensions );
if ( ee.check() )
{
list ext = ee();
for ( long i = 0; i < IECorePython::len( ext ); i++ )
{
extract< std::string > ex( ext[i] );
if ( !ex.check() )
{
throw InvalidArgumentException( "FileSequenceParameter: Invalid extensions value" );
}
result.push_back( ex() );
}
}
else
{
extract<std::string> ee( extensions );
if ( ee.check() )
{
std::string ext = ee();
boost::tokenizer< boost::char_separator<char> > t( ext, boost::char_separator<char>( " " ) );
for ( boost::tokenizer<boost::char_separator<char> >::const_iterator it = t.begin(); it != t.end(); ++it )
{
result.push_back( *it );
}
}
else
{
throw InvalidArgumentException( "FileSequenceParameter: Invalid extensions value" );
}
}
return result;
}
/// Allow construction from either a string, StringData, or a FileSequence
static std::string makeDefault( object defaultValue )
{
extract<std::string> de( defaultValue );
if( de.check() )
{
return de();
}
else
{
extract<StringData *> de( defaultValue );
if( de.check() )
{
return de()->readable();
}
else
{
extract<FileSequence *> de( defaultValue );
if( de.check() )
{
return de()->asString();
}
else
{
throw InvalidArgumentException( "FileSequenceParameter: Invalid default value" );
}
}
}
}
public :
FileSequenceParameterWrap( PyObject *self, const std::string &n, const std::string &d, object dv = object( std::string("") ), bool allowEmptyString = true, FileSequenceParameter::CheckType check = FileSequenceParameter::DontCare, const object &p = boost::python::tuple(), bool po = false, CompoundObjectPtr ud = 0, object extensions = list(), size_t minSequenceSize = 2 )
: FileSequenceParameter( n, d, makeDefault( dv ), allowEmptyString, check, parameterPresets<FileSequenceParameter::PresetsContainer>( p ), po, ud, makeExtensions( extensions ), minSequenceSize ), Wrapper< FileSequenceParameter >( self, this ) {};
IECOREPYTHON_PARAMETERWRAPPERFNS( FileSequenceParameter );
};
static list getFileSequenceExtensionsWrap( FileSequenceParameter ¶m )
{
FileSequenceParameter::ExtensionList extensions = param.getExtensions();
list result;
for ( FileSequenceParameter::ExtensionList::const_iterator it = extensions.begin(); it != extensions.end(); ++it )
{
result.append( *it );
}
return result;
}
static void setFileSequenceExtensionsWrap( FileSequenceParameter ¶m, object ext )
{
for ( long i = 0; i < IECorePython::len( ext ); i++)
{
param.setExtensions( FileSequenceParameterWrap::makeExtensions( ext ) );
}
}
void bindFileSequenceParameter()
{
RunTimeTypedClass<FileSequenceParameter, FileSequenceParameterWrap::Ptr>()
.def(
init< const std::string &, const std::string &, boost::python::optional< object, bool, FileSequenceParameter::CheckType, const object &, bool, CompoundObjectPtr, object, int > >
(
(
arg( "name" ),
arg( "description" ),
arg( "defaultValue" ) = object( std::string("") ),
arg( "allowEmptyString" ) = true,
arg( "check" ) = FileSequenceParameter::DontCare,
arg( "presets" ) = boost::python::tuple(),
arg( "presetsOnly" ) = false ,
arg( "userData" ) = CompoundObject::Ptr( 0 ),
arg( "extensions" ) = list(),
arg( "minSequenceSize" ) = 2
)
)
)
.def( "getFileSequenceValue", &FileSequenceParameter::getFileSequenceValue )
.def( "setFileSequenceValue", &FileSequenceParameter::setFileSequenceValue )
.def( "setMinSequenceSize", &FileSequenceParameter::setMinSequenceSize )
.def( "getMinSequenceSize", &FileSequenceParameter::getMinSequenceSize )
.add_property( "extensions",&getFileSequenceExtensionsWrap, &setFileSequenceExtensionsWrap )
.IECOREPYTHON_DEFPARAMETERWRAPPERFNS( FileSequenceParameter )
;
}
}
<|endoftext|>
|
<commit_before>#include "net/Socket.h"
#include "base/Exception.h"
#include "net/InetAddress.h"
NAMESPACE_ZL_NET_START
const static int MAX_RECV_SIZE = 64;
/*********
recv read write send 函数的返回值说明:
< 0 :出错;
= 0 :连接关闭;
> 0 : 接收/发送数据大小
除此之外,非阻塞模式下返回值 < 0 并且 (errno == EINTR || errno == EWOULDBLOCK || errno == EAGAIN)的情况下认为连接是正常的,继续接收/发送
*********/
Socket::Socket(ZL_SOCKET fd) : sockfd_(fd)
{
}
Socket::~Socket()
{
SocketUtil::closeSocket(sockfd_);
}
bool Socket::bind(const char* ip, int port)
{
if(!isValid())
{
return false;
}
return SocketUtil::bind(sockfd_, ip, port) == 0;
}
bool Socket::bind(const InetAddress& addr)
{
if (!isValid())
{
return false;
}
return SocketUtil::bind(sockfd_, addr.getSockAddrInet()) == 0;
}
bool Socket::listen(int backlog /*= 5*/) const
{
if(!isValid())
{
return false;
}
int ret = ZL_LISTEN(sockfd_, backlog);
if(ret == -1)
{
return false;
}
return true;
}
ZL_SOCKET Socket::accept(ZL_SOCKADDR_IN* peerAddr) const
{
return SocketUtil::accept(sockfd_, peerAddr);
}
ZL_SOCKET Socket::accept(InetAddress* peerAddr) const
{
ZL_SOCKADDR_IN addr;
::memset(&addr, 0, sizeof(addr));
ZL_SOCKET connfd = SocketUtil::accept(sockfd_, &addr);
if (connfd > 0)
{
peerAddr->setSockAddrInet(addr);
}
return connfd;
}
bool Socket::connect(const char* ip, int port)
{
if (!isValid())
{
return false;
}
return SocketUtil::connect(sockfd_, ip, port) == 0;
}
void Socket::close()
{
if (isValid())
{
ZL_CLOSE(sockfd_);
}
}
int Socket::send(const std::string& data) const
{
return send(data.c_str(), data.size());
}
int Socket::send(const void* data, size_t size)const
{
int len = ZL_SEND(sockfd_, data, size, 0);
//if (len == -1) // error
//else if (len == 0) // connection is closed
//else // ok
return len;
}
int Socket::recv(std::string& data) const
{
char buf[MAX_RECV_SIZE + 1] = { 0 };
while(true)
{
int len = recv(buf, MAX_RECV_SIZE, false);
if(len == 0) // 连接已关闭
{
return 0;
}
else if(len < 0)
{
if(SOCK_ERR_RW_RETRY(SOCKET_ERROR))
continue;
else if(SOCKET_ERROR == SOCK_ERR_EWOULDBLOCK)
break;
else
return len; // 发生了错误
break;
}
else
{
data.insert(data.end(), buf, buf + len);
if(len < MAX_RECV_SIZE) //全部接收完成
break;
}
}
return data.size();
}
int Socket::recv(void* data, int length, bool complete /*= false */) const
{
int received = 0;
if(complete)
{
while(received != length)
{
int len = ZL_RECV(sockfd_, (char *)data + received, length - received, 0);
if(len == -1)
{
printf("status == -1, errno == [%d], in Socket::recv\n", errno);
return len;
}
else if(len == 0)
{
return len;
}
else
{
received += len;
}
}
}
else
{
received = ZL_RECV(sockfd_, (char *)data, length, 0);
}
return received;
}
int Socket::sendTo(const std::string& data, int flags, InetAddress& sinaddr)const
{
return sendTo(data.c_str(), data.size(), flags, sinaddr);
}
int Socket::sendTo(const void* data, size_t size, int flags, InetAddress& sinaddr)const
{
int len = ZL_SENDTO(sockfd_, data, size, flags, sinaddr, sinaddr.addressLength());
return len;
}
int Socket::recvFrom(std::string& data, int flags, InetAddress& sinaddr)const
{
char buf[MAX_RECV_SIZE + 1] = { 0 };
while(true)
{
int len = recvFrom(buf, MAX_RECV_SIZE, flags, sinaddr);
if(len == -1 || len == 0)
break;
data.insert(data.end(), buf, buf + len);
if(len < MAX_RECV_SIZE)
break;
}
return data.size();
}
int Socket::recvFrom(void* data, int length, int flags, InetAddress& sinaddr)const
{
socklen_t slen;
int len = ZL_RECVFROM(sockfd_, data, length, flags, sinaddr, &slen);
if(slen != sinaddr.addressLength())
throw zl::base::Exception("unknown protocol type(in Socket::RecvFrom)");
return len;
}
bool Socket::setNonBlocking(bool on /*= true*/)
{
SocketUtil::setNonBlocking(sockfd_, on);
return true;
}
bool Socket::setNoDelay(bool on /*= true*/)
{
return SocketUtil::setNoDelay(sockfd_, on) == 0;
}
bool Socket::setReuseAddr(bool on /*= true*/)
{
return SocketUtil::setReuseAddr(sockfd_, on) == 0;
}
bool Socket::setKeepAlive(bool on /*= true*/)
{
return SocketUtil::setKeepAlive(sockfd_, on) == 0;
}
bool Socket::setSendBuffer(int size)
{
return SocketUtil::setSendBuffer(sockfd_, size) == 0;
}
bool Socket::getSendBuffer(int* size)
{
return SocketUtil::getSendBuffer(sockfd_, size) == 0;
}
bool Socket::setRecvBuffer(int size)
{
return SocketUtil::setRecvBuffer(sockfd_, size) == 0;
}
bool Socket::getRecvBuffer(int* size)
{
return SocketUtil::getRecvBuffer(sockfd_, size) == 0;
}
bool Socket::setSendTimeout(long long timeoutMs)
{
return SocketUtil::setSendTimeout(sockfd_, timeoutMs) == 0;
}
bool Socket::getSendTimeout(long long* timeoutMs)
{
return SocketUtil::getSendTimeout(sockfd_, timeoutMs) == 0;
}
bool Socket::setRecvTimeout(long long timeoutMs)
{
return SocketUtil::setRecvTimeout(sockfd_, timeoutMs) == 0;
}
bool Socket::getRecvTimeout(long long* timeoutMs)
{
return SocketUtil::getRecvTimeout(sockfd_, timeoutMs) == 0;
}
bool Socket::setLinger(bool enable, int waitTimeSec /*= 5*/)
{
linger lngr;
lngr.l_onoff = enable ? 1 : 0;
lngr.l_linger = waitTimeSec;
return ZL_SETSOCKOPT(sockfd_, SOL_SOCKET, SO_LINGER, &lngr, sizeof(linger)) == 0;
}
bool Socket::getLinger(bool& enable, int& waitTimeSec)
{
linger lngr;
if(ZL_GETSOCKOPT(sockfd_, SOL_SOCKET, SO_RCVTIMEO, &lngr, sizeof(lngr)) == 0)
{
enable = lngr.l_onoff;
waitTimeSec = lngr.l_linger;
return true;
}
return false;
}
NAMESPACE_ZL_NET_END
<commit_msg>update Socket.cpp<commit_after>#include "net/Socket.h"
#include "base/Exception.h"
#include "net/InetAddress.h"
NAMESPACE_ZL_NET_START
const static int MAX_RECV_SIZE = 64*1024; // 设置64k ?
/*********
recv read write send 函数的返回值说明:
< 0 :出错;
= 0 :连接关闭;
> 0 : 接收/发送数据大小
除此之外,非阻塞模式下返回值 < 0 并且 (errno == EINTR || errno == EWOULDBLOCK || errno == EAGAIN)的情况下认为连接是正常的,继续接收/发送
*********/
Socket::Socket(ZL_SOCKET fd) : sockfd_(fd)
{
}
Socket::~Socket()
{
SocketUtil::closeSocket(sockfd_);
}
bool Socket::bind(const char* ip, int port)
{
if(!isValid())
{
return false;
}
return SocketUtil::bind(sockfd_, ip, port) == 0;
}
bool Socket::bind(const InetAddress& addr)
{
if (!isValid())
{
return false;
}
return SocketUtil::bind(sockfd_, addr.getSockAddrInet()) == 0;
}
bool Socket::listen(int backlog /*= 5*/) const
{
if(!isValid())
{
return false;
}
int ret = ZL_LISTEN(sockfd_, backlog);
if(ret == -1)
{
return false;
}
return true;
}
ZL_SOCKET Socket::accept(ZL_SOCKADDR_IN* peerAddr) const
{
return SocketUtil::accept(sockfd_, peerAddr);
}
ZL_SOCKET Socket::accept(InetAddress* peerAddr) const
{
ZL_SOCKADDR_IN addr;
::memset(&addr, 0, sizeof(addr));
ZL_SOCKET connfd = SocketUtil::accept(sockfd_, &addr);
if (connfd > 0)
{
peerAddr->setSockAddrInet(addr);
}
return connfd;
}
bool Socket::connect(const char* ip, int port)
{
if (!isValid())
{
return false;
}
return SocketUtil::connect(sockfd_, ip, port) == 0;
}
void Socket::close()
{
if (isValid())
{
ZL_CLOSE(sockfd_);
}
}
int Socket::send(const std::string& data) const
{
return send(data.c_str(), data.size());
}
int Socket::send(const void* data, size_t size)const
{
int len = ZL_SEND(sockfd_, data, size, 0);
//if (len == -1) // error
//else if (len == 0) // connection is closed
//else // ok
return len;
}
int Socket::recv(std::string& data) const
{
char buf[MAX_RECV_SIZE + 1] = { 0 };
while(true)
{
int len = recv(buf, MAX_RECV_SIZE, false);
if(len == 0) // 连接已关闭
{
return 0;
}
else if(len < 0)
{
if(SOCK_ERR_RW_RETRY(SOCKET_ERROR))
continue;
else if(SOCKET_ERROR == SOCK_ERR_EWOULDBLOCK)
break;
else
return len; // 发生了错误
break;
}
else
{
data.insert(data.end(), buf, buf + len);
if(len < MAX_RECV_SIZE) //全部接收完成
break;
}
}
return data.size();
}
int Socket::recv(void* data, int length, bool complete /*= false */) const
{
int received = 0;
if(complete)
{
while(received != length)
{
int len = ZL_RECV(sockfd_, (char *)data + received, length - received, 0);
if(len == -1)
{
printf("status == -1, errno == [%d], in Socket::recv\n", errno);
return len;
}
else if(len == 0)
{
return len;
}
else
{
received += len;
}
}
}
else
{
received = ZL_RECV(sockfd_, (char *)data, length, 0);
}
return received;
}
int Socket::sendTo(const std::string& data, int flags, InetAddress& sinaddr)const
{
return sendTo(data.c_str(), data.size(), flags, sinaddr);
}
int Socket::sendTo(const void* data, size_t size, int flags, InetAddress& sinaddr)const
{
int len = ZL_SENDTO(sockfd_, data, size, flags, sinaddr, sinaddr.addressLength());
return len;
}
int Socket::recvFrom(std::string& data, int flags, InetAddress& sinaddr)const
{
char buf[MAX_RECV_SIZE + 1] = { 0 };
while(true)
{
int len = recvFrom(buf, MAX_RECV_SIZE, flags, sinaddr);
if(len == -1 || len == 0)
break;
data.insert(data.end(), buf, buf + len);
if(len < MAX_RECV_SIZE)
break;
}
return data.size();
}
int Socket::recvFrom(void* data, int length, int flags, InetAddress& sinaddr)const
{
socklen_t slen;
int len = ZL_RECVFROM(sockfd_, data, length, flags, sinaddr, &slen);
if(slen != sinaddr.addressLength())
throw zl::base::Exception("unknown protocol type(in Socket::RecvFrom)");
return len;
}
bool Socket::setNonBlocking(bool on /*= true*/)
{
SocketUtil::setNonBlocking(sockfd_, on);
return true;
}
bool Socket::setNoDelay(bool on /*= true*/)
{
return SocketUtil::setNoDelay(sockfd_, on) == 0;
}
bool Socket::setReuseAddr(bool on /*= true*/)
{
return SocketUtil::setReuseAddr(sockfd_, on) == 0;
}
bool Socket::setKeepAlive(bool on /*= true*/)
{
return SocketUtil::setKeepAlive(sockfd_, on) == 0;
}
bool Socket::setSendBuffer(int size)
{
return SocketUtil::setSendBuffer(sockfd_, size) == 0;
}
bool Socket::getSendBuffer(int* size)
{
return SocketUtil::getSendBuffer(sockfd_, size) == 0;
}
bool Socket::setRecvBuffer(int size)
{
return SocketUtil::setRecvBuffer(sockfd_, size) == 0;
}
bool Socket::getRecvBuffer(int* size)
{
return SocketUtil::getRecvBuffer(sockfd_, size) == 0;
}
bool Socket::setSendTimeout(long long timeoutMs)
{
return SocketUtil::setSendTimeout(sockfd_, timeoutMs) == 0;
}
bool Socket::getSendTimeout(long long* timeoutMs)
{
return SocketUtil::getSendTimeout(sockfd_, timeoutMs) == 0;
}
bool Socket::setRecvTimeout(long long timeoutMs)
{
return SocketUtil::setRecvTimeout(sockfd_, timeoutMs) == 0;
}
bool Socket::getRecvTimeout(long long* timeoutMs)
{
return SocketUtil::getRecvTimeout(sockfd_, timeoutMs) == 0;
}
bool Socket::setLinger(bool enable, int waitTimeSec /*= 5*/)
{
linger lngr;
lngr.l_onoff = enable ? 1 : 0;
lngr.l_linger = waitTimeSec;
return ZL_SETSOCKOPT(sockfd_, SOL_SOCKET, SO_LINGER, &lngr, sizeof(linger)) == 0;
}
bool Socket::getLinger(bool& enable, int& waitTimeSec)
{
linger lngr;
if(ZL_GETSOCKOPT(sockfd_, SOL_SOCKET, SO_RCVTIMEO, &lngr, sizeof(lngr)) == 0)
{
enable = lngr.l_onoff;
waitTimeSec = lngr.l_linger;
return true;
}
return false;
}
NAMESPACE_ZL_NET_END
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: pe_tydef.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2005-09-07 18:29:24 $
*
* 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 <precomp.h>
#include "pe_tydef.hxx"
// NOT FULLY DECLARED SERVICES
#include <ary/cpp/c_rwgate.hxx>
#include <ary/cpp/ca_type.hxx>
#include <all_toks.hxx>
#include "pe_type.hxx"
namespace cpp {
PE_Typedef::PE_Typedef(Cpp_PE * i_pParent )
: Cpp_PE(i_pParent),
pStati( new PeStatusArray<PE_Typedef> ),
// pSpType,
// pSpuType,
// sName
nType(0)
{
Setup_StatusFunctions();
pSpType = new SP_Type(*this);
pSpuType = new SPU_Type(*pSpType, 0, &PE_Typedef::SpReturn_Type);
}
PE_Typedef::~PE_Typedef()
{
}
void
PE_Typedef::Call_Handler( const cpp::Token & i_rTok )
{
pStati->Cur().Call_Handler(i_rTok.TypeId(), i_rTok.Text());
}
void
PE_Typedef::Setup_StatusFunctions()
{
typedef CallFunction<PE_Typedef>::F_Tok F_Tok;
static F_Tok stateF_start[] = { &PE_Typedef::On_start_typedef };
static INT16 stateT_start[] = { Tid_typedef };
static F_Tok stateF_expectName[] = { &PE_Typedef::On_expectName_Identifier };
static INT16 stateT_expectName[] = { Tid_Identifier };
static F_Tok stateF_afterName[] = { &PE_Typedef::On_afterName_Semicolon };
static INT16 stateT_afterName[] = { Tid_Semicolon };
SEMPARSE_CREATE_STATUS(PE_Typedef, start, Hdl_SyntaxError);
SEMPARSE_CREATE_STATUS(PE_Typedef, expectName, Hdl_SyntaxError);
SEMPARSE_CREATE_STATUS(PE_Typedef, afterName, Hdl_SyntaxError);
}
void
PE_Typedef::InitData()
{
pStati->SetCur(start);
sName.clear();
nType = 0;
}
void
PE_Typedef::TransferData()
{
pStati->SetCur(size_of_states);
ary::cpp::Typedef &
rTypedef = Env().AryGate().Store_Typedef(
Env().Context(), sName, nType );
Env().Event_Store_Typedef(rTypedef);
}
void
PE_Typedef::Hdl_SyntaxError( const char * i_sText)
{
StdHandlingOfSyntaxError(i_sText);
}
void
PE_Typedef::SpReturn_Type()
{
pStati->SetCur(expectName);
nType = pSpuType->Child().Result_Type().Id();
}
void
PE_Typedef::On_start_typedef( const char * )
{
pSpuType->Push(done);
}
void
PE_Typedef::On_expectName_Identifier( const char * i_sText )
{
SetTokenResult(done, stay);
pStati->SetCur(afterName);
sName = i_sText;
}
void
PE_Typedef::On_afterName_Semicolon( const char * )
{
SetTokenResult(done, pop_success);
}
} // namespace cpp
<commit_msg>INTEGRATION: CWS pchfix02 (1.4.30); FILE MERGED 2006/09/01 17:15:44 kaib 1.4.30.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: pe_tydef.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: obo $ $Date: 2006-09-16 17:03: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
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_autodoc.hxx"
#include <precomp.h>
#include "pe_tydef.hxx"
// NOT FULLY DECLARED SERVICES
#include <ary/cpp/c_rwgate.hxx>
#include <ary/cpp/ca_type.hxx>
#include <all_toks.hxx>
#include "pe_type.hxx"
namespace cpp {
PE_Typedef::PE_Typedef(Cpp_PE * i_pParent )
: Cpp_PE(i_pParent),
pStati( new PeStatusArray<PE_Typedef> ),
// pSpType,
// pSpuType,
// sName
nType(0)
{
Setup_StatusFunctions();
pSpType = new SP_Type(*this);
pSpuType = new SPU_Type(*pSpType, 0, &PE_Typedef::SpReturn_Type);
}
PE_Typedef::~PE_Typedef()
{
}
void
PE_Typedef::Call_Handler( const cpp::Token & i_rTok )
{
pStati->Cur().Call_Handler(i_rTok.TypeId(), i_rTok.Text());
}
void
PE_Typedef::Setup_StatusFunctions()
{
typedef CallFunction<PE_Typedef>::F_Tok F_Tok;
static F_Tok stateF_start[] = { &PE_Typedef::On_start_typedef };
static INT16 stateT_start[] = { Tid_typedef };
static F_Tok stateF_expectName[] = { &PE_Typedef::On_expectName_Identifier };
static INT16 stateT_expectName[] = { Tid_Identifier };
static F_Tok stateF_afterName[] = { &PE_Typedef::On_afterName_Semicolon };
static INT16 stateT_afterName[] = { Tid_Semicolon };
SEMPARSE_CREATE_STATUS(PE_Typedef, start, Hdl_SyntaxError);
SEMPARSE_CREATE_STATUS(PE_Typedef, expectName, Hdl_SyntaxError);
SEMPARSE_CREATE_STATUS(PE_Typedef, afterName, Hdl_SyntaxError);
}
void
PE_Typedef::InitData()
{
pStati->SetCur(start);
sName.clear();
nType = 0;
}
void
PE_Typedef::TransferData()
{
pStati->SetCur(size_of_states);
ary::cpp::Typedef &
rTypedef = Env().AryGate().Store_Typedef(
Env().Context(), sName, nType );
Env().Event_Store_Typedef(rTypedef);
}
void
PE_Typedef::Hdl_SyntaxError( const char * i_sText)
{
StdHandlingOfSyntaxError(i_sText);
}
void
PE_Typedef::SpReturn_Type()
{
pStati->SetCur(expectName);
nType = pSpuType->Child().Result_Type().Id();
}
void
PE_Typedef::On_start_typedef( const char * )
{
pSpuType->Push(done);
}
void
PE_Typedef::On_expectName_Identifier( const char * i_sText )
{
SetTokenResult(done, stay);
pStati->SetCur(afterName);
sName = i_sText;
}
void
PE_Typedef::On_afterName_Semicolon( const char * )
{
SetTokenResult(done, pop_success);
}
} // namespace cpp
<|endoftext|>
|
<commit_before>inline
grass_points::grass_points( const std::string in_path,
const std::string in_actionNames,
const int in_scale_factor,
const int in_shift,
const int in_scene, //only for kth
const int in_segment_length,
const int in_p
)
:path(in_path), actionNames(in_actionNames), scale_factor(in_scale_factor), shift(in_shift), total_scenes(in_scene), segment_length(in_segment_length), p(in_p)
{
actions.load( actionNames );
}
inline
void
grass_points::calculate( field<string> in_all_people, int in_dim )
{
all_people = in_all_people;
dim = in_dim;
int n_actions = actions.n_rows;
int n_peo = all_people.n_rows;
//all_people.print("people");
for (int sc = 1; sc<=total_scenes; ++sc) //scene
{
for (int pe = 0; pe< n_peo; ++pe)
{
for (int act=0; act<n_actions; ++act)
{
std::stringstream load_folder;
std::stringstream load_feat_video_i;
std::stringstream load_labels_video_i;
//cout << "Loading.." << endl;
load_folder << path << "/kth-features/sc" << sc << "/scale" << scale_factor << "-shift"<< shift ;
load_feat_video_i << load_folder.str() << "/" << all_people (pe) << "_" << actions(act) << "_dim" << dim << ".h5";
load_labels_video_i << load_folder.str() << "/lab_" << all_people (pe) << "_" << actions(act) << "_dim" << dim << ".h5";
//For one Video
if( !( ( sc==3 && pe==12) && act==1) ) //person13_handclapping_d3 doesn't exist
{
one_video(load_feat_video_i.str(), load_labels_video_i.str(), sc, pe, act );
}
//getchar();
}
}
}
}
inline
void
grass_points::one_video( std::string load_feat_video_i, std::string load_labels_video_i, int sc, int pe, int act )
{
cout << load_feat_video_i << endl;
mat mat_features_video_i;
vec lab_video_i;
mat_features_video_i.load( load_feat_video_i, hdf5_binary );
lab_video_i.load( load_labels_video_i, hdf5_binary );
int n_vec = lab_video_i.n_elem;
int last = lab_video_i( n_vec - 1 );
//cout << last << endl;
int seg = 0;
std::stringstream save_folder;
save_folder << "./kth-grass-point/sc" << sc << "/scale" << scale_factor << "-shift"<< shift ;
for (int l=2; l<last-segment_length; l = l+4 )
{
std::vector<vec> feat_seg;
for (int j=l; j< l + segment_length; ++j)
{
//k++;
//cout << " " << j;
uvec indices = find(lab_video_i == j);
mat feat_fr = mat_features_video_i.cols(indices);
for (int v=0; v < feat_fr.n_cols; ++v)
{
vec sample = feat_fr.col(v);
feat_seg.push_back(sample);
}
}
cout << feat_seg.size() << endl;
if (feat_seg.size()>100) // Cuando en el segmento hay mas de 100 vectores
{
mat mat_feat_seg(dim,feat_seg.size());
for (uword i = 0; i < feat_seg.size(); ++i)
{
mat_feat_seg.col(i) = feat_seg.at(i);
}
mat U; vec s; mat V;
svd(U,s,V,mat_feat_seg);
mat Gnp = U.cols(0,p-1);
std::stringstream save_Gnp;
cout << save_folder.str() << endl;
save_Gnp << save_folder.str() << "/grass_pt" << seg << "_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim << ".h5";
cout << save_Gnp.str() << endl;
Gnp.save( save_Gnp.str(), hdf5_binary );
seg++;
}
else {
//cout << " " << stat_seg.count();
//getchar();
}
}
std::stringstream save_seg;
vec total_seg;
total_seg.zeros(1);
total_seg( 0 ) = seg;
save_seg << save_folder.str() << "/num_seg_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim << ".dat";
total_seg.save( save_seg.str(), raw_ascii );
cout << "Total # of segments " << seg << endl;
//cout << "press a key " ;
//getchar();
}
<commit_msg>Run in wanda<commit_after>inline
grass_points::grass_points( const std::string in_path,
const std::string in_actionNames,
const int in_scale_factor,
const int in_shift,
const int in_scene, //only for kth
const int in_segment_length,
const int in_p
)
:path(in_path), actionNames(in_actionNames), scale_factor(in_scale_factor), shift(in_shift), total_scenes(in_scene), segment_length(in_segment_length), p(in_p)
{
actions.load( actionNames );
}
inline
void
grass_points::calculate( field<string> in_all_people, int in_dim )
{
all_people = in_all_people;
dim = in_dim;
int n_actions = actions.n_rows;
int n_peo = all_people.n_rows;
//all_people.print("people");
for (int sc = 1; sc<=total_scenes; ++sc) //scene
{
for (int pe = 0; pe< n_peo; ++pe)
{
for (int act=0; act<n_actions; ++act)
{
std::stringstream load_folder;
std::stringstream load_feat_video_i;
std::stringstream load_labels_video_i;
//cout << "Loading.." << endl;
load_folder << path << "/kth-features/sc" << sc << "/scale" << scale_factor << "-shift"<< shift ;
load_feat_video_i << load_folder.str() << "/" << all_people (pe) << "_" << actions(act) << "_dim" << dim << ".h5";
load_labels_video_i << load_folder.str() << "/lab_" << all_people (pe) << "_" << actions(act) << "_dim" << dim << ".h5";
//For one Video
if( !( ( sc==3 && pe==12) && act==1) ) //person13_handclapping_d3 doesn't exist
{
one_video(load_feat_video_i.str(), load_labels_video_i.str(), sc, pe, act );
}
//getchar();
}
}
}
}
inline
void
grass_points::one_video( std::string load_feat_video_i, std::string load_labels_video_i, int sc, int pe, int act )
{
cout << load_feat_video_i << endl;
mat mat_features_video_i;
vec lab_video_i;
mat_features_video_i.load( load_feat_video_i, hdf5_binary );
lab_video_i.load( load_labels_video_i, hdf5_binary );
int n_vec = lab_video_i.n_elem;
int last = lab_video_i( n_vec - 1 );
//cout << last << endl;
int seg = 0;
std::stringstream save_folder;
save_folder << "./kth-grass-point/sc" << sc << "/scale" << scale_factor << "-shift"<< shift ;
for (int l=2; l<last-segment_length; l = l+4 )
{
std::vector<vec> feat_seg;
for (int j=l; j< l + segment_length; ++j)
{
//k++;
//cout << " " << j;
uvec indices = find(lab_video_i == j);
mat feat_fr = mat_features_video_i.cols(indices);
for (int v=0; v < feat_fr.n_cols; ++v)
{
vec sample = feat_fr.col(v);
feat_seg.push_back(sample);
}
}
cout << feat_seg.size() << endl;
if (feat_seg.size()>100) // Cuando en el segmento hay mas de 100 vectores
{
mat mat_feat_seg(dim,feat_seg.size());
for (uword i = 0; i < feat_seg.size(); ++i)
{
mat_feat_seg.col(i) = feat_seg.at(i);
}
mat U; vec s; mat V;
svd(U,s,V,mat_feat_seg);
mat Gnp = U.cols(0,p-1);
std::stringstream save_Gnp;
//cout << save_folder.str() << endl;
save_Gnp << save_folder.str() << "/grass_pt" << seg << "_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim << ".h5";
//cout << save_Gnp.str() << endl;
Gnp.save( save_Gnp.str(), hdf5_binary );
seg++;
}
else {
//cout << " " << stat_seg.count();
//getchar();
}
}
std::stringstream save_seg;
vec total_seg;
total_seg.zeros(1);
total_seg( 0 ) = seg;
save_seg << save_folder.str() << "/num_seg_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim << ".dat";
total_seg.save( save_seg.str(), raw_ascii );
cout << "Total # of segments " << seg << endl;
//cout << "press a key " ;
//getchar();
}
<|endoftext|>
|
<commit_before>/******************************************************************************
* _ _____ __________ *
* | | / / _ | / __/_ __/ Visibility *
* | |/ / __ |_\ \ / / Across *
* |___/_/ |_/___/ /_/ Space and Time *
* *
* This file is part of VAST. It is subject to the license terms in the *
* LICENSE file found in the top-level directory of this distribution and at *
* http://vast.io/license. No part of VAST, including this file, may be *
* copied, modified, propagated, or distributed except according to the terms *
* contained in the LICENSE file. *
******************************************************************************/
#include <array>
#include <cstdint>
#include <string>
#include <type_traits>
#include <variant>
#include <caf/intrusive_ptr.hpp>
#include <caf/make_counted.hpp>
#include <caf/ref_counted.hpp>
#include "vast/aliases.hpp"
#include "vast/data.hpp"
#include "vast/time.hpp"
#include "vast/detail/assert.hpp"
#include "vast/detail/iterator.hpp"
#include "vast/detail/operators.hpp"
#include "vast/detail/type_traits.hpp"
namespace vast {
/// A type-safe overlay over an immutable sequence of bytes.
template <class>
struct view;
/// @relates view
template <class T>
using view_t = typename view<T>::type;
/// @relates view
template <>
struct view<boolean> {
using type = boolean;
};
/// @relates view
template <>
struct view<integer> {
using type = integer;
};
/// @relates view
template <>
struct view<count> {
using type = count;
};
/// @relates view
template <>
struct view<real> {
using type = real;
};
/// @relates view
template <>
struct view<timespan> {
using type = timespan;
};
/// @relates view
template <>
struct view<timestamp> {
using type = timestamp;
};
/// @relates view
template <>
struct view<std::string> {
using type = std::string_view;
};
/// @relates view
class pattern_view : detail::totally_ordered<pattern_view> {
public:
static pattern glob(std::string_view x);
pattern_view(const pattern& x);
bool match(std::string_view x) const;
bool search(std::string_view x) const;
std::string_view string() const;
friend bool operator==(pattern_view x, pattern_view y) noexcept;
friend bool operator<(pattern_view x, pattern_view y) noexcept;
private:
std::string_view pattern_;
};
//// @relates view
template <>
struct view<pattern> {
using type = pattern_view;
};
/// @relates view
class address_view : detail::totally_ordered<address_view> {
public:
address_view(const address& x);
// See vast::address for documentation.
bool is_v4() const;
bool is_v6() const;
bool is_loopback() const;
bool is_broadcast() const;
bool is_multicast() const;
bool mask(unsigned top_bits_to_keep) const;
bool compare(address_view other, size_t k) const;
const std::array<uint8_t, 16>& data() const;
friend bool operator==(address_view x, address_view y) noexcept;
friend bool operator<(address_view x, address_view y) noexcept;
private:
const std::array<uint8_t, 16>* data_;
};
//// @relates view
template <>
struct view<address> {
using type = address_view;
};
/// @relates view
class subnet_view : detail::totally_ordered<subnet_view> {
public:
subnet_view(const subnet& x);
// See vast::subnet for documentation.
bool contains(address_view x) const;
bool contains(subnet_view x) const;
address_view network() const;
uint8_t length() const;
friend bool operator==(subnet_view x, subnet_view y) noexcept;
friend bool operator<(subnet_view x, subnet_view y) noexcept;
private:
address_view network_;
uint8_t length_;
};
//// @relates view
template <>
struct view<subnet> {
using type = subnet_view;
};
//// @relates view
template <>
struct view<port> {
using type = port;
};
struct vector_view_ptr;
struct set_view_ptr;
struct map_view_ptr;
/// @relates view
template <>
struct view<vector> {
using type = vector_view_ptr;
};
/// @relates view
template <>
struct view<set> {
using type = set_view_ptr;
};
/// @relates view
template <>
struct view<map> {
using type = map_view_ptr;
};
/// A type-erased view over variout types of data.
/// @relates view
using data_view = std::variant<
view_t<boolean>,
view_t<integer>,
view_t<count>,
view_t<real>,
view_t<timespan>,
view_t<timestamp>,
view_t<std::string>,
view_t<pattern>,
view_t<address>,
view_t<subnet>,
view_t<port>,
view_t<vector>,
view_t<set>,
view_t<map>
>;
/// @relates view
template <>
struct view<data> {
using type = data_view;
};
template <class T>
struct container_view;
/// @relates view
template <class T>
using container_view_ptr = caf::intrusive_ptr<container_view<T>>;
namespace detail {
/// @relates view
template <class T>
class container_view_iterator
: public detail::iterator_facade<
container_view_iterator<T>,
data_view,
std::random_access_iterator_tag,
data_view
> {
friend iterator_access;
public:
container_view_iterator(container_view_ptr<T> x, size_t pos)
: view_{x.get()}, position_{pos} {
// nop
}
auto dereference() const {
return view_->at(position_);
}
void increment() {
++position_;
}
void decremenet() {
--position_;
}
template <class N>
void advance(N n) {
position_ += n;
}
bool equals(container_view_iterator other) const {
return view_ == other.view_ && position_ == other.position_;
}
auto distance_to(container_view_iterator other) const {
return other.position_ - position_;
}
private:
typename container_view_ptr<T>::const_pointer view_;
size_t position_;
};
} // namespace detail
/// Base class for container views.
/// @relates view
template <class T>
struct container_view : caf::ref_counted {
using value_type = T;
using size_type = size_t;
using iterator = detail::container_view_iterator<T>;
using const_iterator = iterator;
virtual ~container_view() = default;
iterator begin() const {
// TODO: const_cast okay?
return {container_view_ptr<T>{const_cast<container_view*>(this), true}, 0};
}
iterator end() const {
// TODO: see above
return {container_view_ptr<T>{const_cast<container_view*>(this), true}, size()};
}
/// Retrieves a specific element.
/// @param i The position of the element to retrieve.
/// @returns A view to the element at position *i*.
virtual value_type at(size_type i) const = 0;
/// @returns The number of elements in the container.
virtual size_type size() const noexcept = 0;
};
// @relates view
struct vector_view_ptr : container_view_ptr<data_view> {};
// @relates view
struct set_view_ptr : container_view_ptr<data_view> {};
// @relates view
struct map_view_ptr : container_view_ptr<std::pair<data_view, data_view>> {};
/// A view over a @ref vector.
/// @relates view
class default_vector_view
: public container_view<data_view>,
detail::totally_ordered<default_vector_view> {
public:
default_vector_view(const vector& xs);
value_type at(size_type i) const override;
size_type size() const noexcept override;
private:
const vector& xs_;
};
/// A view over a @ref set.
/// @relates view
class default_set_view
: public container_view<data_view>,
detail::totally_ordered<default_set_view> {
public:
default_set_view(const set& xs);
value_type at(size_type i) const override;
size_type size() const noexcept override;
private:
const set& xs_;
};
/// A view over a @ref map.
/// @relates view
class default_map_view
: public container_view<std::pair<data_view, data_view>>,
detail::totally_ordered<default_map_view> {
public:
default_map_view(const map& xs);
value_type at(size_type i) const override;
size_type size() const noexcept override;
private:
const map& xs_;
};
/// Creates a view from a specific type.
/// @relates view
template <class T>
view_t<T> make_view(const T& x) {
constexpr auto directly_constructible
= detail::is_any_v<T, boolean, integer, count, real, timespan,
timestamp, std::string, pattern, address, subnet, port>;
if constexpr (directly_constructible) {
return x;
} else if constexpr (std::is_same_v<T, vector>) {
return vector_view_ptr{caf::make_counted<default_vector_view>(x)};
} else if constexpr (std::is_same_v<T, set>) {
return set_view_ptr{caf::make_counted<default_set_view>(x)};
} else if constexpr (std::is_same_v<T, map>) {
return map_view_ptr{caf::make_counted<default_map_view>(x)};
} else {
VAST_ASSERT(!"missing branch");
return {};
}
}
/// @relates view
data_view make_view(const data& x);
/// Creates a type-erased data view from a specific type.
/// @relates view
template <class T>
data_view make_data_view(const T& x) {
return make_view(x);
}
} // namespace vast
<commit_msg>Fix half-hearted reference count fix<commit_after>/******************************************************************************
* _ _____ __________ *
* | | / / _ | / __/_ __/ Visibility *
* | |/ / __ |_\ \ / / Across *
* |___/_/ |_/___/ /_/ Space and Time *
* *
* This file is part of VAST. It is subject to the license terms in the *
* LICENSE file found in the top-level directory of this distribution and at *
* http://vast.io/license. No part of VAST, including this file, may be *
* copied, modified, propagated, or distributed except according to the terms *
* contained in the LICENSE file. *
******************************************************************************/
#include <array>
#include <cstdint>
#include <string>
#include <type_traits>
#include <variant>
#include <caf/intrusive_ptr.hpp>
#include <caf/make_counted.hpp>
#include <caf/ref_counted.hpp>
#include "vast/aliases.hpp"
#include "vast/data.hpp"
#include "vast/time.hpp"
#include "vast/detail/assert.hpp"
#include "vast/detail/iterator.hpp"
#include "vast/detail/operators.hpp"
#include "vast/detail/type_traits.hpp"
namespace vast {
/// A type-safe overlay over an immutable sequence of bytes.
template <class>
struct view;
/// @relates view
template <class T>
using view_t = typename view<T>::type;
/// @relates view
template <>
struct view<boolean> {
using type = boolean;
};
/// @relates view
template <>
struct view<integer> {
using type = integer;
};
/// @relates view
template <>
struct view<count> {
using type = count;
};
/// @relates view
template <>
struct view<real> {
using type = real;
};
/// @relates view
template <>
struct view<timespan> {
using type = timespan;
};
/// @relates view
template <>
struct view<timestamp> {
using type = timestamp;
};
/// @relates view
template <>
struct view<std::string> {
using type = std::string_view;
};
/// @relates view
class pattern_view : detail::totally_ordered<pattern_view> {
public:
static pattern glob(std::string_view x);
pattern_view(const pattern& x);
bool match(std::string_view x) const;
bool search(std::string_view x) const;
std::string_view string() const;
friend bool operator==(pattern_view x, pattern_view y) noexcept;
friend bool operator<(pattern_view x, pattern_view y) noexcept;
private:
std::string_view pattern_;
};
//// @relates view
template <>
struct view<pattern> {
using type = pattern_view;
};
/// @relates view
class address_view : detail::totally_ordered<address_view> {
public:
address_view(const address& x);
// See vast::address for documentation.
bool is_v4() const;
bool is_v6() const;
bool is_loopback() const;
bool is_broadcast() const;
bool is_multicast() const;
bool mask(unsigned top_bits_to_keep) const;
bool compare(address_view other, size_t k) const;
const std::array<uint8_t, 16>& data() const;
friend bool operator==(address_view x, address_view y) noexcept;
friend bool operator<(address_view x, address_view y) noexcept;
private:
const std::array<uint8_t, 16>* data_;
};
//// @relates view
template <>
struct view<address> {
using type = address_view;
};
/// @relates view
class subnet_view : detail::totally_ordered<subnet_view> {
public:
subnet_view(const subnet& x);
// See vast::subnet for documentation.
bool contains(address_view x) const;
bool contains(subnet_view x) const;
address_view network() const;
uint8_t length() const;
friend bool operator==(subnet_view x, subnet_view y) noexcept;
friend bool operator<(subnet_view x, subnet_view y) noexcept;
private:
address_view network_;
uint8_t length_;
};
//// @relates view
template <>
struct view<subnet> {
using type = subnet_view;
};
//// @relates view
template <>
struct view<port> {
using type = port;
};
struct vector_view_ptr;
struct set_view_ptr;
struct map_view_ptr;
/// @relates view
template <>
struct view<vector> {
using type = vector_view_ptr;
};
/// @relates view
template <>
struct view<set> {
using type = set_view_ptr;
};
/// @relates view
template <>
struct view<map> {
using type = map_view_ptr;
};
/// A type-erased view over variout types of data.
/// @relates view
using data_view = std::variant<
view_t<boolean>,
view_t<integer>,
view_t<count>,
view_t<real>,
view_t<timespan>,
view_t<timestamp>,
view_t<std::string>,
view_t<pattern>,
view_t<address>,
view_t<subnet>,
view_t<port>,
view_t<vector>,
view_t<set>,
view_t<map>
>;
/// @relates view
template <>
struct view<data> {
using type = data_view;
};
template <class T>
struct container_view;
/// @relates view
template <class T>
using container_view_ptr = caf::intrusive_ptr<container_view<T>>;
namespace detail {
/// @relates view
template <class T>
class container_view_iterator
: public detail::iterator_facade<
container_view_iterator<T>,
data_view,
std::random_access_iterator_tag,
data_view
> {
friend iterator_access;
public:
container_view_iterator(typename container_view_ptr<T>::const_pointer ptr,
size_t pos)
: view_{ptr}, position_{pos} {
// nop
}
auto dereference() const {
return view_->at(position_);
}
void increment() {
++position_;
}
void decremenet() {
--position_;
}
template <class N>
void advance(N n) {
position_ += n;
}
bool equals(container_view_iterator other) const {
return view_ == other.view_ && position_ == other.position_;
}
auto distance_to(container_view_iterator other) const {
return other.position_ - position_;
}
private:
typename container_view_ptr<T>::const_pointer view_;
size_t position_;
};
} // namespace detail
/// Base class for container views.
/// @relates view
template <class T>
struct container_view : caf::ref_counted {
using value_type = T;
using size_type = size_t;
using iterator = detail::container_view_iterator<T>;
using const_iterator = iterator;
virtual ~container_view() = default;
iterator begin() const {
// TODO: const_cast okay?
return {const_cast<container_view*>(this), 0};
}
iterator end() const {
// TODO: see above
return {const_cast<container_view*>(this), size()};
}
/// Retrieves a specific element.
/// @param i The position of the element to retrieve.
/// @returns A view to the element at position *i*.
virtual value_type at(size_type i) const = 0;
/// @returns The number of elements in the container.
virtual size_type size() const noexcept = 0;
};
// @relates view
struct vector_view_ptr : container_view_ptr<data_view> {};
// @relates view
struct set_view_ptr : container_view_ptr<data_view> {};
// @relates view
struct map_view_ptr : container_view_ptr<std::pair<data_view, data_view>> {};
/// A view over a @ref vector.
/// @relates view
class default_vector_view
: public container_view<data_view>,
detail::totally_ordered<default_vector_view> {
public:
default_vector_view(const vector& xs);
value_type at(size_type i) const override;
size_type size() const noexcept override;
private:
const vector& xs_;
};
/// A view over a @ref set.
/// @relates view
class default_set_view
: public container_view<data_view>,
detail::totally_ordered<default_set_view> {
public:
default_set_view(const set& xs);
value_type at(size_type i) const override;
size_type size() const noexcept override;
private:
const set& xs_;
};
/// A view over a @ref map.
/// @relates view
class default_map_view
: public container_view<std::pair<data_view, data_view>>,
detail::totally_ordered<default_map_view> {
public:
default_map_view(const map& xs);
value_type at(size_type i) const override;
size_type size() const noexcept override;
private:
const map& xs_;
};
/// Creates a view from a specific type.
/// @relates view
template <class T>
view_t<T> make_view(const T& x) {
constexpr auto directly_constructible
= detail::is_any_v<T, boolean, integer, count, real, timespan,
timestamp, std::string, pattern, address, subnet, port>;
if constexpr (directly_constructible) {
return x;
} else if constexpr (std::is_same_v<T, vector>) {
return vector_view_ptr{caf::make_counted<default_vector_view>(x)};
} else if constexpr (std::is_same_v<T, set>) {
return set_view_ptr{caf::make_counted<default_set_view>(x)};
} else if constexpr (std::is_same_v<T, map>) {
return map_view_ptr{caf::make_counted<default_map_view>(x)};
} else {
VAST_ASSERT(!"missing branch");
return {};
}
}
/// @relates view
data_view make_view(const data& x);
/// Creates a type-erased data view from a specific type.
/// @relates view
template <class T>
data_view make_data_view(const T& x) {
return make_view(x);
}
} // namespace vast
<|endoftext|>
|
<commit_before>// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <vespa/fnet/frt/supervisor.h>
#include <vespa/fnet/frt/target.h>
#include <vespa/config/config.h>
#include <vespa/config/frt/frtconfigrequestfactory.h>
#include <vespa/config/frt/frtconnection.h>
#include <vespa/config/common/payload_converter.h>
#include <vespa/fastos/app.h>
#include <string>
#include <sstream>
#include <fstream>
#include <vespa/log/log.h>
LOG_SETUP("vespa-get-config");
using namespace config;
class GetConfig : public FastOS_Application
{
private:
std::unique_ptr<fnet::frt::StandaloneFRT> _server;
FRT_Target *_target;
GetConfig(const GetConfig &);
GetConfig &operator=(const GetConfig &);
public:
GetConfig() : _server(), _target(nullptr) {}
~GetConfig() override;
int usage();
void initRPC(const char *spec);
void finiRPC();
int Main() override;
};
GetConfig::~GetConfig()
{
LOG_ASSERT( ! _server);
LOG_ASSERT(_target == nullptr);
}
int
GetConfig::usage()
{
fprintf(stderr, "usage: %s -n name -i configId\n", _argv[0]);
fprintf(stderr, "-n name (config name, including namespace, on the form <namespace>.<name>)\n");
fprintf(stderr, "-i configId (config id, optional)\n");
fprintf(stderr, "-j (output config as json, optional)\n");
fprintf(stderr, "-l (output config in legacy cfg format, optional)\n");
fprintf(stderr, "-g generation (config generation, optional)\n");
fprintf(stderr, "-a schema (config def schema file, optional)\n");
fprintf(stderr, "-v defVersion (config definition version, optional, deprecated)\n");
fprintf(stderr, "-m defMd5 (definition md5sum, optional)\n");
fprintf(stderr, "-t serverTimeout (server timeout in seconds, default 3)\n");
fprintf(stderr, "-w timeout (timeout in seconds, default 10)\n");
fprintf(stderr, "-s server (server hostname, default localhost)\n");
fprintf(stderr, "-p port (proxy/server port number, default 19090)\n");
fprintf(stderr, "-r traceLevel (tracelevel to use in request, default 0\n");
fprintf(stderr, "-V vespaVersion (vespa version to use in request, optional\n");
fprintf(stderr, "-d (debug mode)\n");
fprintf(stderr, "-h (This help text)\n");
return 1;
}
void
GetConfig::initRPC(const char *spec)
{
_server = std::make_unique<fnet::frt::StandaloneFRT>();
_target = _server->supervisor().GetTarget(spec);
}
void
GetConfig::finiRPC()
{
if (_target != nullptr) {
_target->SubRef();
_target = nullptr;
}
_server.reset();
}
int
GetConfig::Main()
{
bool debugging = false;
int c = -1;
std::vector<vespalib::string> defSchema;
const char *schema = nullptr;
const char *defName = nullptr;
const char *defMD5 = "";
std::string defNamespace("config");
const char *serverHost = "localhost";
const char *configId = getenv("VESPA_CONFIG_ID");
bool printAsJson = false;
int traceLevel = config::protocol::readTraceLevel();
const char *vespaVersionString = nullptr;
int64_t generation = 0;
if (configId == nullptr) {
configId = "";
}
const char *configXxhash64 = "";
int serverTimeout = 3;
int clientTimeout = 10;
int serverPort = 19090;
const char *optArg = nullptr;
int optInd = 0;
while ((c = GetOpt("a:n:v:g:i:jlm:c:t:V:w:r:s:p:dh", optArg, optInd)) != -1) {
int retval = 1;
switch (c) {
case 'a':
schema = optArg;
break;
case 'n':
defName = optArg;
break;
case 'v':
break;
case 'g':
generation = atoll(optArg);
break;
case 'i':
configId = optArg;
break;
case 'j':
printAsJson = true;
break;
case 'l':
printAsJson = false;
break;
case 'm':
defMD5 = optArg;
break;
case 't':
serverTimeout = atoi(optArg);
break;
case 'w':
clientTimeout = atoi(optArg);
break;
case 'r':
traceLevel = atoi(optArg);
break;
case 'V':
vespaVersionString = optArg;
break;
case 's':
serverHost = optArg;
break;
case 'p':
serverPort = atoi(optArg);
break;
case 'd':
debugging = true;
break;
case 'h':
retval = 0;
[[fallthrough]];
case '?':
default:
usage();
return retval;
}
}
if (defName == nullptr || serverPort == 0) {
usage();
return 1;
}
if (strchr(defName, '.') != nullptr) {
const char *tmp = defName;
defName = strrchr(defName, '.');
defName++;
defNamespace = std::string(tmp, defName - tmp - 1);
}
if (schema != nullptr) {
std::ifstream is;
is.open(schema);
std::string item;
while (std::getline(is, item)) {
if (item.find("namespace=") == std::string::npos) {
defSchema.push_back(item);
}
}
is.close();
}
std::ostringstream tmp;
tmp << "tcp/";
tmp << serverHost;
tmp << ":";
tmp << serverPort;
std::string sspec = tmp.str();
const char *spec = sspec.c_str();
if (debugging) {
printf("connecting to '%s'\n", spec);
}
initRPC(spec);
auto vespaVersion = VespaVersion::getCurrentVersion();
if (vespaVersionString != nullptr) {
vespaVersion = VespaVersion::fromString(vespaVersionString);
}
FRTConfigRequestFactory requestFactory(traceLevel, vespaVersion, config::protocol::readProtocolCompressionType());
FRTConnection connection(spec, _server->supervisor(), TimingValues());
ConfigKey key(configId, defName, defNamespace, defMD5, defSchema);
ConfigState state(configXxhash64, generation, false);
FRTConfigRequest::UP request = requestFactory.createConfigRequest(key, &connection, state, serverTimeout * 1000);
_target->InvokeSync(request->getRequest(), clientTimeout); // seconds
ConfigResponse::UP response = request->createResponse(request->getRequest());
response->validateResponse();
if (response->isError()) {
fprintf(stderr, "error %d: %s\n",
response->errorCode(), response->errorMessage().c_str());
} else {
response->fill();
ConfigKey rKey(response->getKey());
ConfigState rState(response->getConfigState());
ConfigValue rValue(response->getValue());
if (debugging) {
printf("defName %s\n", rKey.getDefName().c_str());
printf("defMD5 %s\n", rKey.getDefMd5().c_str());
printf("defNamespace %s\n", rKey.getDefNamespace().c_str());
printf("configID %s\n", rKey.getConfigId().c_str());
printf("configXxhash64 %s\n", rState.xxhash64.c_str());
printf("generation %" PRId64 "\n", rState.generation);
printf("trace %s\n", response->getTrace().toString().c_str());
} else if (traceLevel > 0) {
printf("trace %s\n", response->getTrace().toString().c_str());
}
// TODO: Make printAsJson default
if (printAsJson) {
printf("%s\n", rValue.asJson().c_str());
} else {
std::vector<vespalib::string> lines = rValue.getLegacyFormat();
for (uint32_t j = 0; j < lines.size(); j++) {
printf("%s\n", lines[j].c_str());
}
}
}
finiRPC();
return 0;
}
int main(int argc, char **argv)
{
GetConfig app;
return app.Entry(argc, argv);
}
<commit_msg>Use installed config schema if none is given as option<commit_after>// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <vespa/fnet/frt/supervisor.h>
#include <vespa/fnet/frt/target.h>
#include <vespa/config/config.h>
#include <vespa/config/frt/frtconfigrequestfactory.h>
#include <vespa/config/frt/frtconnection.h>
#include <vespa/config/common/payload_converter.h>
#include <vespa/fastos/app.h>
#include <string>
#include <sstream>
#include <fstream>
#include <vespa/log/log.h>
LOG_SETUP("vespa-get-config");
using namespace config;
class GetConfig : public FastOS_Application
{
private:
std::unique_ptr<fnet::frt::StandaloneFRT> _server;
FRT_Target *_target;
GetConfig(const GetConfig &);
GetConfig &operator=(const GetConfig &);
public:
GetConfig() : _server(), _target(nullptr) {}
~GetConfig() override;
int usage();
void initRPC(const char *spec);
void finiRPC();
int Main() override;
};
GetConfig::~GetConfig()
{
LOG_ASSERT( ! _server);
LOG_ASSERT(_target == nullptr);
}
int
GetConfig::usage()
{
fprintf(stderr, "usage: %s -n name -i configId\n", _argv[0]);
fprintf(stderr, "-n name (config name, including namespace, on the form <namespace>.<name>)\n");
fprintf(stderr, "-i configId (config id, optional)\n");
fprintf(stderr, "-j (output config as json, optional)\n");
fprintf(stderr, "-l (output config in legacy cfg format, optional)\n");
fprintf(stderr, "-g generation (config generation, optional)\n");
fprintf(stderr, "-a schema (config def schema file, optional)\n");
fprintf(stderr, "-v defVersion (config definition version, optional, deprecated)\n");
fprintf(stderr, "-m defMd5 (definition md5sum, optional)\n");
fprintf(stderr, "-t serverTimeout (server timeout in seconds, default 3)\n");
fprintf(stderr, "-w timeout (timeout in seconds, default 10)\n");
fprintf(stderr, "-s server (server hostname, default localhost)\n");
fprintf(stderr, "-p port (proxy/server port number, default 19090)\n");
fprintf(stderr, "-r traceLevel (tracelevel to use in request, default 0\n");
fprintf(stderr, "-V vespaVersion (vespa version to use in request, optional\n");
fprintf(stderr, "-d (debug mode)\n");
fprintf(stderr, "-h (This help text)\n");
return 1;
}
void
GetConfig::initRPC(const char *spec)
{
_server = std::make_unique<fnet::frt::StandaloneFRT>();
_target = _server->supervisor().GetTarget(spec);
}
void
GetConfig::finiRPC()
{
if (_target != nullptr) {
_target->SubRef();
_target = nullptr;
}
_server.reset();
}
int
GetConfig::Main()
{
bool debugging = false;
int c = -1;
std::vector<vespalib::string> defSchema;
const char *schemaString = nullptr;
const char *defName = nullptr;
const char *defMD5 = "";
std::string defNamespace("config");
const char *serverHost = "localhost";
const char *configId = getenv("VESPA_CONFIG_ID");
bool printAsJson = false;
int traceLevel = config::protocol::readTraceLevel();
const char *vespaVersionString = nullptr;
int64_t generation = 0;
if (configId == nullptr) {
configId = "";
}
const char *configXxhash64 = "";
int serverTimeout = 3;
int clientTimeout = 10;
int serverPort = 19090;
const char *optArg = nullptr;
int optInd = 0;
while ((c = GetOpt("a:n:v:g:i:jlm:c:t:V:w:r:s:p:dh", optArg, optInd)) != -1) {
int retval = 1;
switch (c) {
case 'a':
schemaString = optArg;
break;
case 'n':
defName = optArg;
break;
case 'v':
break;
case 'g':
generation = atoll(optArg);
break;
case 'i':
configId = optArg;
break;
case 'j':
printAsJson = true;
break;
case 'l':
printAsJson = false;
break;
case 'm':
defMD5 = optArg;
break;
case 't':
serverTimeout = atoi(optArg);
break;
case 'w':
clientTimeout = atoi(optArg);
break;
case 'r':
traceLevel = atoi(optArg);
break;
case 'V':
vespaVersionString = optArg;
break;
case 's':
serverHost = optArg;
break;
case 'p':
serverPort = atoi(optArg);
break;
case 'd':
debugging = true;
break;
case 'h':
retval = 0;
[[fallthrough]];
case '?':
default:
usage();
return retval;
}
}
if (defName == nullptr || serverPort == 0) {
usage();
return 1;
}
if (strchr(defName, '.') != nullptr) {
const char *tmp = defName;
defName = strrchr(defName, '.');
defName++;
defNamespace = std::string(tmp, defName - tmp - 1);
}
std::string schema;
if (schemaString == nullptr) {
std::ostringstream tmp;
tmp << getenv("VESPA_HOME");
tmp << "/share/vespa/configdefinitions/";
tmp << defName;
tmp << ".def";
schema = tmp.str();
} else {
schema = schemaString;
}
if (debugging) {
printf("Using schema in %s\n", schema.c_str());
}
std::ifstream is;
is.open(schema);
std::string item;
while (std::getline(is, item)) {
if (item.find("namespace=") == std::string::npos) {
defSchema.push_back(item);
}
}
is.close();
std::ostringstream tmp;
tmp << "tcp/";
tmp << serverHost;
tmp << ":";
tmp << serverPort;
std::string sspec = tmp.str();
const char *spec = sspec.c_str();
if (debugging) {
printf("connecting to '%s'\n", spec);
}
initRPC(spec);
auto vespaVersion = VespaVersion::getCurrentVersion();
if (vespaVersionString != nullptr) {
vespaVersion = VespaVersion::fromString(vespaVersionString);
}
FRTConfigRequestFactory requestFactory(traceLevel, vespaVersion, config::protocol::readProtocolCompressionType());
FRTConnection connection(spec, _server->supervisor(), TimingValues());
ConfigKey key(configId, defName, defNamespace, defMD5, defSchema);
ConfigState state(configXxhash64, generation, false);
FRTConfigRequest::UP request = requestFactory.createConfigRequest(key, &connection, state, serverTimeout * 1000);
_target->InvokeSync(request->getRequest(), clientTimeout); // seconds
ConfigResponse::UP response = request->createResponse(request->getRequest());
response->validateResponse();
if (response->isError()) {
fprintf(stderr, "error %d: %s\n",
response->errorCode(), response->errorMessage().c_str());
} else {
response->fill();
ConfigKey rKey(response->getKey());
ConfigState rState(response->getConfigState());
ConfigValue rValue(response->getValue());
if (debugging) {
printf("defName %s\n", rKey.getDefName().c_str());
printf("defMD5 %s\n", rKey.getDefMd5().c_str());
printf("defNamespace %s\n", rKey.getDefNamespace().c_str());
printf("configID %s\n", rKey.getConfigId().c_str());
printf("configXxhash64 %s\n", rState.xxhash64.c_str());
printf("generation %" PRId64 "\n", rState.generation);
printf("trace %s\n", response->getTrace().toString().c_str());
} else if (traceLevel > 0) {
printf("trace %s\n", response->getTrace().toString().c_str());
}
// TODO: Make printAsJson default
if (printAsJson) {
printf("%s\n", rValue.asJson().c_str());
} else {
std::vector<vespalib::string> lines = rValue.getLegacyFormat();
for (uint32_t j = 0; j < lines.size(); j++) {
printf("%s\n", lines[j].c_str());
}
}
}
finiRPC();
return 0;
}
int main(int argc, char **argv)
{
GetConfig app;
return app.Entry(argc, argv);
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: b3ituple.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: hjs $ $Date: 2004-06-25 17:17:26 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _BGFX_TUPLE_B3ITUPLE_HXX
#define _BGFX_TUPLE_B3ITUPLE_HXX
#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif
#ifndef _BGFX_TUPLE_B3DTUPLE_HXX
#include <basegfx/tuple/b3dtuple.hxx>
#endif
namespace basegfx
{
/** Base class for all Points/Vectors with three sal_Int32 values
This class provides all methods common to Point
avd Vector classes which are derived from here.
@derive Use this class to implement Points or Vectors
which are based on three sal_Int32 values
*/
class B3ITuple
{
protected:
sal_Int32 mnX;
sal_Int32 mnY;
sal_Int32 mnZ;
public:
/** Create a 3D Tuple
The tuple is initialized to (0, 0, 0)
*/
B3ITuple()
: mnX(0),
mnY(0),
mnZ(0)
{}
/** Create a 3D Tuple
@param nX
This parameter is used to initialize the X-coordinate
of the 3D Tuple.
@param nY
This parameter is used to initialize the Y-coordinate
of the 3D Tuple.
@param nZ
This parameter is used to initialize the Z-coordinate
of the 3D Tuple.
*/
B3ITuple(sal_Int32 nX, sal_Int32 nY, sal_Int32 nZ)
: mnX(nX),
mnY(nY),
mnZ(nZ)
{}
/** Create a copy of a 3D Tuple
@param rTup
The 3D Tuple which will be copied.
*/
B3ITuple(const B3ITuple& rTup)
: mnX( rTup.mnX ),
mnY( rTup.mnY ),
mnZ( rTup.mnZ )
{}
~B3ITuple()
{}
/// get X-Coordinate of 3D Tuple
sal_Int32 getX() const
{
return mnX;
}
/// get Y-Coordinate of 3D Tuple
sal_Int32 getY() const
{
return mnY;
}
/// get Z-Coordinate of 3D Tuple
sal_Int32 getZ() const
{
return mnZ;
}
/// set X-Coordinate of 3D Tuple
void setX(sal_Int32 nX)
{
mnX = nX;
}
/// set Y-Coordinate of 3D Tuple
void setY(sal_Int32 nY)
{
mnY = nY;
}
/// set Z-Coordinate of 3D Tuple
void setZ(sal_Int32 nZ)
{
mnZ = nZ;
}
/// Array-access to 3D Tuple
const sal_Int32& operator[] (int nPos) const
{
// Here, normally two if(...)'s should be used. In the assumption that
// both sal_Int32 members can be accessed as an array a shortcut is used here.
// if(0 == nPos) return mnX; if(1 == nPos) return mnY; return mnZ;
return *((&mnX) + nPos);
}
/// Array-access to 3D Tuple
sal_Int32& operator[] (int nPos)
{
// Here, normally two if(...)'s should be used. In the assumption that
// both sal_Int32 members can be accessed as an array a shortcut is used here.
// if(0 == nPos) return mnX; if(1 == nPos) return mnY; return mnZ;
return *((&mnX) + nPos);
}
// operators
//////////////////////////////////////////////////////////////////////
B3ITuple& operator+=( const B3ITuple& rTup )
{
mnX += rTup.mnX;
mnY += rTup.mnY;
mnZ += rTup.mnZ;
return *this;
}
B3ITuple& operator-=( const B3ITuple& rTup )
{
mnX -= rTup.mnX;
mnY -= rTup.mnY;
mnZ -= rTup.mnZ;
return *this;
}
B3ITuple& operator/=( const B3ITuple& rTup )
{
mnX /= rTup.mnX;
mnY /= rTup.mnY;
mnZ /= rTup.mnZ;
return *this;
}
B3ITuple& operator*=( const B3ITuple& rTup )
{
mnX *= rTup.mnX;
mnY *= rTup.mnY;
mnZ *= rTup.mnZ;
return *this;
}
B3ITuple& operator*=(sal_Int32 t)
{
mnX *= t;
mnY *= t;
mnZ *= t;
return *this;
}
B3ITuple& operator/=(sal_Int32 t)
{
mnX /= t;
mnY /= t;
mnZ /= t;
return *this;
}
B3ITuple operator-(void) const
{
return B3ITuple(-mnX, -mnY, -mnZ);
}
bool equalZero() const
{
return (this == &getEmptyTuple() ||
(mnX == 0 && mnY == 0 && mnZ == 0));
}
bool operator==( const B3ITuple& rTup ) const
{
return rTup.mnX == mnX && rTup.mnY == mnY && rTup.mnZ == mnZ;
}
bool operator!=( const B3ITuple& rTup ) const
{
return !(*this == rTup);
}
B3ITuple& operator=( const B3ITuple& rTup )
{
mnX = rTup.mnX;
mnY = rTup.mnY;
mnZ = rTup.mnZ;
return *this;
}
static const B3ITuple& getEmptyTuple();
};
// external operators
//////////////////////////////////////////////////////////////////////////
inline B3ITuple minimum(const B3ITuple& rTupA, const B3ITuple& rTupB)
{
B3ITuple aMin(
(rTupB.getX() < rTupA.getX()) ? rTupB.getX() : rTupA.getX(),
(rTupB.getY() < rTupA.getY()) ? rTupB.getY() : rTupA.getY(),
(rTupB.getZ() < rTupA.getZ()) ? rTupB.getZ() : rTupA.getZ());
return aMin;
}
inline B3ITuple maximum(const B3ITuple& rTupA, const B3ITuple& rTupB)
{
B3ITuple aMax(
(rTupB.getX() > rTupA.getX()) ? rTupB.getX() : rTupA.getX(),
(rTupB.getY() > rTupA.getY()) ? rTupB.getY() : rTupA.getY(),
(rTupB.getZ() > rTupA.getZ()) ? rTupB.getZ() : rTupA.getZ());
return aMax;
}
inline B3ITuple absolute(const B3ITuple& rTup)
{
B3ITuple aAbs(
(0 > rTup.getX()) ? -rTup.getX() : rTup.getX(),
(0 > rTup.getY()) ? -rTup.getY() : rTup.getY(),
(0 > rTup.getZ()) ? -rTup.getZ() : rTup.getZ());
return aAbs;
}
inline B3DTuple interpolate(const B3ITuple& rOld1, const B3ITuple& rOld2, double t)
{
B3DTuple aInt(
((rOld2.getX() - rOld1.getX()) * t) + rOld1.getX(),
((rOld2.getY() - rOld1.getY()) * t) + rOld1.getY(),
((rOld2.getZ() - rOld1.getZ()) * t) + rOld1.getZ());
return aInt;
}
inline B3DTuple average(const B3ITuple& rOld1, const B3ITuple& rOld2)
{
B3DTuple aAvg(
(rOld1.getX() + rOld2.getX()) * 0.5,
(rOld1.getY() + rOld2.getY()) * 0.5,
(rOld1.getZ() + rOld2.getZ()) * 0.5);
return aAvg;
}
inline B3DTuple average(const B3ITuple& rOld1, const B3ITuple& rOld2, const B3ITuple& rOld3)
{
B3DTuple aAvg(
(rOld1.getX() + rOld2.getX() + rOld3.getX()) * (1.0 / 3.0),
(rOld1.getY() + rOld2.getY() + rOld3.getY()) * (1.0 / 3.0),
(rOld1.getZ() + rOld2.getZ() + rOld3.getZ()) * (1.0 / 3.0));
return aAvg;
}
inline B3ITuple operator+(const B3ITuple& rTupA, const B3ITuple& rTupB)
{
B3ITuple aSum(rTupA);
aSum += rTupB;
return aSum;
}
inline B3ITuple operator-(const B3ITuple& rTupA, const B3ITuple& rTupB)
{
B3ITuple aSub(rTupA);
aSub -= rTupB;
return aSub;
}
inline B3ITuple operator/(const B3ITuple& rTupA, const B3ITuple& rTupB)
{
B3ITuple aDiv(rTupA);
aDiv /= rTupB;
return aDiv;
}
inline B3ITuple operator*(const B3ITuple& rTupA, const B3ITuple& rTupB)
{
B3ITuple aMul(rTupA);
aMul *= rTupB;
return aMul;
}
inline B3ITuple operator*(const B3ITuple& rTup, sal_Int32 t)
{
B3ITuple aNew(rTup);
aNew *= t;
return aNew;
}
inline B3ITuple operator*(sal_Int32 t, const B3ITuple& rTup)
{
B3ITuple aNew(rTup);
aNew *= t;
return aNew;
}
inline B3ITuple operator/(const B3ITuple& rTup, sal_Int32 t)
{
B3ITuple aNew(rTup);
aNew /= t;
return aNew;
}
inline B3ITuple operator/(sal_Int32 t, const B3ITuple& rTup)
{
B3ITuple aNew(t, t, t);
B3ITuple aTmp(rTup);
aNew /= aTmp;
return aNew;
}
} // end of namespace basegfx
#endif /* _BGFX_TUPLE_B3ITUPLE_HXX */
<commit_msg>INTEGRATION: CWS ooo19126 (1.3.44); FILE MERGED 2005/09/05 17:38:31 rt 1.3.44.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: b3ituple.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2005-09-07 20:37:23 $
*
* 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 _BGFX_TUPLE_B3ITUPLE_HXX
#define _BGFX_TUPLE_B3ITUPLE_HXX
#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif
#ifndef _BGFX_TUPLE_B3DTUPLE_HXX
#include <basegfx/tuple/b3dtuple.hxx>
#endif
namespace basegfx
{
/** Base class for all Points/Vectors with three sal_Int32 values
This class provides all methods common to Point
avd Vector classes which are derived from here.
@derive Use this class to implement Points or Vectors
which are based on three sal_Int32 values
*/
class B3ITuple
{
protected:
sal_Int32 mnX;
sal_Int32 mnY;
sal_Int32 mnZ;
public:
/** Create a 3D Tuple
The tuple is initialized to (0, 0, 0)
*/
B3ITuple()
: mnX(0),
mnY(0),
mnZ(0)
{}
/** Create a 3D Tuple
@param nX
This parameter is used to initialize the X-coordinate
of the 3D Tuple.
@param nY
This parameter is used to initialize the Y-coordinate
of the 3D Tuple.
@param nZ
This parameter is used to initialize the Z-coordinate
of the 3D Tuple.
*/
B3ITuple(sal_Int32 nX, sal_Int32 nY, sal_Int32 nZ)
: mnX(nX),
mnY(nY),
mnZ(nZ)
{}
/** Create a copy of a 3D Tuple
@param rTup
The 3D Tuple which will be copied.
*/
B3ITuple(const B3ITuple& rTup)
: mnX( rTup.mnX ),
mnY( rTup.mnY ),
mnZ( rTup.mnZ )
{}
~B3ITuple()
{}
/// get X-Coordinate of 3D Tuple
sal_Int32 getX() const
{
return mnX;
}
/// get Y-Coordinate of 3D Tuple
sal_Int32 getY() const
{
return mnY;
}
/// get Z-Coordinate of 3D Tuple
sal_Int32 getZ() const
{
return mnZ;
}
/// set X-Coordinate of 3D Tuple
void setX(sal_Int32 nX)
{
mnX = nX;
}
/// set Y-Coordinate of 3D Tuple
void setY(sal_Int32 nY)
{
mnY = nY;
}
/// set Z-Coordinate of 3D Tuple
void setZ(sal_Int32 nZ)
{
mnZ = nZ;
}
/// Array-access to 3D Tuple
const sal_Int32& operator[] (int nPos) const
{
// Here, normally two if(...)'s should be used. In the assumption that
// both sal_Int32 members can be accessed as an array a shortcut is used here.
// if(0 == nPos) return mnX; if(1 == nPos) return mnY; return mnZ;
return *((&mnX) + nPos);
}
/// Array-access to 3D Tuple
sal_Int32& operator[] (int nPos)
{
// Here, normally two if(...)'s should be used. In the assumption that
// both sal_Int32 members can be accessed as an array a shortcut is used here.
// if(0 == nPos) return mnX; if(1 == nPos) return mnY; return mnZ;
return *((&mnX) + nPos);
}
// operators
//////////////////////////////////////////////////////////////////////
B3ITuple& operator+=( const B3ITuple& rTup )
{
mnX += rTup.mnX;
mnY += rTup.mnY;
mnZ += rTup.mnZ;
return *this;
}
B3ITuple& operator-=( const B3ITuple& rTup )
{
mnX -= rTup.mnX;
mnY -= rTup.mnY;
mnZ -= rTup.mnZ;
return *this;
}
B3ITuple& operator/=( const B3ITuple& rTup )
{
mnX /= rTup.mnX;
mnY /= rTup.mnY;
mnZ /= rTup.mnZ;
return *this;
}
B3ITuple& operator*=( const B3ITuple& rTup )
{
mnX *= rTup.mnX;
mnY *= rTup.mnY;
mnZ *= rTup.mnZ;
return *this;
}
B3ITuple& operator*=(sal_Int32 t)
{
mnX *= t;
mnY *= t;
mnZ *= t;
return *this;
}
B3ITuple& operator/=(sal_Int32 t)
{
mnX /= t;
mnY /= t;
mnZ /= t;
return *this;
}
B3ITuple operator-(void) const
{
return B3ITuple(-mnX, -mnY, -mnZ);
}
bool equalZero() const
{
return (this == &getEmptyTuple() ||
(mnX == 0 && mnY == 0 && mnZ == 0));
}
bool operator==( const B3ITuple& rTup ) const
{
return rTup.mnX == mnX && rTup.mnY == mnY && rTup.mnZ == mnZ;
}
bool operator!=( const B3ITuple& rTup ) const
{
return !(*this == rTup);
}
B3ITuple& operator=( const B3ITuple& rTup )
{
mnX = rTup.mnX;
mnY = rTup.mnY;
mnZ = rTup.mnZ;
return *this;
}
static const B3ITuple& getEmptyTuple();
};
// external operators
//////////////////////////////////////////////////////////////////////////
inline B3ITuple minimum(const B3ITuple& rTupA, const B3ITuple& rTupB)
{
B3ITuple aMin(
(rTupB.getX() < rTupA.getX()) ? rTupB.getX() : rTupA.getX(),
(rTupB.getY() < rTupA.getY()) ? rTupB.getY() : rTupA.getY(),
(rTupB.getZ() < rTupA.getZ()) ? rTupB.getZ() : rTupA.getZ());
return aMin;
}
inline B3ITuple maximum(const B3ITuple& rTupA, const B3ITuple& rTupB)
{
B3ITuple aMax(
(rTupB.getX() > rTupA.getX()) ? rTupB.getX() : rTupA.getX(),
(rTupB.getY() > rTupA.getY()) ? rTupB.getY() : rTupA.getY(),
(rTupB.getZ() > rTupA.getZ()) ? rTupB.getZ() : rTupA.getZ());
return aMax;
}
inline B3ITuple absolute(const B3ITuple& rTup)
{
B3ITuple aAbs(
(0 > rTup.getX()) ? -rTup.getX() : rTup.getX(),
(0 > rTup.getY()) ? -rTup.getY() : rTup.getY(),
(0 > rTup.getZ()) ? -rTup.getZ() : rTup.getZ());
return aAbs;
}
inline B3DTuple interpolate(const B3ITuple& rOld1, const B3ITuple& rOld2, double t)
{
B3DTuple aInt(
((rOld2.getX() - rOld1.getX()) * t) + rOld1.getX(),
((rOld2.getY() - rOld1.getY()) * t) + rOld1.getY(),
((rOld2.getZ() - rOld1.getZ()) * t) + rOld1.getZ());
return aInt;
}
inline B3DTuple average(const B3ITuple& rOld1, const B3ITuple& rOld2)
{
B3DTuple aAvg(
(rOld1.getX() + rOld2.getX()) * 0.5,
(rOld1.getY() + rOld2.getY()) * 0.5,
(rOld1.getZ() + rOld2.getZ()) * 0.5);
return aAvg;
}
inline B3DTuple average(const B3ITuple& rOld1, const B3ITuple& rOld2, const B3ITuple& rOld3)
{
B3DTuple aAvg(
(rOld1.getX() + rOld2.getX() + rOld3.getX()) * (1.0 / 3.0),
(rOld1.getY() + rOld2.getY() + rOld3.getY()) * (1.0 / 3.0),
(rOld1.getZ() + rOld2.getZ() + rOld3.getZ()) * (1.0 / 3.0));
return aAvg;
}
inline B3ITuple operator+(const B3ITuple& rTupA, const B3ITuple& rTupB)
{
B3ITuple aSum(rTupA);
aSum += rTupB;
return aSum;
}
inline B3ITuple operator-(const B3ITuple& rTupA, const B3ITuple& rTupB)
{
B3ITuple aSub(rTupA);
aSub -= rTupB;
return aSub;
}
inline B3ITuple operator/(const B3ITuple& rTupA, const B3ITuple& rTupB)
{
B3ITuple aDiv(rTupA);
aDiv /= rTupB;
return aDiv;
}
inline B3ITuple operator*(const B3ITuple& rTupA, const B3ITuple& rTupB)
{
B3ITuple aMul(rTupA);
aMul *= rTupB;
return aMul;
}
inline B3ITuple operator*(const B3ITuple& rTup, sal_Int32 t)
{
B3ITuple aNew(rTup);
aNew *= t;
return aNew;
}
inline B3ITuple operator*(sal_Int32 t, const B3ITuple& rTup)
{
B3ITuple aNew(rTup);
aNew *= t;
return aNew;
}
inline B3ITuple operator/(const B3ITuple& rTup, sal_Int32 t)
{
B3ITuple aNew(rTup);
aNew /= t;
return aNew;
}
inline B3ITuple operator/(sal_Int32 t, const B3ITuple& rTup)
{
B3ITuple aNew(t, t, t);
B3ITuple aTmp(rTup);
aNew /= aTmp;
return aNew;
}
} // end of namespace basegfx
#endif /* _BGFX_TUPLE_B3ITUPLE_HXX */
<|endoftext|>
|
<commit_before>/*
This file is part of Magnum.
Original authors — credit is appreciated but not required:
2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019,
2020, 2021, 2022 — Vladimír Vondruš <mosra@centrum.cz>
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or distribute
this software, either in source code form or as a compiled binary, for any
purpose, commercial or non-commercial, and by any means.
In jurisdictions that recognize copyright laws, the author or authors of
this software dedicate any and all copyright interest in the software to
the public domain. We make this dedication for the benefit of the public
at large and to the detriment of our heirs and successors. We intend this
dedication to be an overt act of relinquishment in perpetuity of all
present and future rights to this software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <Corrade/PluginManager/Manager.h>
#include <Corrade/Utility/FormatStl.h>
#include <Corrade/Utility/Resource.h>
#include <Magnum/GL/DefaultFramebuffer.h>
#include <Magnum/GL/Mesh.h>
#include <Magnum/GL/Renderer.h>
#include <Magnum/Math/Color.h>
#include <Magnum/Math/Complex.h>
#include <Magnum/Math/Matrix3.h>
#include <Magnum/Platform/Sdl2Application.h>
#include <Magnum/Shaders/DistanceFieldVectorGL.h>
#include <Magnum/Text/AbstractFont.h>
#include <Magnum/Text/DistanceFieldGlyphCache.h>
#include <Magnum/Text/Renderer.h>
namespace Magnum { namespace Examples {
using namespace Math::Literals;
class TextExample: public Platform::Application {
public:
explicit TextExample(const Arguments& arguments);
private:
void viewportEvent(ViewportEvent& event) override;
void drawEvent() override;
void mouseScrollEvent(MouseScrollEvent& event) override;
void updateText();
PluginManager::Manager<Text::AbstractFont> _manager;
Containers::Pointer<Text::AbstractFont> _font;
Text::DistanceFieldGlyphCache _cache;
GL::Mesh _rotatingText{NoCreate};
GL::Buffer _vertices, _indices;
Containers::Pointer<Text::Renderer2D> _dynamicText;
Shaders::DistanceFieldVectorGL2D _shader;
Matrix3 _transformationRotatingText,
_projectionRotatingText,
_transformationProjectionDynamicText;
};
TextExample::TextExample(const Arguments& arguments):
Platform::Application{arguments, Configuration{}
.setTitle("Magnum Text Example")
.setWindowFlags(Configuration::WindowFlag::Resizable)},
_cache{Vector2i{2048}, Vector2i{512}, 22}
{
/* Load a TrueTypeFont plugin and open the font */
Utility::Resource rs("fonts");
_font = _manager.loadAndInstantiate("TrueTypeFont");
if(!_font || !_font->openData(rs.getRaw("SourceSansPro-Regular.ttf"), 180.0f))
Fatal{} << "Cannot open font file";
/* Glyphs we need to render everything */
_font->fillGlyphCache(_cache,
"abcdefghijklmnopqrstuvwxyz"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"0123456789:-+,.!°ěäЗдравстуймиΓειασουκόμ ");
/* Text that rotates using mouse wheel. Size relative to the window size
(1/10 of it) -- if you resize the window, it gets bigger */
std::tie(_rotatingText, std::ignore) = Text::Renderer2D::render(*_font, _cache, 0.2f,
"Hello, world!\n"
"Ahoj, světe!\n"
"Здравствуй, мир!\n"
"Γεια σου κόσμε!\n"
"Hej Världen!",
_vertices, _indices, GL::BufferUsage::StaticDraw, Text::Alignment::MiddleCenter);
_transformationRotatingText = Matrix3::rotation(-10.0_degf);
_projectionRotatingText = Matrix3::projection(
Vector2::xScale(Vector2{windowSize()}.aspectRatio()));
/* Dynamically updated text that shows rotation/zoom of the other. Size in
points that stays the same if you resize the window. Aligned so top
right of the bounding box is at mesh origin, and then transformed so the
origin is at the top right corner of the window. */
_dynamicText.reset(new Text::Renderer2D(*_font, _cache, 32.0f, Text::Alignment::TopRight));
_dynamicText->reserve(40, GL::BufferUsage::DynamicDraw, GL::BufferUsage::StaticDraw);
_transformationProjectionDynamicText =
Matrix3::projection(Vector2{windowSize()})*
Matrix3::translation(Vector2{windowSize()}*0.5f);
/* Set up premultiplied alpha blending to avoid overlapping text characters
to cut into each other */
GL::Renderer::enable(GL::Renderer::Feature::Blending);
GL::Renderer::setBlendFunction(GL::Renderer::BlendFunction::One, GL::Renderer::BlendFunction::OneMinusSourceAlpha);
GL::Renderer::setBlendEquation(GL::Renderer::BlendEquation::Add, GL::Renderer::BlendEquation::Add);
updateText();
}
void TextExample::viewportEvent(ViewportEvent& event) {
GL::defaultFramebuffer.setViewport({{}, event.framebufferSize()});
_projectionRotatingText = Matrix3::projection(
Vector2::xScale(Vector2{windowSize()}.aspectRatio()));
_transformationProjectionDynamicText =
Matrix3::projection(Vector2{windowSize()})*
Matrix3::translation(Vector2{windowSize()}*0.5f);
}
void TextExample::drawEvent() {
GL::defaultFramebuffer.clear(GL::FramebufferClear::Color);
_shader.bindVectorTexture(_cache.texture());
_shader
.setTransformationProjectionMatrix(
_projectionRotatingText*_transformationRotatingText)
.setColor(0x2f83cc_rgbf)
.setOutlineColor(0xdcdcdc_rgbf)
.setOutlineRange(0.45f, 0.35f)
.setSmoothness(0.025f/ _transformationRotatingText.uniformScaling())
.draw(_rotatingText);
_shader
.setTransformationProjectionMatrix(_transformationProjectionDynamicText)
.setColor(0xffffff_rgbf)
.setOutlineRange(0.5f, 1.0f)
.setSmoothness(0.075f)
.draw(_dynamicText->mesh());
swapBuffers();
}
void TextExample::mouseScrollEvent(MouseScrollEvent& event) {
if(!event.offset().y()) return;
if(event.offset().y() > 0)
_transformationRotatingText = Matrix3::rotation(1.0_degf)*Matrix3::scaling(Vector2{1.1f})* _transformationRotatingText;
else
_transformationRotatingText = Matrix3::rotation(-1.0_degf)*Matrix3::scaling(Vector2{1.0f/1.1f})* _transformationRotatingText;
updateText();
event.setAccepted();
redraw();
}
void TextExample::updateText() {
_dynamicText->render(Utility::formatString("Rotation: {:.2}°\nScale: {:.2}",
Float(Deg(Complex::fromMatrix(_transformationRotatingText.rotation()).angle())),
_transformationRotatingText.uniformScaling()));
}
}}
MAGNUM_APPLICATION_MAIN(Magnum::Examples::TextExample)
<commit_msg>text: minor.<commit_after>/*
This file is part of Magnum.
Original authors — credit is appreciated but not required:
2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019,
2020, 2021, 2022 — Vladimír Vondruš <mosra@centrum.cz>
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or distribute
this software, either in source code form or as a compiled binary, for any
purpose, commercial or non-commercial, and by any means.
In jurisdictions that recognize copyright laws, the author or authors of
this software dedicate any and all copyright interest in the software to
the public domain. We make this dedication for the benefit of the public
at large and to the detriment of our heirs and successors. We intend this
dedication to be an overt act of relinquishment in perpetuity of all
present and future rights to this software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <Corrade/PluginManager/Manager.h>
#include <Corrade/Utility/FormatStl.h>
#include <Corrade/Utility/Resource.h>
#include <Magnum/GL/DefaultFramebuffer.h>
#include <Magnum/GL/Mesh.h>
#include <Magnum/GL/Renderer.h>
#include <Magnum/Math/Color.h>
#include <Magnum/Math/Complex.h>
#include <Magnum/Math/Matrix3.h>
#include <Magnum/Platform/Sdl2Application.h>
#include <Magnum/Shaders/DistanceFieldVectorGL.h>
#include <Magnum/Text/AbstractFont.h>
#include <Magnum/Text/DistanceFieldGlyphCache.h>
#include <Magnum/Text/Renderer.h>
namespace Magnum { namespace Examples {
using namespace Math::Literals;
class TextExample: public Platform::Application {
public:
explicit TextExample(const Arguments& arguments);
private:
void viewportEvent(ViewportEvent& event) override;
void drawEvent() override;
void mouseScrollEvent(MouseScrollEvent& event) override;
void updateText();
PluginManager::Manager<Text::AbstractFont> _manager;
Containers::Pointer<Text::AbstractFont> _font;
Text::DistanceFieldGlyphCache _cache;
GL::Mesh _rotatingText{NoCreate};
GL::Buffer _vertices, _indices;
Containers::Pointer<Text::Renderer2D> _dynamicText;
Shaders::DistanceFieldVectorGL2D _shader;
Matrix3 _transformationRotatingText,
_projectionRotatingText,
_transformationProjectionDynamicText;
};
TextExample::TextExample(const Arguments& arguments):
Platform::Application{arguments, Configuration{}
.setTitle("Magnum Text Example")
.setWindowFlags(Configuration::WindowFlag::Resizable)},
_cache{Vector2i{2048}, Vector2i{512}, 22}
{
/* Load a TrueTypeFont plugin and open the font */
Utility::Resource rs("fonts");
_font = _manager.loadAndInstantiate("TrueTypeFont");
if(!_font || !_font->openData(rs.getRaw("SourceSansPro-Regular.ttf"), 180.0f))
Fatal{} << "Cannot open font file";
/* Glyphs we need to render everything */
_font->fillGlyphCache(_cache,
"abcdefghijklmnopqrstuvwxyz"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"0123456789:-+,.!°ěäЗдравстуймиΓειασουκόμ ");
/* Text that rotates using mouse wheel. Size relative to the window size
(1/10 of it) -- if you resize the window, it gets bigger */
std::tie(_rotatingText, std::ignore) = Text::Renderer2D::render(*_font, _cache, 0.2f,
"Hello, world!\n"
"Ahoj, světe!\n"
"Здравствуй, мир!\n"
"Γεια σου κόσμε!\n"
"Hej Världen!",
_vertices, _indices, GL::BufferUsage::StaticDraw, Text::Alignment::MiddleCenter);
_transformationRotatingText = Matrix3::rotation(-10.0_degf);
_projectionRotatingText = Matrix3::projection(
Vector2::xScale(Vector2{windowSize()}.aspectRatio()));
/* Dynamically updated text that shows rotation/zoom of the other. Size in
points that stays the same if you resize the window. Aligned so top
right of the bounding box is at mesh origin, and then transformed so the
origin is at the top right corner of the window. */
_dynamicText.reset(new Text::Renderer2D(*_font, _cache, 32.0f, Text::Alignment::TopRight));
_dynamicText->reserve(40, GL::BufferUsage::DynamicDraw, GL::BufferUsage::StaticDraw);
_transformationProjectionDynamicText =
Matrix3::projection(Vector2{windowSize()})*
Matrix3::translation(Vector2{windowSize()}*0.5f);
/* Set up premultiplied alpha blending to avoid overlapping text characters
to cut into each other */
GL::Renderer::enable(GL::Renderer::Feature::Blending);
GL::Renderer::setBlendFunction(GL::Renderer::BlendFunction::One, GL::Renderer::BlendFunction::OneMinusSourceAlpha);
GL::Renderer::setBlendEquation(GL::Renderer::BlendEquation::Add, GL::Renderer::BlendEquation::Add);
updateText();
}
void TextExample::viewportEvent(ViewportEvent& event) {
GL::defaultFramebuffer.setViewport({{}, event.framebufferSize()});
_projectionRotatingText = Matrix3::projection(
Vector2::xScale(Vector2{windowSize()}.aspectRatio()));
_transformationProjectionDynamicText =
Matrix3::projection(Vector2{windowSize()})*
Matrix3::translation(Vector2{windowSize()}*0.5f);
}
void TextExample::drawEvent() {
GL::defaultFramebuffer.clear(GL::FramebufferClear::Color);
_shader.bindVectorTexture(_cache.texture());
_shader
.setTransformationProjectionMatrix(
_projectionRotatingText*_transformationRotatingText)
.setColor(0x2f83cc_rgbf)
.setOutlineColor(0xdcdcdc_rgbf)
.setOutlineRange(0.45f, 0.35f)
.setSmoothness(0.025f/_transformationRotatingText.uniformScaling())
.draw(_rotatingText);
_shader
.setTransformationProjectionMatrix(_transformationProjectionDynamicText)
.setColor(0xffffff_rgbf)
.setOutlineRange(0.5f, 1.0f)
.setSmoothness(0.075f)
.draw(_dynamicText->mesh());
swapBuffers();
}
void TextExample::mouseScrollEvent(MouseScrollEvent& event) {
if(!event.offset().y()) return;
if(event.offset().y() > 0)
_transformationRotatingText = Matrix3::rotation(1.0_degf)*Matrix3::scaling(Vector2{1.1f})* _transformationRotatingText;
else
_transformationRotatingText = Matrix3::rotation(-1.0_degf)*Matrix3::scaling(Vector2{1.0f/1.1f})* _transformationRotatingText;
updateText();
event.setAccepted();
redraw();
}
void TextExample::updateText() {
_dynamicText->render(Utility::formatString("Rotation: {:.2}°\nScale: {:.2}",
Float(Deg(Complex::fromMatrix(_transformationRotatingText.rotation()).angle())),
_transformationRotatingText.uniformScaling()));
}
}}
MAGNUM_APPLICATION_MAIN(Magnum::Examples::TextExample)
<|endoftext|>
|
<commit_before>
#ifdef CPU_TIME
#include "timing_functions.h"
#include "io.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
#ifdef MPI_CHOLLA
#include "mpi_routines.h"
#endif
Time::Time( void ){}
void Time::Initialize(){
n_steps = 0;
time_hydro_all = 0;
time_bound_all = 0;
#ifdef GRAVITY
time_potential_all = 0;
#ifdef GRAVITY_COUPLE_CPU
time_dt_all = 0;
time_bound_pot_all = 0;
#endif
#endif
#ifdef PARTICLES
time_part_dens_all = 0;
time_part_dens_transf_all = 0;
time_part_tranf_all = 0;
time_advance_particles_1_all = 0;
time_advance_particles_2_all = 0;
#endif
#ifdef COOLING_GRACKLE
time_cooling_all = 0;
#endif
chprintf( "\nTiming Functions is ON \n");
}
void Time::Start_Timer(){
time_start = get_time();
}
void Time::End_and_Record_Time( int time_var ){
time_end = get_time();
time = (time_end - time_start)*1000;
Real t_min, t_max, t_avg;
#ifdef MPI_CHOLLA
t_min = ReduceRealMin(time);
t_max = ReduceRealMax(time);
t_avg = ReduceRealAvg(time);
#else
t_min = time;
t_max = time;
t_avg = time;
#endif
if( time_var == 1 ){
time_hydro_min = t_min;
time_hydro_max = t_max;
time_hydro_mean = t_avg;
if (n_steps > 0) time_hydro_all += t_max;
}
if( time_var == 2 ){
time_bound_min = t_min;
time_bound_max = t_max;
time_bound_mean = t_avg;
if (n_steps > 0) time_bound_all += t_max;
}
#ifdef GRAVITY
if( time_var == 3 ){
time_potential_min = t_min;
time_potential_max = t_max;
time_potential_mean = t_avg;
if (n_steps > 0) time_potential_all += t_max;
}
#ifdef GRAVITY_COUPLE_CPU
if( time_var == 0 ){
time_dt_min = t_min;
time_dt_max = t_max;
time_dt_mean = t_avg;
if (n_steps > 0) time_dt_all += t_max;
}
if( time_var == 9 ){
time_bound_pot_min = t_min;
time_bound_pot_max = t_max;
time_bound_pot_mean = t_avg;
if (n_steps > 0) time_bound_pot_all += t_max;
}
#endif
#endif
#ifdef PARTICLES
if( time_var == 4 ){
time_part_dens_min = t_min;
time_part_dens_max = t_max;
time_part_dens_mean = t_avg;
if (n_steps > 0) time_part_dens_all += t_max;
}
if( time_var == 5 ){
time_part_dens_transf_min = t_min;
time_part_dens_transf_max = t_max;
time_part_dens_transf_mean = t_avg;
if (n_steps > 0) time_part_dens_transf_all += t_max;
}
if( time_var == 6 ){
time_advance_particles_1_min = t_min;
time_advance_particles_1_max = t_max;
time_advance_particles_1_mean = t_avg;
if (n_steps > 0) time_advance_particles_1_all += t_max;
}
if( time_var == 7 ){
time_advance_particles_2_min = t_min;
time_advance_particles_2_max = t_max;
time_advance_particles_2_mean = t_avg;
if (n_steps > 0) time_advance_particles_2_all += t_max;
}
if( time_var == 8 ){
time_part_tranf_min = t_min;
time_part_tranf_max = t_max;
time_part_tranf_mean = t_avg;
if (n_steps > 0) time_part_tranf_all += t_max;
}
#endif
#ifdef COOLING_GRACKLE
if( time_var == 10 ){
time_cooling_min = t_min;
time_cooling_max = t_max;
time_cooling_mean = t_avg;
if (n_steps > 0) time_cooling_all += t_max;
}
#endif
}
void Time::Print_Times(){
#ifdef GRAVITY_COUPLE_CPU
chprintf(" Time Calc dt min: %9.4f max: %9.4f avg: %9.4f ms\n", time_dt_min, time_dt_max, time_dt_mean);
#endif
chprintf(" Time Hydro min: %9.4f max: %9.4f avg: %9.4f ms\n", time_hydro_min, time_hydro_max, time_hydro_mean);
chprintf(" Time Boundaries min: %9.4f max: %9.4f avg: %9.4f ms\n", time_bound_min, time_bound_max, time_bound_mean);
#ifdef GRAVITY
chprintf(" Time Grav Potential min: %9.4f max: %9.4f avg: %9.4f ms\n", time_potential_min, time_potential_max, time_potential_mean);
#ifdef GRAVITY_COUPLE_CPU
chprintf(" Time Pot Boundaries min: %9.4f max: %9.4f avg: %9.4f ms\n", time_bound_pot_min, time_bound_pot_max, time_bound_pot_mean);
#endif
#endif
#ifdef PARTICLES
chprintf(" Time Part Density min: %9.4f max: %9.4f avg: %9.4f ms\n", time_part_dens_min, time_part_dens_max, time_part_dens_mean);
chprintf(" Time Part Boundaries min: %9.4f max: %9.4f avg: %9.4f ms\n", time_part_tranf_min, time_part_tranf_max, time_part_tranf_mean);
chprintf(" Time Part Dens Transf min: %9.4f max: %9.4f avg: %9.4f ms\n", time_part_dens_transf_min, time_part_dens_transf_max, time_part_dens_transf_mean);
chprintf(" Time Advance Part 1 min: %9.4f max: %9.4f avg: %9.4f ms\n", time_advance_particles_1_min, time_advance_particles_1_max, time_advance_particles_1_mean);
chprintf(" Time Advance Part 2 min: %9.4f max: %9.4f avg: %9.4f ms\n", time_advance_particles_2_min, time_advance_particles_2_max, time_advance_particles_2_mean);
#endif
#ifdef COOLING_GRACKLE
chprintf(" Time Cooling min: %9.4f max: %9.4f avg: %9.4f ms\n", time_cooling_min, time_cooling_max, time_cooling_mean);
#endif
}
void Time::Get_Average_Times(){
n_steps -= 1; //Ignore the first timestep
time_hydro_all /= n_steps;
time_bound_all /= n_steps;
#ifdef GRAVITY_COUPLE_CPU
time_dt_all /= n_steps;
time_bound_pot_all /= n_steps;
#endif
#ifdef GRAVITY
time_potential_all /= n_steps;
#ifdef PARTICLES
time_part_dens_all /= n_steps;
time_part_tranf_all /= n_steps;
time_part_dens_transf_all /= n_steps;
time_advance_particles_1_all /= n_steps;
time_advance_particles_2_all /= n_steps;
#endif
#endif
#ifdef COOLING_GRACKLE
time_cooling_all /= n_steps;
#endif
}
void Time::Print_Average_Times( struct parameters P ){
Real time_total;
time_total = time_hydro_all + time_bound_all;
#ifdef GRAVITY_COUPLE_CPU
time_total += time_dt_all;
time_total += time_bound_pot_all;
#endif
#ifdef GRAVITY
time_total += time_potential_all;
#ifdef PARTICLES
time_total += time_part_dens_all;
time_total += time_part_tranf_all;
time_total += time_part_dens_transf_all;
time_total += time_advance_particles_1_all;
time_total += time_advance_particles_2_all;
#endif
#endif
#ifdef COOLING_GRACKLE
time_total += time_cooling_all;
#endif
chprintf("\nAverage Times n_steps:%d\n", n_steps);
#ifdef GRAVITY_COUPLE_CPU
chprintf(" Time Calc dt avg: %9.4f ms\n", time_dt_all);
#endif
chprintf(" Time Hydro avg: %9.4f ms\n", time_hydro_all);
chprintf(" Time Boundaries avg: %9.4f ms\n", time_bound_all);
#ifdef GRAVITY
chprintf(" Time Grav Potential avg: %9.4f ms\n", time_potential_all);
#ifdef GRAVITY_COUPLE_CPU
chprintf(" Time Pot Boundaries avg: %9.4f ms\n", time_bound_pot_all);
#endif
#ifdef PARTICLES
chprintf(" Time Part Density avg: %9.4f ms\n", time_part_dens_all);
chprintf(" Time Part Boundaries avg: %9.4f ms\n", time_part_tranf_all);
chprintf(" Time Part Dens Transf avg: %9.4f ms\n", time_part_dens_transf_all);
chprintf(" Time Advance Part 1 avg: %9.4f ms\n", time_advance_particles_1_all);
chprintf(" Time Advance Part 2 avg: %9.4f ms\n", time_advance_particles_2_all);
#endif
#endif
#ifdef COOLING_GRACKLE
chprintf(" Time Cooling avg: %9.4f ms\n", time_cooling_all);
#endif
chprintf(" Time Total avg: %9.4f ms\n\n", time_total);
string file_name ( "run_timing.log" );
string header;
chprintf( "Writing timming values to file: %s \n", file_name.c_str());
header = "# nx ny nz n_proc n_omp n_steps ";
#ifdef GRAVITY_COUPLE_CPU
header += "dt ";
#endif
header += "hydo ";
header += "bound ";
#ifdef GRAVITY
header += "grav_pot ";
#ifdef GRAVITY_COUPLE_CPU
header += "pot_bound ";
#endif
#endif
#ifdef PARTICLES
header += "part_dens ";
header += "part_bound ";
header += "part_dens_boud ";
header += "part_adv_1 ";
header += "part_adv_2 ";
#endif
#ifdef COOLING_GRACKLE
header += "cool ";
#endif
header += "total ";
header += " \n";
bool file_exists = false;
if (FILE *file = fopen(file_name.c_str(), "r")){
file_exists = true;
chprintf( " File exists, appending values: %s \n\n", file_name.c_str() );
fclose( file );
} else{
chprintf( " Creating File: %s \n\n", file_name.c_str() );
}
#ifdef MPI_CHOLLA
if ( procID != 0 ) return;
#endif
ofstream out_file;
// Output timing values
out_file.open(file_name.c_str(), ios::app);
if ( !file_exists ) out_file << header;
out_file << P.nx << " " << P.ny << " " << P.nz << " ";
#ifdef MPI_CHOLLA
out_file << nproc << " ";
#else
out_file << 1 << " ";
#endif
#ifdef PARALLEL_OMP
out_file << N_OMP_THREADS << " ";
#else
out_file << 0 << " ";
#endif
out_file << n_steps << " ";
#ifdef GRAVITY_COUPLE_CPU
out_file << time_dt_all << " ";
#endif
out_file << time_hydro_all << " ";
out_file << time_bound_all << " ";
#ifdef GRAVITY
out_file << time_potential_all << " ";
#ifdef GRAVITY_COUPLE_CPU
out_file << time_bound_pot_all << " ";
#endif
#endif
#ifdef PARTICLES
out_file << time_part_dens_all << " ";
out_file << time_part_tranf_all << " ";
out_file << time_part_dens_transf_all << " ";
out_file << time_advance_particles_1_all << " ";
out_file << time_advance_particles_2_all << " ";
#endif
#ifdef COOLING_GRACKLE
out_file << time_cooling_all << " ";
#endif
out_file << time_total << " ";
out_file << "\n";
out_file.close();
}
#endif<commit_msg>alloc calc_dt timing when using gpu for gravity<commit_after>
#ifdef CPU_TIME
#include "timing_functions.h"
#include "io.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
#ifdef MPI_CHOLLA
#include "mpi_routines.h"
#endif
Time::Time( void ){}
void Time::Initialize(){
n_steps = 0;
time_hydro_all = 0;
time_bound_all = 0;
time_dt_all = 0;
#ifdef GRAVITY
time_potential_all = 0;
#ifdef GRAVITY_COUPLE_CPU
time_bound_pot_all = 0;
#endif
#endif
#ifdef PARTICLES
time_part_dens_all = 0;
time_part_dens_transf_all = 0;
time_part_tranf_all = 0;
time_advance_particles_1_all = 0;
time_advance_particles_2_all = 0;
#endif
#ifdef COOLING_GRACKLE
time_cooling_all = 0;
#endif
chprintf( "\nTiming Functions is ON \n");
}
void Time::Start_Timer(){
time_start = get_time();
}
void Time::End_and_Record_Time( int time_var ){
time_end = get_time();
time = (time_end - time_start)*1000;
Real t_min, t_max, t_avg;
#ifdef MPI_CHOLLA
t_min = ReduceRealMin(time);
t_max = ReduceRealMax(time);
t_avg = ReduceRealAvg(time);
#else
t_min = time;
t_max = time;
t_avg = time;
#endif
if( time_var == 0 ){
time_dt_min = t_min;
time_dt_max = t_max;
time_dt_mean = t_avg;
if (n_steps > 0) time_dt_all += t_max;
}
if( time_var == 1 ){
time_hydro_min = t_min;
time_hydro_max = t_max;
time_hydro_mean = t_avg;
if (n_steps > 0) time_hydro_all += t_max;
}
if( time_var == 2 ){
time_bound_min = t_min;
time_bound_max = t_max;
time_bound_mean = t_avg;
if (n_steps > 0) time_bound_all += t_max;
}
#ifdef GRAVITY
if( time_var == 3 ){
time_potential_min = t_min;
time_potential_max = t_max;
time_potential_mean = t_avg;
if (n_steps > 0) time_potential_all += t_max;
}
#ifdef GRAVITY_COUPLE_CPU
if( time_var == 9 ){
time_bound_pot_min = t_min;
time_bound_pot_max = t_max;
time_bound_pot_mean = t_avg;
if (n_steps > 0) time_bound_pot_all += t_max;
}
#endif
#endif
#ifdef PARTICLES
if( time_var == 4 ){
time_part_dens_min = t_min;
time_part_dens_max = t_max;
time_part_dens_mean = t_avg;
if (n_steps > 0) time_part_dens_all += t_max;
}
if( time_var == 5 ){
time_part_dens_transf_min = t_min;
time_part_dens_transf_max = t_max;
time_part_dens_transf_mean = t_avg;
if (n_steps > 0) time_part_dens_transf_all += t_max;
}
if( time_var == 6 ){
time_advance_particles_1_min = t_min;
time_advance_particles_1_max = t_max;
time_advance_particles_1_mean = t_avg;
if (n_steps > 0) time_advance_particles_1_all += t_max;
}
if( time_var == 7 ){
time_advance_particles_2_min = t_min;
time_advance_particles_2_max = t_max;
time_advance_particles_2_mean = t_avg;
if (n_steps > 0) time_advance_particles_2_all += t_max;
}
if( time_var == 8 ){
time_part_tranf_min = t_min;
time_part_tranf_max = t_max;
time_part_tranf_mean = t_avg;
if (n_steps > 0) time_part_tranf_all += t_max;
}
#endif
#ifdef COOLING_GRACKLE
if( time_var == 10 ){
time_cooling_min = t_min;
time_cooling_max = t_max;
time_cooling_mean = t_avg;
if (n_steps > 0) time_cooling_all += t_max;
}
#endif
}
void Time::Print_Times(){
#if defined(GRAVITY_COUPLE_CPU) || defined( PARTICLES )
chprintf(" Time Calc dt min: %9.4f max: %9.4f avg: %9.4f ms\n", time_dt_min, time_dt_max, time_dt_mean);
#endif
chprintf(" Time Hydro min: %9.4f max: %9.4f avg: %9.4f ms\n", time_hydro_min, time_hydro_max, time_hydro_mean);
chprintf(" Time Boundaries min: %9.4f max: %9.4f avg: %9.4f ms\n", time_bound_min, time_bound_max, time_bound_mean);
#ifdef GRAVITY
chprintf(" Time Grav Potential min: %9.4f max: %9.4f avg: %9.4f ms\n", time_potential_min, time_potential_max, time_potential_mean);
#ifdef GRAVITY_COUPLE_CPU
chprintf(" Time Pot Boundaries min: %9.4f max: %9.4f avg: %9.4f ms\n", time_bound_pot_min, time_bound_pot_max, time_bound_pot_mean);
#endif
#endif
#ifdef PARTICLES
chprintf(" Time Part Density min: %9.4f max: %9.4f avg: %9.4f ms\n", time_part_dens_min, time_part_dens_max, time_part_dens_mean);
chprintf(" Time Part Boundaries min: %9.4f max: %9.4f avg: %9.4f ms\n", time_part_tranf_min, time_part_tranf_max, time_part_tranf_mean);
chprintf(" Time Part Dens Transf min: %9.4f max: %9.4f avg: %9.4f ms\n", time_part_dens_transf_min, time_part_dens_transf_max, time_part_dens_transf_mean);
chprintf(" Time Advance Part 1 min: %9.4f max: %9.4f avg: %9.4f ms\n", time_advance_particles_1_min, time_advance_particles_1_max, time_advance_particles_1_mean);
chprintf(" Time Advance Part 2 min: %9.4f max: %9.4f avg: %9.4f ms\n", time_advance_particles_2_min, time_advance_particles_2_max, time_advance_particles_2_mean);
#endif
#ifdef COOLING_GRACKLE
chprintf(" Time Cooling min: %9.4f max: %9.4f avg: %9.4f ms\n", time_cooling_min, time_cooling_max, time_cooling_mean);
#endif
}
void Time::Get_Average_Times(){
n_steps -= 1; //Ignore the first timestep
time_hydro_all /= n_steps;
time_bound_all /= n_steps;
#ifdef GRAVITY_COUPLE_CPU
time_dt_all /= n_steps;
time_bound_pot_all /= n_steps;
#endif
#ifdef GRAVITY
time_potential_all /= n_steps;
#ifdef PARTICLES
time_part_dens_all /= n_steps;
time_part_tranf_all /= n_steps;
time_part_dens_transf_all /= n_steps;
time_advance_particles_1_all /= n_steps;
time_advance_particles_2_all /= n_steps;
#endif
#endif
#ifdef COOLING_GRACKLE
time_cooling_all /= n_steps;
#endif
}
void Time::Print_Average_Times( struct parameters P ){
Real time_total;
time_total = time_hydro_all + time_bound_all;
#ifdef GRAVITY_COUPLE_CPU
time_total += time_dt_all;
time_total += time_bound_pot_all;
#endif
#ifdef GRAVITY
time_total += time_potential_all;
#ifdef PARTICLES
time_total += time_part_dens_all;
time_total += time_part_tranf_all;
time_total += time_part_dens_transf_all;
time_total += time_advance_particles_1_all;
time_total += time_advance_particles_2_all;
#endif
#endif
#ifdef COOLING_GRACKLE
time_total += time_cooling_all;
#endif
chprintf("\nAverage Times n_steps:%d\n", n_steps);
#ifdef GRAVITY_COUPLE_CPU
chprintf(" Time Calc dt avg: %9.4f ms\n", time_dt_all);
#endif
chprintf(" Time Hydro avg: %9.4f ms\n", time_hydro_all);
chprintf(" Time Boundaries avg: %9.4f ms\n", time_bound_all);
#ifdef GRAVITY
chprintf(" Time Grav Potential avg: %9.4f ms\n", time_potential_all);
#ifdef GRAVITY_COUPLE_CPU
chprintf(" Time Pot Boundaries avg: %9.4f ms\n", time_bound_pot_all);
#endif
#ifdef PARTICLES
chprintf(" Time Part Density avg: %9.4f ms\n", time_part_dens_all);
chprintf(" Time Part Boundaries avg: %9.4f ms\n", time_part_tranf_all);
chprintf(" Time Part Dens Transf avg: %9.4f ms\n", time_part_dens_transf_all);
chprintf(" Time Advance Part 1 avg: %9.4f ms\n", time_advance_particles_1_all);
chprintf(" Time Advance Part 2 avg: %9.4f ms\n", time_advance_particles_2_all);
#endif
#endif
#ifdef COOLING_GRACKLE
chprintf(" Time Cooling avg: %9.4f ms\n", time_cooling_all);
#endif
chprintf(" Time Total avg: %9.4f ms\n\n", time_total);
string file_name ( "run_timing.log" );
string header;
chprintf( "Writing timming values to file: %s \n", file_name.c_str());
header = "# nx ny nz n_proc n_omp n_steps ";
#ifdef GRAVITY_COUPLE_CPU
header += "dt ";
#endif
header += "hydo ";
header += "bound ";
#ifdef GRAVITY
header += "grav_pot ";
#ifdef GRAVITY_COUPLE_CPU
header += "pot_bound ";
#endif
#endif
#ifdef PARTICLES
header += "part_dens ";
header += "part_bound ";
header += "part_dens_boud ";
header += "part_adv_1 ";
header += "part_adv_2 ";
#endif
#ifdef COOLING_GRACKLE
header += "cool ";
#endif
header += "total ";
header += " \n";
bool file_exists = false;
if (FILE *file = fopen(file_name.c_str(), "r")){
file_exists = true;
chprintf( " File exists, appending values: %s \n\n", file_name.c_str() );
fclose( file );
} else{
chprintf( " Creating File: %s \n\n", file_name.c_str() );
}
#ifdef MPI_CHOLLA
if ( procID != 0 ) return;
#endif
ofstream out_file;
// Output timing values
out_file.open(file_name.c_str(), ios::app);
if ( !file_exists ) out_file << header;
out_file << P.nx << " " << P.ny << " " << P.nz << " ";
#ifdef MPI_CHOLLA
out_file << nproc << " ";
#else
out_file << 1 << " ";
#endif
#ifdef PARALLEL_OMP
out_file << N_OMP_THREADS << " ";
#else
out_file << 0 << " ";
#endif
out_file << n_steps << " ";
#ifdef GRAVITY_COUPLE_CPU
out_file << time_dt_all << " ";
#endif
out_file << time_hydro_all << " ";
out_file << time_bound_all << " ";
#ifdef GRAVITY
out_file << time_potential_all << " ";
#ifdef GRAVITY_COUPLE_CPU
out_file << time_bound_pot_all << " ";
#endif
#endif
#ifdef PARTICLES
out_file << time_part_dens_all << " ";
out_file << time_part_tranf_all << " ";
out_file << time_part_dens_transf_all << " ";
out_file << time_advance_particles_1_all << " ";
out_file << time_advance_particles_2_all << " ";
#endif
#ifdef COOLING_GRACKLE
out_file << time_cooling_all << " ";
#endif
out_file << time_total << " ";
out_file << "\n";
out_file.close();
}
#endif<|endoftext|>
|
<commit_before>// ***************************************************************************
// bamtools.cpp (c) 2010 Derek Barnett, Erik Garrison
// Marth Lab, Department of Biology, Boston College
// ---------------------------------------------------------------------------
// Last modified: 12 October 2012 (DB)
// ---------------------------------------------------------------------------
// Integrates a number of BamTools functionalities into a single executable.
// ***************************************************************************
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <sstream>
#include <string>
#include "bamtools_convert.h"
#include "bamtools_count.h"
#include "bamtools_coverage.h"
#include "bamtools_filter.h"
#include "bamtools_header.h"
#include "bamtools_index.h"
#include "bamtools_merge.h"
#include "bamtools_random.h"
#include "bamtools_resolve.h"
#include "bamtools_revert.h"
#include "bamtools_sort.h"
#include "bamtools_split.h"
#include "bamtools_stats.h"
#include "bamtools_version.h"
using namespace BamTools;
// bamtools subtool names
static const std::string CONVERT = "convert";
static const std::string COUNT = "count";
static const std::string COVERAGE = "coverage";
static const std::string FILTER = "filter";
static const std::string HEADER = "header";
static const std::string INDEX = "index";
static const std::string MERGE = "merge";
static const std::string RANDOM = "random";
static const std::string RESOLVE = "resolve";
static const std::string REVERT = "revert";
static const std::string SORT = "sort";
static const std::string SPLIT = "split";
static const std::string STATS = "stats";
// bamtools help/version constants
static const std::string HELP = "help";
static const std::string LONG_HELP = "--help";
static const std::string SHORT_HELP = "-h";
static const std::string VERSION = "version";
static const std::string LONG_VERSION = "--version";
static const std::string SHORT_VERSION = "-v";
// determine if string is a help constant
static bool IsHelp(char* str)
{
return (str == HELP || str == LONG_HELP || str == SHORT_HELP);
}
// determine if string is a version constant
static bool IsVersion(char* str)
{
return (str == VERSION || str == LONG_VERSION || str == SHORT_VERSION);
}
// subtool factory method
AbstractTool* CreateTool(const std::string& arg)
{
// determine tool type based on arg
if (arg == CONVERT) {
return new ConvertTool;
}
if (arg == COUNT) {
return new CountTool;
}
if (arg == COVERAGE) {
return new CoverageTool;
}
if (arg == FILTER) {
return new FilterTool;
}
if (arg == HEADER) {
return new HeaderTool;
}
if (arg == INDEX) {
return new IndexTool;
}
if (arg == MERGE) {
return new MergeTool;
}
if (arg == RANDOM) {
return new RandomTool;
}
if (arg == RESOLVE) {
return new ResolveTool;
}
if (arg == REVERT) {
return new RevertTool;
}
if (arg == SORT) {
return new SortTool;
}
if (arg == SPLIT) {
return new SplitTool;
}
if (arg == STATS) {
return new StatsTool;
}
// unknown arg
return 0;
}
// print help info
int Help(int argc, char* argv[])
{
// check for 'bamtools help COMMAND' to print tool-specific help message
if (argc > 2) {
// determine desired sub-tool
AbstractTool* tool = CreateTool(argv[2]);
// if tool known, print its help screen
if (tool) {
return tool->Help();
}
}
// print general BamTools help message
std::cerr << std::endl;
std::cerr << "usage: bamtools [--help] COMMAND [ARGS]" << std::endl;
std::cerr << std::endl;
std::cerr << "Available bamtools commands:" << std::endl;
std::cerr << "\tconvert Converts between BAM and a number of other formats"
<< std::endl;
std::cerr << "\tcount Prints number of alignments in BAM file(s)" << std::endl;
std::cerr << "\tcoverage Prints coverage statistics from the input BAM file"
<< std::endl;
std::cerr << "\tfilter Filters BAM file(s) by user-specified criteria" << std::endl;
std::cerr << "\theader Prints BAM header information" << std::endl;
std::cerr << "\tindex Generates index for BAM file" << std::endl;
std::cerr << "\tmerge Merge multiple BAM files into single file" << std::endl;
std::cerr << "\trandom Select random alignments from existing BAM file(s), intended "
"more as a testing tool."
<< std::endl;
std::cerr
<< "\tresolve Resolves paired-end reads (marking the IsProperPair flag as needed)"
<< std::endl;
std::cerr << "\trevert Removes duplicate marks and restores original base qualities"
<< std::endl;
std::cerr << "\tsort Sorts the BAM file according to some criteria" << std::endl;
std::cerr << "\tsplit Splits a BAM file on user-specified property, creating a new "
"BAM output file for each value found"
<< std::endl;
std::cerr << "\tstats Prints some basic statistics from input BAM file(s)"
<< std::endl;
std::cerr << std::endl;
std::cerr << "See 'bamtools help COMMAND' for more information on a specific command."
<< std::endl;
std::cerr << std::endl;
return EXIT_SUCCESS;
}
// print version info
int Version()
{
std::stringstream versionStream;
versionStream << BAMTOOLS_VERSION_MAJOR << '.' << BAMTOOLS_VERSION_MINOR << '.'
<< BAMTOOLS_VERSION_PATCH;
std::cout << std::endl;
std::cout << "bamtools " << versionStream.str() << std::endl;
std::cout << "Part of BamTools API and toolkit" << std::endl;
std::cout << "Primary authors: Derek Barnett, Erik Garrison, Michael Stromberg" << std::endl;
std::cout << "(c) 2009-2012 Marth Lab, Biology Dept., Boston College" << std::endl;
std::cout << std::endl;
return EXIT_SUCCESS;
}
// toolkit entry point
int main(int argc, char* argv[])
{
// just 'bamtools'
if (argc == 1) {
return Help(argc, argv);
}
// 'bamtools help', 'bamtools --help', or 'bamtools -h'
if (IsHelp(argv[1])) {
return Help(argc, argv);
}
// 'bamtools version', 'bamtools --version', or 'bamtools -v'
if (IsVersion(argv[1])) {
return Version();
}
// determine desired sub-tool, run if found
AbstractTool* tool = CreateTool(argv[1]);
if (tool) {
return tool->Run(argc, argv);
}
delete tool;
// no tool matched, show help
return Help(argc, argv);
}
<commit_msg>Fix the memory leak in `main()`<commit_after>// ***************************************************************************
// bamtools.cpp (c) 2010 Derek Barnett, Erik Garrison
// Marth Lab, Department of Biology, Boston College
// ---------------------------------------------------------------------------
// Last modified: 12 October 2012 (DB)
// ---------------------------------------------------------------------------
// Integrates a number of BamTools functionalities into a single executable.
// ***************************************************************************
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <sstream>
#include <string>
#include "bamtools_convert.h"
#include "bamtools_count.h"
#include "bamtools_coverage.h"
#include "bamtools_filter.h"
#include "bamtools_header.h"
#include "bamtools_index.h"
#include "bamtools_merge.h"
#include "bamtools_random.h"
#include "bamtools_resolve.h"
#include "bamtools_revert.h"
#include "bamtools_sort.h"
#include "bamtools_split.h"
#include "bamtools_stats.h"
#include "bamtools_version.h"
using namespace BamTools;
// bamtools subtool names
static const std::string CONVERT = "convert";
static const std::string COUNT = "count";
static const std::string COVERAGE = "coverage";
static const std::string FILTER = "filter";
static const std::string HEADER = "header";
static const std::string INDEX = "index";
static const std::string MERGE = "merge";
static const std::string RANDOM = "random";
static const std::string RESOLVE = "resolve";
static const std::string REVERT = "revert";
static const std::string SORT = "sort";
static const std::string SPLIT = "split";
static const std::string STATS = "stats";
// bamtools help/version constants
static const std::string HELP = "help";
static const std::string LONG_HELP = "--help";
static const std::string SHORT_HELP = "-h";
static const std::string VERSION = "version";
static const std::string LONG_VERSION = "--version";
static const std::string SHORT_VERSION = "-v";
// determine if string is a help constant
static bool IsHelp(char* str)
{
return (str == HELP || str == LONG_HELP || str == SHORT_HELP);
}
// determine if string is a version constant
static bool IsVersion(char* str)
{
return (str == VERSION || str == LONG_VERSION || str == SHORT_VERSION);
}
// subtool factory method
AbstractTool* CreateTool(const std::string& arg)
{
// determine tool type based on arg
if (arg == CONVERT) {
return new ConvertTool;
}
if (arg == COUNT) {
return new CountTool;
}
if (arg == COVERAGE) {
return new CoverageTool;
}
if (arg == FILTER) {
return new FilterTool;
}
if (arg == HEADER) {
return new HeaderTool;
}
if (arg == INDEX) {
return new IndexTool;
}
if (arg == MERGE) {
return new MergeTool;
}
if (arg == RANDOM) {
return new RandomTool;
}
if (arg == RESOLVE) {
return new ResolveTool;
}
if (arg == REVERT) {
return new RevertTool;
}
if (arg == SORT) {
return new SortTool;
}
if (arg == SPLIT) {
return new SplitTool;
}
if (arg == STATS) {
return new StatsTool;
}
// unknown arg
return 0;
}
// print help info
int Help(int argc, char* argv[])
{
// check for 'bamtools help COMMAND' to print tool-specific help message
if (argc > 2) {
// determine desired sub-tool
AbstractTool* tool = CreateTool(argv[2]);
// if tool known, print its help screen
if (tool) {
const int result = tool->Help();
delete tool;
return result;
}
}
// print general BamTools help message
std::cerr << std::endl;
std::cerr << "usage: bamtools [--help] COMMAND [ARGS]" << std::endl;
std::cerr << std::endl;
std::cerr << "Available bamtools commands:" << std::endl;
std::cerr << "\tconvert Converts between BAM and a number of other formats"
<< std::endl;
std::cerr << "\tcount Prints number of alignments in BAM file(s)" << std::endl;
std::cerr << "\tcoverage Prints coverage statistics from the input BAM file"
<< std::endl;
std::cerr << "\tfilter Filters BAM file(s) by user-specified criteria" << std::endl;
std::cerr << "\theader Prints BAM header information" << std::endl;
std::cerr << "\tindex Generates index for BAM file" << std::endl;
std::cerr << "\tmerge Merge multiple BAM files into single file" << std::endl;
std::cerr << "\trandom Select random alignments from existing BAM file(s), intended "
"more as a testing tool."
<< std::endl;
std::cerr
<< "\tresolve Resolves paired-end reads (marking the IsProperPair flag as needed)"
<< std::endl;
std::cerr << "\trevert Removes duplicate marks and restores original base qualities"
<< std::endl;
std::cerr << "\tsort Sorts the BAM file according to some criteria" << std::endl;
std::cerr << "\tsplit Splits a BAM file on user-specified property, creating a new "
"BAM output file for each value found"
<< std::endl;
std::cerr << "\tstats Prints some basic statistics from input BAM file(s)"
<< std::endl;
std::cerr << std::endl;
std::cerr << "See 'bamtools help COMMAND' for more information on a specific command."
<< std::endl;
std::cerr << std::endl;
return EXIT_SUCCESS;
}
// print version info
int Version()
{
std::stringstream versionStream;
versionStream << BAMTOOLS_VERSION_MAJOR << '.' << BAMTOOLS_VERSION_MINOR << '.'
<< BAMTOOLS_VERSION_PATCH;
std::cout << std::endl;
std::cout << "bamtools " << versionStream.str() << std::endl;
std::cout << "Part of BamTools API and toolkit" << std::endl;
std::cout << "Primary authors: Derek Barnett, Erik Garrison, Michael Stromberg" << std::endl;
std::cout << "(c) 2009-2012 Marth Lab, Biology Dept., Boston College" << std::endl;
std::cout << std::endl;
return EXIT_SUCCESS;
}
// toolkit entry point
int main(int argc, char* argv[])
{
// just 'bamtools'
if (argc == 1) {
return Help(argc, argv);
}
// 'bamtools help', 'bamtools --help', or 'bamtools -h'
if (IsHelp(argv[1])) {
return Help(argc, argv);
}
// 'bamtools version', 'bamtools --version', or 'bamtools -v'
if (IsVersion(argv[1])) {
return Version();
}
// determine desired sub-tool, run if found
AbstractTool* tool = CreateTool(argv[1]);
if (tool) {
const int result = tool->Run(argc, argv);
delete tool;
return result;
}
// no tool matched, show help
return Help(argc, argv);
}
<|endoftext|>
|
<commit_before>//// lXDR.cc
//
// Simple XDR class, see header
//
// WGL, 24 May 2002
//
////
#include "UTIL/lXDR.hh"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#if defined(__APPLE_CC__)
#include "/usr/include/sys/types.h"
#endif
#if defined(__linux) || defined(__CYGWIN__) || defined(__APPLE_CC__)
#include <netinet/in.h>
#endif
#ifdef _MSC_VER
#include <winsock.h>
#else
#include <sys/socket.h>
#endif
namespace UTIL{
////
//
// Constructor, destructor
//
////
lXDR::~lXDR()
{
if (_fp) {
fclose(_fp);
_fp = 0;
}
if (_fileName) {
delete [] _fileName;
_fileName = 0;
}
return;
}
lXDR::lXDR(const char *filename, bool open_for_write) : _fileName(0), _fp(0)
{
setFileName(filename, open_for_write);
if (htonl(1L) == 1L) _hasNetworkOrder = true;
else _hasNetworkOrder = false;
return;
}
void lXDR::setFileName(const char *filename, bool open_for_write)
{
//
// First check if we can open this file
//
if (filename == 0) {
_error = LXDR_OPENFAILURE;
return;
}
#ifdef _MSC_VER
FILE *fp = fopen(filename, open_for_write ? "wb" : "rb");
#else
FILE *fp = fopen(filename, open_for_write ? "w" : "r");
#endif
if (fp == 0) {
_error = LXDR_OPENFAILURE;
return;
}
if (_fp) fclose(_fp);
_fp = fp;
if (_fileName) {
delete [] _fileName;
_fileName = 0;
}
int n = strlen(filename);
_fileName = new char [n + 1];
strncpy(_fileName, filename, n);
_fileName[n] = '\0';
_openForWrite = open_for_write;
_error = LXDR_SUCCESS;
return;
}
double lXDR::ntohd(double d) const
{
//
// If we already have network order, we don't swap
//
if (_hasNetworkOrder == false) {
union {
double d;
unsigned char b[8];
} dd;
int i;
dd.d = d;
for (i = 0; i < 4; i++) {
unsigned char c = dd.b[i];
dd.b[i] = dd.b[7 - i];
dd.b[7 - i] = c;
}
d = dd.d;
}
return(d);
}
long lXDR::checkRead(long *l)
{
if (_openForWrite) return(_error = LXDR_READONLY);
if (_fp == 0) return(_error = LXDR_NOFILE);
if (l) {
// je: in architectures where long isn't 4 byte long this code crashes
//long nr;
//if ((nr = fread(l, 4, 1, _fp)) != 1) return(_error = LXDR_READERROR);
//*l = ntohl(*l);
int32_t buf;
if (fread(&buf, 4, 1, _fp) != 1) return(_error = LXDR_READERROR);
*l = ((int32_t)ntohl(buf));
}
return(LXDR_SUCCESS);
}
long lXDR::checkRead(double *d)
{
if (_openForWrite) return(_error = LXDR_READONLY);
if (_fp == 0) return(_error = LXDR_NOFILE);
if (d) {
if (fread(d, 8, 1, _fp) != 1) return(_error = LXDR_READERROR);
*d = ntohd(*d);
}
return(LXDR_SUCCESS);
}
long lXDR::checkRead(float *f)
{
if (_openForWrite) return(_error = LXDR_READONLY);
if (_fp == 0) return(_error = LXDR_NOFILE);
if (f) {
if (fread(f, 4, 1, _fp) != 1) return(_error = LXDR_READERROR);
// je: in architectures where long isn't 4 byte long this code crashes
//*((long *) f) = ntohl(*((long *) f));
*((int32_t *) f) = ntohl(*((int32_t *) f));
}
return(LXDR_SUCCESS);
}
long lXDR::readLong(void)
{
long l = 0;
checkRead(&l);
return(l);
}
double lXDR::readDouble(void)
{
double d = 0.0;
checkRead(&d);
return(d);
}
double lXDR::readFloat(void)
{
float f = 0.0;
checkRead(&f);
return((double) f);
}
const char *lXDR::readString(long &length)
{
if (checkRead(&length)) return(0);
long rl = (length + 3) & 0xFFFFFFFC;
char *s = new char[rl + 1];
if (fread(s, 1, rl, _fp) != (unsigned long) rl) {
_error = LXDR_READERROR;
delete [] s;
return(0);
}
s[rl] = '\0';
_error = LXDR_SUCCESS;
return(s);
}
long *lXDR::readLongArray(long &length)
{
if (checkRead(&length)) return(0);
long *s = new long[length];
// je: in architectures where long isn't 4 byte long this code crashes
//if (fread(s, 4, length, _fp) != (unsigned long) length) {
// _error = LXDR_READERROR;
// delete [] s;
// return(0);
//}
//if (_hasNetworkOrder == false) for (long i = 0; i < length; i++) s[i] = ntohl(s[i]);
int32_t *buf = new int32_t[length];
if (fread(buf, 4, length, _fp) != (unsigned long) length) {
_error = LXDR_READERROR;
delete [] buf;
delete [] s;
return(0);
}
for (long i = 0; i < length; i++){
if (_hasNetworkOrder == false){
s[i] = ((int32_t)ntohl(buf[i]));
}
else{
s[i] = (long)buf[i];
}
}
delete [] buf;
_error = LXDR_SUCCESS;
return(s);
}
double *lXDR::readDoubleArray(long &length)
{
if (checkRead(&length)) return(0);
double *s = new double[length];
if (fread(s, 8, length, _fp) != (unsigned long) length) {
_error = LXDR_READERROR;
delete [] s;
return(0);
}
if (_hasNetworkOrder == false) for (long i = 0; i < length; i++) s[i] = ntohd(s[i]);
_error = LXDR_SUCCESS;
return(s);
}
double *lXDR::readFloatArray(long &length)
{
if (checkRead(&length)) return(0);
long *st = new long[length];
// je: FIXME this will cause problems in architectures where long isn't 4 byte long
if (fread(st, 4, length, _fp) != (unsigned long) length) {
_error = LXDR_READERROR;
delete [] st;
return(0);
}
double *s = new double[length];
// je: FIXME what happens if _hasNetworkOrder == true?!
if (_hasNetworkOrder == false) {
for (long i = 0; i < length; i++) {
long l = ntohl(st[i]);
// s[i] = (double) (*((float *) &l));
//fg: the above causes a strict aliasing error, so we sue memcpy
float f ;
memcpy( &f, &l, sizeof(float) ) ;
s[i] = f ;
}
}
_error = LXDR_SUCCESS;
delete [] st;
return(s);
}
long lXDR::checkWrite(long *l)
{
if (_openForWrite == false) return(_error = LXDR_WRITEONLY);
if (_fp == 0) return(_error = LXDR_NOFILE);
if (l) {
long ll = htonl(*l);
// je: FIXME this will cause problems in architectures where long isn't 4 byte long
if (fwrite(&ll, 4, 1, _fp) != 4) return(_error = LXDR_WRITEERROR);
}
return(LXDR_SUCCESS);
}
long lXDR::checkWrite(double *d)
{
if (_openForWrite == false) return(_error = LXDR_WRITEONLY);
if (_fp == 0) return(_error = LXDR_NOFILE);
if (d) {
double dd = htond(*d);
if (fwrite(&dd, 8, 1, _fp) != 8) return(_error = LXDR_WRITEERROR);
}
return(LXDR_SUCCESS);
}
long lXDR::writeLong(long data)
{
return(checkWrite(&data));
}
long lXDR::writeDouble(double data)
{
return(checkWrite(&data));
}
long lXDR::writeString(const char *data)
{
return(writeString(data, strlen(data)));
}
long lXDR::writeString(const char *data, long length)
{
if (checkWrite(&length)) return(_error);
if (fwrite(data, 1, length, _fp) != (unsigned long) length) return(_error = LXDR_WRITEERROR);
long l = ((length + 3) & 0xFFFFFFFC) - length;
if (fwrite(&l, 1, l, _fp) != (unsigned long) l) return(_error = LXDR_WRITEERROR);
return(_error = LXDR_SUCCESS);
}
long lXDR::writeLongArray(const long *data, long length)
{
if (checkWrite(&length)) return(_error);
long *s = (long *) data;
if (_hasNetworkOrder == false) {
s = new long[length];
for (long i = 0; i < length; i++) s[i] = htonl(data[i]);
}
// je: FIXME this will cause problems in architectures where long isn't 4 byte long
long l = fwrite(s, 4, length, _fp);
if (_hasNetworkOrder == false) delete [] s;
if (l != length) return(_error = LXDR_WRITEERROR);
return(_error = LXDR_SUCCESS);
}
long lXDR::writeDoubleArray(const double *data, long length)
{
if (checkWrite(&length)) return(_error);
double *s = (double *) data;
if (_hasNetworkOrder == false) {
s = new double[length];
for (long i = 0; i < length; i++) s[i] = htond(data[i]);
}
long l = fwrite(s, 8, length, _fp);
if (_hasNetworkOrder == false) delete [] s;
if (l != length) return(_error = LXDR_WRITEERROR);
return(_error = LXDR_SUCCESS);
}
long lXDR::filePosition(long pos)
{
if (_fp == 0) {
_error = LXDR_NOFILE;
return(-1);
}
if (pos == -1) return(ftell(_fp));
if (fseek(_fp, pos, SEEK_SET)) {
_error = LXDR_SEEKERROR;
return(-1);
}
return(pos);
}
}// end namespace
<commit_msg>fix building for MacOS 10.14<commit_after>//// lXDR.cc
//
// Simple XDR class, see header
//
// WGL, 24 May 2002
//
////
#include "UTIL/lXDR.hh"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#if defined(__linux) || defined(__CYGWIN__) || defined(__APPLE_CC__)
#include <netinet/in.h>
#endif
#ifdef _MSC_VER
#include <winsock.h>
#else
#include <sys/socket.h>
#endif
namespace UTIL{
////
//
// Constructor, destructor
//
////
lXDR::~lXDR()
{
if (_fp) {
fclose(_fp);
_fp = 0;
}
if (_fileName) {
delete [] _fileName;
_fileName = 0;
}
return;
}
lXDR::lXDR(const char *filename, bool open_for_write) : _fileName(0), _fp(0)
{
setFileName(filename, open_for_write);
if (htonl(1L) == 1L) _hasNetworkOrder = true;
else _hasNetworkOrder = false;
return;
}
void lXDR::setFileName(const char *filename, bool open_for_write)
{
//
// First check if we can open this file
//
if (filename == 0) {
_error = LXDR_OPENFAILURE;
return;
}
#ifdef _MSC_VER
FILE *fp = fopen(filename, open_for_write ? "wb" : "rb");
#else
FILE *fp = fopen(filename, open_for_write ? "w" : "r");
#endif
if (fp == 0) {
_error = LXDR_OPENFAILURE;
return;
}
if (_fp) fclose(_fp);
_fp = fp;
if (_fileName) {
delete [] _fileName;
_fileName = 0;
}
int n = strlen(filename);
_fileName = new char [n + 1];
strncpy(_fileName, filename, n);
_fileName[n] = '\0';
_openForWrite = open_for_write;
_error = LXDR_SUCCESS;
return;
}
double lXDR::ntohd(double d) const
{
//
// If we already have network order, we don't swap
//
if (_hasNetworkOrder == false) {
union {
double d;
unsigned char b[8];
} dd;
int i;
dd.d = d;
for (i = 0; i < 4; i++) {
unsigned char c = dd.b[i];
dd.b[i] = dd.b[7 - i];
dd.b[7 - i] = c;
}
d = dd.d;
}
return(d);
}
long lXDR::checkRead(long *l)
{
if (_openForWrite) return(_error = LXDR_READONLY);
if (_fp == 0) return(_error = LXDR_NOFILE);
if (l) {
// je: in architectures where long isn't 4 byte long this code crashes
//long nr;
//if ((nr = fread(l, 4, 1, _fp)) != 1) return(_error = LXDR_READERROR);
//*l = ntohl(*l);
int32_t buf;
if (fread(&buf, 4, 1, _fp) != 1) return(_error = LXDR_READERROR);
*l = ((int32_t)ntohl(buf));
}
return(LXDR_SUCCESS);
}
long lXDR::checkRead(double *d)
{
if (_openForWrite) return(_error = LXDR_READONLY);
if (_fp == 0) return(_error = LXDR_NOFILE);
if (d) {
if (fread(d, 8, 1, _fp) != 1) return(_error = LXDR_READERROR);
*d = ntohd(*d);
}
return(LXDR_SUCCESS);
}
long lXDR::checkRead(float *f)
{
if (_openForWrite) return(_error = LXDR_READONLY);
if (_fp == 0) return(_error = LXDR_NOFILE);
if (f) {
if (fread(f, 4, 1, _fp) != 1) return(_error = LXDR_READERROR);
// je: in architectures where long isn't 4 byte long this code crashes
//*((long *) f) = ntohl(*((long *) f));
*((int32_t *) f) = ntohl(*((int32_t *) f));
}
return(LXDR_SUCCESS);
}
long lXDR::readLong(void)
{
long l = 0;
checkRead(&l);
return(l);
}
double lXDR::readDouble(void)
{
double d = 0.0;
checkRead(&d);
return(d);
}
double lXDR::readFloat(void)
{
float f = 0.0;
checkRead(&f);
return((double) f);
}
const char *lXDR::readString(long &length)
{
if (checkRead(&length)) return(0);
long rl = (length + 3) & 0xFFFFFFFC;
char *s = new char[rl + 1];
if (fread(s, 1, rl, _fp) != (unsigned long) rl) {
_error = LXDR_READERROR;
delete [] s;
return(0);
}
s[rl] = '\0';
_error = LXDR_SUCCESS;
return(s);
}
long *lXDR::readLongArray(long &length)
{
if (checkRead(&length)) return(0);
long *s = new long[length];
// je: in architectures where long isn't 4 byte long this code crashes
//if (fread(s, 4, length, _fp) != (unsigned long) length) {
// _error = LXDR_READERROR;
// delete [] s;
// return(0);
//}
//if (_hasNetworkOrder == false) for (long i = 0; i < length; i++) s[i] = ntohl(s[i]);
int32_t *buf = new int32_t[length];
if (fread(buf, 4, length, _fp) != (unsigned long) length) {
_error = LXDR_READERROR;
delete [] buf;
delete [] s;
return(0);
}
for (long i = 0; i < length; i++){
if (_hasNetworkOrder == false){
s[i] = ((int32_t)ntohl(buf[i]));
}
else{
s[i] = (long)buf[i];
}
}
delete [] buf;
_error = LXDR_SUCCESS;
return(s);
}
double *lXDR::readDoubleArray(long &length)
{
if (checkRead(&length)) return(0);
double *s = new double[length];
if (fread(s, 8, length, _fp) != (unsigned long) length) {
_error = LXDR_READERROR;
delete [] s;
return(0);
}
if (_hasNetworkOrder == false) for (long i = 0; i < length; i++) s[i] = ntohd(s[i]);
_error = LXDR_SUCCESS;
return(s);
}
double *lXDR::readFloatArray(long &length)
{
if (checkRead(&length)) return(0);
long *st = new long[length];
// je: FIXME this will cause problems in architectures where long isn't 4 byte long
if (fread(st, 4, length, _fp) != (unsigned long) length) {
_error = LXDR_READERROR;
delete [] st;
return(0);
}
double *s = new double[length];
// je: FIXME what happens if _hasNetworkOrder == true?!
if (_hasNetworkOrder == false) {
for (long i = 0; i < length; i++) {
long l = ntohl(st[i]);
// s[i] = (double) (*((float *) &l));
//fg: the above causes a strict aliasing error, so we sue memcpy
float f ;
memcpy( &f, &l, sizeof(float) ) ;
s[i] = f ;
}
}
_error = LXDR_SUCCESS;
delete [] st;
return(s);
}
long lXDR::checkWrite(long *l)
{
if (_openForWrite == false) return(_error = LXDR_WRITEONLY);
if (_fp == 0) return(_error = LXDR_NOFILE);
if (l) {
long ll = htonl(*l);
// je: FIXME this will cause problems in architectures where long isn't 4 byte long
if (fwrite(&ll, 4, 1, _fp) != 4) return(_error = LXDR_WRITEERROR);
}
return(LXDR_SUCCESS);
}
long lXDR::checkWrite(double *d)
{
if (_openForWrite == false) return(_error = LXDR_WRITEONLY);
if (_fp == 0) return(_error = LXDR_NOFILE);
if (d) {
double dd = htond(*d);
if (fwrite(&dd, 8, 1, _fp) != 8) return(_error = LXDR_WRITEERROR);
}
return(LXDR_SUCCESS);
}
long lXDR::writeLong(long data)
{
return(checkWrite(&data));
}
long lXDR::writeDouble(double data)
{
return(checkWrite(&data));
}
long lXDR::writeString(const char *data)
{
return(writeString(data, strlen(data)));
}
long lXDR::writeString(const char *data, long length)
{
if (checkWrite(&length)) return(_error);
if (fwrite(data, 1, length, _fp) != (unsigned long) length) return(_error = LXDR_WRITEERROR);
long l = ((length + 3) & 0xFFFFFFFC) - length;
if (fwrite(&l, 1, l, _fp) != (unsigned long) l) return(_error = LXDR_WRITEERROR);
return(_error = LXDR_SUCCESS);
}
long lXDR::writeLongArray(const long *data, long length)
{
if (checkWrite(&length)) return(_error);
long *s = (long *) data;
if (_hasNetworkOrder == false) {
s = new long[length];
for (long i = 0; i < length; i++) s[i] = htonl(data[i]);
}
// je: FIXME this will cause problems in architectures where long isn't 4 byte long
long l = fwrite(s, 4, length, _fp);
if (_hasNetworkOrder == false) delete [] s;
if (l != length) return(_error = LXDR_WRITEERROR);
return(_error = LXDR_SUCCESS);
}
long lXDR::writeDoubleArray(const double *data, long length)
{
if (checkWrite(&length)) return(_error);
double *s = (double *) data;
if (_hasNetworkOrder == false) {
s = new double[length];
for (long i = 0; i < length; i++) s[i] = htond(data[i]);
}
long l = fwrite(s, 8, length, _fp);
if (_hasNetworkOrder == false) delete [] s;
if (l != length) return(_error = LXDR_WRITEERROR);
return(_error = LXDR_SUCCESS);
}
long lXDR::filePosition(long pos)
{
if (_fp == 0) {
_error = LXDR_NOFILE;
return(-1);
}
if (pos == -1) return(ftell(_fp));
if (fseek(_fp, pos, SEEK_SET)) {
_error = LXDR_SEEKERROR;
return(-1);
}
return(pos);
}
}// end namespace
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2004-2005 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Kevin Lim
*/
#include <vector>
#include "cpu/o3/rename_map.hh"
#include "debug/Rename.hh"
using namespace std;
// @todo: Consider making inline bool functions that determine if the
// register is a logical int, logical fp, physical int, physical fp,
// etc.
SimpleRenameMap::~SimpleRenameMap()
{
}
void
SimpleRenameMap::init(unsigned _numLogicalIntRegs,
unsigned _numPhysicalIntRegs,
PhysRegIndex &ireg_idx,
unsigned _numLogicalFloatRegs,
unsigned _numPhysicalFloatRegs,
PhysRegIndex &freg_idx,
unsigned _numMiscRegs,
RegIndex _intZeroReg,
RegIndex _floatZeroReg,
int map_id,
bool bindRegs)
{
id = map_id;
numLogicalIntRegs = _numLogicalIntRegs;
numLogicalFloatRegs = _numLogicalFloatRegs;
numPhysicalIntRegs = _numPhysicalIntRegs;
numPhysicalFloatRegs = _numPhysicalFloatRegs;
numMiscRegs = _numMiscRegs;
intZeroReg = _intZeroReg;
floatZeroReg = _floatZeroReg;
DPRINTF(Rename, "Creating rename map %i. Phys: %i / %i, Float: "
"%i / %i.\n", id, numLogicalIntRegs, numPhysicalIntRegs,
numLogicalFloatRegs, numPhysicalFloatRegs);
numLogicalRegs = numLogicalIntRegs + numLogicalFloatRegs;
numPhysicalRegs = numPhysicalIntRegs + numPhysicalFloatRegs;
//Create the rename maps
intRenameMap.resize(numLogicalIntRegs);
floatRenameMap.resize(numLogicalRegs);
if (bindRegs) {
DPRINTF(Rename, "Binding registers into rename map %i\n",id);
// Initialize the entries in the integer rename map to point to the
// physical registers of the same index
for (RegIndex index = 0; index < numLogicalIntRegs; ++index)
{
intRenameMap[index].physical_reg = ireg_idx++;
}
// Initialize the entries in the floating point rename map to point to
// the physical registers of the same index
// Although the index refers purely to architected registers, because
// the floating reg indices come after the integer reg indices, they
// may exceed the size of a normal RegIndex (short).
for (PhysRegIndex index = numLogicalIntRegs;
index < numLogicalRegs; ++index)
{
floatRenameMap[index].physical_reg = freg_idx++;
}
} else {
DPRINTF(Rename, "Binding registers into rename map %i\n",id);
PhysRegIndex temp_ireg = ireg_idx;
for (RegIndex index = 0; index < numLogicalIntRegs; ++index)
{
intRenameMap[index].physical_reg = temp_ireg++;
}
PhysRegIndex temp_freg = freg_idx;
for (PhysRegIndex index = numLogicalIntRegs;
index < numLogicalRegs; ++index)
{
floatRenameMap[index].physical_reg = temp_freg++;
}
}
}
void
SimpleRenameMap::setFreeList(SimpleFreeList *fl_ptr)
{
freeList = fl_ptr;
}
SimpleRenameMap::RenameInfo
SimpleRenameMap::rename(RegIndex arch_reg)
{
PhysRegIndex renamed_reg;
PhysRegIndex prev_reg;
if (arch_reg < numLogicalIntRegs) {
// Record the current physical register that is renamed to the
// requested architected register.
prev_reg = intRenameMap[arch_reg].physical_reg;
// If it's not referencing the zero register, then rename the
// register.
if (arch_reg != intZeroReg) {
renamed_reg = freeList->getIntReg();
intRenameMap[arch_reg].physical_reg = renamed_reg;
assert(renamed_reg >= 0 && renamed_reg < numPhysicalIntRegs);
} else {
// Otherwise return the zero register so nothing bad happens.
renamed_reg = intZeroReg;
}
} else if (arch_reg < numLogicalRegs) {
// Record the current physical register that is renamed to the
// requested architected register.
prev_reg = floatRenameMap[arch_reg].physical_reg;
// If it's not referencing the zero register, then rename the
// register.
#if THE_ISA == ALPHA_ISA
if (arch_reg != floatZeroReg) {
#endif
renamed_reg = freeList->getFloatReg();
floatRenameMap[arch_reg].physical_reg = renamed_reg;
assert(renamed_reg < numPhysicalRegs &&
renamed_reg >= numPhysicalIntRegs);
#if THE_ISA == ALPHA_ISA
} else {
// Otherwise return the zero register so nothing bad happens.
renamed_reg = floatZeroReg;
}
#endif
} else {
// Subtract off the base offset for miscellaneous registers.
arch_reg = arch_reg - numLogicalRegs;
DPRINTF(Rename, "Renamed misc reg %d\n", arch_reg);
// No renaming happens to the misc. registers. They are
// simply the registers that come after all the physical
// registers; thus take the base architected register and add
// the physical registers to it.
renamed_reg = arch_reg + numPhysicalRegs;
// Set the previous register to the same register; mainly it must be
// known that the prev reg was outside the range of normal registers
// so the free list can avoid adding it.
prev_reg = renamed_reg;
}
DPRINTF(Rename, "Renamed reg %d to physical reg %d old mapping was %d\n",
arch_reg, renamed_reg, prev_reg);
return RenameInfo(renamed_reg, prev_reg);
}
PhysRegIndex
SimpleRenameMap::lookup(RegIndex arch_reg)
{
if (arch_reg < numLogicalIntRegs) {
return intRenameMap[arch_reg].physical_reg;
} else if (arch_reg < numLogicalRegs) {
return floatRenameMap[arch_reg].physical_reg;
} else {
// Subtract off the misc registers offset.
arch_reg = arch_reg - numLogicalRegs;
// Misc. regs don't rename, so simply add the base arch reg to
// the number of physical registers.
return numPhysicalRegs + arch_reg;
}
}
void
SimpleRenameMap::setEntry(RegIndex arch_reg, PhysRegIndex renamed_reg)
{
// In this implementation the miscellaneous registers do not
// actually rename, so this function does not allow you to try to
// change their mappings.
if (arch_reg < numLogicalIntRegs) {
DPRINTF(Rename, "Rename Map: Integer register %i being set to %i.\n",
(int)arch_reg, renamed_reg);
intRenameMap[arch_reg].physical_reg = renamed_reg;
} else if (arch_reg < numLogicalIntRegs + numLogicalFloatRegs) {
DPRINTF(Rename, "Rename Map: Float register %i being set to %i.\n",
(int)arch_reg - numLogicalIntRegs, renamed_reg);
floatRenameMap[arch_reg].physical_reg = renamed_reg;
}
}
int
SimpleRenameMap::numFreeEntries()
{
int free_int_regs = freeList->numFreeIntRegs();
int free_float_regs = freeList->numFreeFloatRegs();
if (free_int_regs < free_float_regs) {
return free_int_regs;
} else {
return free_float_regs;
}
}
<commit_msg>o3 cpu: fix zero reg problem There was an issue w/ the rename logic, which would assign a previous physical register to the ZeroReg architectural register in x86. This issue was giving problems for instructions squashed in threads w/ ID different from 0, sometimes allowing non-mispredicted instructions to obtain a value different from zero when reading the zeroReg.<commit_after>/*
* Copyright (c) 2004-2005 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Kevin Lim
*/
#include <vector>
#include "cpu/o3/rename_map.hh"
#include "debug/Rename.hh"
using namespace std;
// @todo: Consider making inline bool functions that determine if the
// register is a logical int, logical fp, physical int, physical fp,
// etc.
SimpleRenameMap::~SimpleRenameMap()
{
}
void
SimpleRenameMap::init(unsigned _numLogicalIntRegs,
unsigned _numPhysicalIntRegs,
PhysRegIndex &ireg_idx,
unsigned _numLogicalFloatRegs,
unsigned _numPhysicalFloatRegs,
PhysRegIndex &freg_idx,
unsigned _numMiscRegs,
RegIndex _intZeroReg,
RegIndex _floatZeroReg,
int map_id,
bool bindRegs)
{
id = map_id;
numLogicalIntRegs = _numLogicalIntRegs;
numLogicalFloatRegs = _numLogicalFloatRegs;
numPhysicalIntRegs = _numPhysicalIntRegs;
numPhysicalFloatRegs = _numPhysicalFloatRegs;
numMiscRegs = _numMiscRegs;
intZeroReg = _intZeroReg;
floatZeroReg = _floatZeroReg;
DPRINTF(Rename, "Creating rename map %i. Phys: %i / %i, Float: "
"%i / %i.\n", id, numLogicalIntRegs, numPhysicalIntRegs,
numLogicalFloatRegs, numPhysicalFloatRegs);
numLogicalRegs = numLogicalIntRegs + numLogicalFloatRegs;
numPhysicalRegs = numPhysicalIntRegs + numPhysicalFloatRegs;
//Create the rename maps
intRenameMap.resize(numLogicalIntRegs);
floatRenameMap.resize(numLogicalRegs);
if (bindRegs) {
DPRINTF(Rename, "Binding registers into rename map %i\n",id);
// Initialize the entries in the integer rename map to point to the
// physical registers of the same index
for (RegIndex index = 0; index < numLogicalIntRegs; ++index)
{
intRenameMap[index].physical_reg = ireg_idx++;
}
// Initialize the entries in the floating point rename map to point to
// the physical registers of the same index
// Although the index refers purely to architected registers, because
// the floating reg indices come after the integer reg indices, they
// may exceed the size of a normal RegIndex (short).
for (PhysRegIndex index = numLogicalIntRegs;
index < numLogicalRegs; ++index)
{
floatRenameMap[index].physical_reg = freg_idx++;
}
} else {
DPRINTF(Rename, "Binding registers into rename map %i\n",id);
PhysRegIndex temp_ireg = ireg_idx;
for (RegIndex index = 0; index < numLogicalIntRegs; ++index)
{
intRenameMap[index].physical_reg = temp_ireg++;
}
PhysRegIndex temp_freg = freg_idx;
for (PhysRegIndex index = numLogicalIntRegs;
index < numLogicalRegs; ++index)
{
floatRenameMap[index].physical_reg = temp_freg++;
}
}
}
void
SimpleRenameMap::setFreeList(SimpleFreeList *fl_ptr)
{
freeList = fl_ptr;
}
SimpleRenameMap::RenameInfo
SimpleRenameMap::rename(RegIndex arch_reg)
{
PhysRegIndex renamed_reg;
PhysRegIndex prev_reg;
if (arch_reg < numLogicalIntRegs) {
// Record the current physical register that is renamed to the
// requested architected register.
prev_reg = intRenameMap[arch_reg].physical_reg;
// If it's not referencing the zero register, then rename the
// register.
if (arch_reg != intZeroReg) {
renamed_reg = freeList->getIntReg();
intRenameMap[arch_reg].physical_reg = renamed_reg;
assert(renamed_reg >= 0 && renamed_reg < numPhysicalIntRegs);
} else {
// Otherwise return the zero register so nothing bad happens.
renamed_reg = intZeroReg;
prev_reg = intZeroReg;
}
} else if (arch_reg < numLogicalRegs) {
// Record the current physical register that is renamed to the
// requested architected register.
prev_reg = floatRenameMap[arch_reg].physical_reg;
// If it's not referencing the zero register, then rename the
// register.
#if THE_ISA == ALPHA_ISA
if (arch_reg != floatZeroReg) {
#endif
renamed_reg = freeList->getFloatReg();
floatRenameMap[arch_reg].physical_reg = renamed_reg;
assert(renamed_reg < numPhysicalRegs &&
renamed_reg >= numPhysicalIntRegs);
#if THE_ISA == ALPHA_ISA
} else {
// Otherwise return the zero register so nothing bad happens.
renamed_reg = floatZeroReg;
}
#endif
} else {
// Subtract off the base offset for miscellaneous registers.
arch_reg = arch_reg - numLogicalRegs;
DPRINTF(Rename, "Renamed misc reg %d\n", arch_reg);
// No renaming happens to the misc. registers. They are
// simply the registers that come after all the physical
// registers; thus take the base architected register and add
// the physical registers to it.
renamed_reg = arch_reg + numPhysicalRegs;
// Set the previous register to the same register; mainly it must be
// known that the prev reg was outside the range of normal registers
// so the free list can avoid adding it.
prev_reg = renamed_reg;
}
DPRINTF(Rename, "Renamed reg %d to physical reg %d old mapping was %d\n",
arch_reg, renamed_reg, prev_reg);
return RenameInfo(renamed_reg, prev_reg);
}
PhysRegIndex
SimpleRenameMap::lookup(RegIndex arch_reg)
{
if (arch_reg < numLogicalIntRegs) {
return intRenameMap[arch_reg].physical_reg;
} else if (arch_reg < numLogicalRegs) {
return floatRenameMap[arch_reg].physical_reg;
} else {
// Subtract off the misc registers offset.
arch_reg = arch_reg - numLogicalRegs;
// Misc. regs don't rename, so simply add the base arch reg to
// the number of physical registers.
return numPhysicalRegs + arch_reg;
}
}
void
SimpleRenameMap::setEntry(RegIndex arch_reg, PhysRegIndex renamed_reg)
{
// In this implementation the miscellaneous registers do not
// actually rename, so this function does not allow you to try to
// change their mappings.
if (arch_reg < numLogicalIntRegs) {
DPRINTF(Rename, "Rename Map: Integer register %i being set to %i.\n",
(int)arch_reg, renamed_reg);
intRenameMap[arch_reg].physical_reg = renamed_reg;
} else if (arch_reg < numLogicalIntRegs + numLogicalFloatRegs) {
DPRINTF(Rename, "Rename Map: Float register %i being set to %i.\n",
(int)arch_reg - numLogicalIntRegs, renamed_reg);
floatRenameMap[arch_reg].physical_reg = renamed_reg;
}
}
int
SimpleRenameMap::numFreeEntries()
{
int free_int_regs = freeList->numFreeIntRegs();
int free_float_regs = freeList->numFreeFloatRegs();
if (free_int_regs < free_float_regs) {
return free_int_regs;
} else {
return free_float_regs;
}
}
<|endoftext|>
|
<commit_before>/*=========================================================================
Library: TubeTK
Copyright 2010 Kitware Inc. 28 Corporate Drive,
Clifton Park, NY, 12065, USA.
All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=========================================================================*/
#include <ios>
#include "tubeCLIFilterWatcher.h"
#include "tubeCLIProgressReporter.h"
#include "tubeMessage.h"
#include "tubeStringUtilities.h"
#include <itkTimeProbesCollectorBase.h>
#include <itkImageFileWriter.h>
#include <itkImageFileReader.h>
#include <metaUtils.h>
// Must include CLP before including tubeCLIHelperFunctions
#include "ConvertImagesToCSVCLP.h"
// Must do a forward declaration of DoIt before including
// tubeCLIHelperFunctions
template< class TPixel, unsigned int VDimension >
int DoIt( int argc, char * argv[] );
// Must follow include of "...CLP.h" and forward declaration of int DoIt( ... ).
#include "tubeCLIHelperFunctions.h"
// Your code should be within the DoIt function...
template< class TPixel, unsigned int VDimension >
int DoIt( int argc, char * argv[] )
{
PARSE_ARGS;
typedef float InputPixelType;
typedef itk::Image< InputPixelType, VDimension > InputImageType;
typedef itk::ImageFileReader< InputImageType > ReaderType;
typename ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName( inputImageFileName );
try
{
reader->Update();
}
catch( itk::ExceptionObject & err )
{
tube::ErrorMessage( "Reading volume: Exception caught: "
+ std::string(err.GetDescription()) );
return EXIT_FAILURE;
}
typename InputImageType::Pointer maskImage = reader->GetOutput();
int numImages = 0;
std::vector< typename InputImageType::Pointer > imageList;
std::vector< std::string > imageFileNameList;
tube::StringToVector< std::string >( inputImageFileNameList,
imageFileNameList );
std::ofstream outFile( outputCSVFileName.c_str() );
for( unsigned int i = 0; i < imageFileNameList.size(); ++i )
{
reader = ReaderType::New();
reader->SetFileName( imageFileNameList[i] );
char filePath[4096];
std::string fileName = imageFileNameList[i];
if( MET_GetFilePath( imageFileNameList[i].c_str(), filePath ) )
{
fileName = &( imageFileNameList[i][ strlen( filePath ) ] );
}
outFile << fileName << ", ";
try
{
reader->Update();
}
catch( itk::ExceptionObject & err )
{
tube::ErrorMessage( "Reading volume: Exception caught: "
+ std::string(err.GetDescription()) );
return EXIT_FAILURE;
}
imageList.push_back( reader->GetOutput() );
++numImages;
}
outFile << "Class" << std::endl;
typedef itk::ImageRegionIterator< InputImageType > IteratorType;
std::vector< IteratorType * > iterList;
for( unsigned int i = 0; i < numImages; ++i )
{
iterList.push_back( new IteratorType( imageList[i],
imageList[i]->GetLargestPossibleRegion() ) );
}
IteratorType maskIter( maskImage, maskImage->GetLargestPossibleRegion() );
while( !maskIter.IsAtEnd() )
{
if( maskIter.Get() != 0 )
{
for( unsigned int i=0; i<numImages; ++i )
{
outFile << iterList[i]->Get() << ", ";
}
outFile << maskIter.Get() << std::endl;
}
for( unsigned int s=0; s<stride && !maskIter.IsAtEnd(); ++s )
{
for( unsigned int i=0; i<numImages; ++i )
{
++(*iterList[i]);
}
++maskIter;
}
}
outFile.close();
return EXIT_SUCCESS;
}
// Main
int main( int argc, char * argv[] )
{
PARSE_ARGS;
// You may need to update this line if, in the project's .xml CLI file,
// you change the variable name for the inputImageFileName.
return tube::ParseArgsAndCallDoIt( inputImageFileName, argc, argv );
}
<commit_msg>COMP: Fixed signed/unsigned warnings<commit_after>/*=========================================================================
Library: TubeTK
Copyright 2010 Kitware Inc. 28 Corporate Drive,
Clifton Park, NY, 12065, USA.
All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=========================================================================*/
#include <ios>
#include "tubeCLIFilterWatcher.h"
#include "tubeCLIProgressReporter.h"
#include "tubeMessage.h"
#include "tubeStringUtilities.h"
#include <itkTimeProbesCollectorBase.h>
#include <itkImageFileWriter.h>
#include <itkImageFileReader.h>
#include <metaUtils.h>
// Must include CLP before including tubeCLIHelperFunctions
#include "ConvertImagesToCSVCLP.h"
// Must do a forward declaration of DoIt before including
// tubeCLIHelperFunctions
template< class TPixel, unsigned int VDimension >
int DoIt( int argc, char * argv[] );
// Must follow include of "...CLP.h" and forward declaration of int DoIt( ... ).
#include "tubeCLIHelperFunctions.h"
// Your code should be within the DoIt function...
template< class TPixel, unsigned int VDimension >
int DoIt( int argc, char * argv[] )
{
PARSE_ARGS;
typedef float InputPixelType;
typedef itk::Image< InputPixelType, VDimension > InputImageType;
typedef itk::ImageFileReader< InputImageType > ReaderType;
typename ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName( inputImageFileName );
try
{
reader->Update();
}
catch( itk::ExceptionObject & err )
{
tube::ErrorMessage( "Reading volume: Exception caught: "
+ std::string(err.GetDescription()) );
return EXIT_FAILURE;
}
typename InputImageType::Pointer maskImage = reader->GetOutput();
unsigned int numImages = 0;
std::vector< typename InputImageType::Pointer > imageList;
std::vector< std::string > imageFileNameList;
tube::StringToVector< std::string >( inputImageFileNameList,
imageFileNameList );
std::ofstream outFile( outputCSVFileName.c_str() );
for( unsigned int i = 0; i < imageFileNameList.size(); ++i )
{
reader = ReaderType::New();
reader->SetFileName( imageFileNameList[i] );
char filePath[4096];
std::string fileName = imageFileNameList[i];
if( MET_GetFilePath( imageFileNameList[i].c_str(), filePath ) )
{
fileName = &( imageFileNameList[i][ strlen( filePath ) ] );
}
outFile << fileName << ", ";
try
{
reader->Update();
}
catch( itk::ExceptionObject & err )
{
tube::ErrorMessage( "Reading volume: Exception caught: "
+ std::string(err.GetDescription()) );
return EXIT_FAILURE;
}
imageList.push_back( reader->GetOutput() );
++numImages;
}
outFile << "Class" << std::endl;
typedef itk::ImageRegionIterator< InputImageType > IteratorType;
std::vector< IteratorType * > iterList;
for( unsigned int i = 0; i < numImages; ++i )
{
iterList.push_back( new IteratorType( imageList[i],
imageList[i]->GetLargestPossibleRegion() ) );
}
IteratorType maskIter( maskImage, maskImage->GetLargestPossibleRegion() );
while( !maskIter.IsAtEnd() )
{
if( maskIter.Get() != 0 )
{
for( unsigned int i=0; i<numImages; ++i )
{
outFile << iterList[i]->Get() << ", ";
}
outFile << maskIter.Get() << std::endl;
}
for( int s=0; s<stride && !maskIter.IsAtEnd(); ++s )
{
for( unsigned int i=0; i<numImages; ++i )
{
++(*iterList[i]);
}
++maskIter;
}
}
outFile.close();
return EXIT_SUCCESS;
}
// Main
int main( int argc, char * argv[] )
{
PARSE_ARGS;
// You may need to update this line if, in the project's .xml CLI file,
// you change the variable name for the inputImageFileName.
return tube::ParseArgsAndCallDoIt( inputImageFileName, argc, argv );
}
<|endoftext|>
|
<commit_before><commit_msg>Fix *_component_getFactory function type<commit_after><|endoftext|>
|
<commit_before>/**
* \file
* \brief SignalAction class header
*
* \author Copyright (C) 2015 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
*
* \par License
* 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/.
*
* \date 2015-04-18
*/
#ifndef INCLUDE_DISTORTOS_SIGNALACTION_HPP_
#define INCLUDE_DISTORTOS_SIGNALACTION_HPP_
#include "distortos/SignalSet.hpp"
namespace distortos
{
class SignalInformation;
/**
* \brief SignalAction class contains information needed to handle signal that was caught
*
* Similar to \a sigaction - http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/signal.h.html
*/
class SignalAction
{
public:
/// handler function
using Handler = void(const SignalInformation&);
/**
* \brief SignalAction's constructor which uses "default" signal handler.
*/
constexpr SignalAction() :
signalMask_{SignalSet::empty},
handler_{}
{
}
/**
* \brief SignalAction's constructor.
*
* \param [in] handler is a reference to handler function (similar to \a sa_sigaction member of \a sigaction)
* \param [in] signalMask is the additional set of signals to be masked during execution of signal-catching function
* (similar to \a sa_mask member of \a sigaction)
*/
constexpr SignalAction(Handler& handler, const SignalSet signalMask) :
signalMask_{signalMask},
handler_{&handler}
{
}
private:
/// additional set of signals to be masked during execution of signal-catching function (similar to \a sa_mask
/// member of \a sigaction)
SignalSet signalMask_;
/// pointer to handler function (similar to \a sa_sigaction member of \a sigaction), nullptr to use default handler
/// (similar to \a SIG_DFL)
Handler* handler_;
};
} // namespace distortos
#endif // INCLUDE_DISTORTOS_SIGNALACTION_HPP_
<commit_msg>SignalAction: add SignalAction::getHandler()<commit_after>/**
* \file
* \brief SignalAction class header
*
* \author Copyright (C) 2015 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
*
* \par License
* 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/.
*
* \date 2015-04-18
*/
#ifndef INCLUDE_DISTORTOS_SIGNALACTION_HPP_
#define INCLUDE_DISTORTOS_SIGNALACTION_HPP_
#include "distortos/SignalSet.hpp"
namespace distortos
{
class SignalInformation;
/**
* \brief SignalAction class contains information needed to handle signal that was caught
*
* Similar to \a sigaction - http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/signal.h.html
*/
class SignalAction
{
public:
/// handler function
using Handler = void(const SignalInformation&);
/**
* \brief SignalAction's constructor which uses "default" signal handler.
*/
constexpr SignalAction() :
signalMask_{SignalSet::empty},
handler_{}
{
}
/**
* \brief SignalAction's constructor.
*
* \param [in] handler is a reference to handler function (similar to \a sa_sigaction member of \a sigaction)
* \param [in] signalMask is the additional set of signals to be masked during execution of signal-catching function
* (similar to \a sa_mask member of \a sigaction)
*/
constexpr SignalAction(Handler& handler, const SignalSet signalMask) :
signalMask_{signalMask},
handler_{&handler}
{
}
/**
* \return pointer to handler function (similar to \a sa_sigaction member of \a sigaction), nullptr if use of
* default handler was configured (similar to \a SIG_DFL)
*/
Handler* getHandler() const
{
return handler_;
}
private:
/// additional set of signals to be masked during execution of signal-catching function (similar to \a sa_mask
/// member of \a sigaction)
SignalSet signalMask_;
/// pointer to handler function (similar to \a sa_sigaction member of \a sigaction), nullptr to use default handler
/// (similar to \a SIG_DFL)
Handler* handler_;
};
} // namespace distortos
#endif // INCLUDE_DISTORTOS_SIGNALACTION_HPP_
<|endoftext|>
|
<commit_before>#pragma once
#include <gunrock/algorithms/algorithms.hxx>
using vertex_t = int;
using edge_t = int;
using weight_t = float;
namespace gunrock {
namespace mst {
template <typename vertex_t>
struct param_t {
// No parameters for this algorithm
};
template <typename vertex_t, typename weight_t>
struct result_t {
weight_t* mst_weight;
result_t(weight_t* _mst_weight) : mst_weight(_mst_weight) {}
};
// <boilerplate>
template <typename graph_t, typename param_type, typename result_type>
struct problem_t : gunrock::problem_t<graph_t> {
param_type param;
result_type result;
problem_t(graph_t& G,
param_type& _param,
result_type& _result,
std::shared_ptr<cuda::multi_context_t> _context)
: gunrock::problem_t<graph_t>(G, _context),
param(_param),
result(_result) {}
using vertex_t = typename graph_t::vertex_type;
using edge_t = typename graph_t::edge_type;
using weight_t = typename graph_t::weight_type;
// </boilerplate>
graph_t g = this->get_graph();
int n_vertices = g.get_number_of_vertices();
thrust::device_vector<vertex_t> roots;
thrust::device_vector<weight_t> min_weights;
thrust::device_vector<int> mst_edges;
thrust::device_vector<int> super_vertices;
thrust::device_vector<int> min_neighbors;
void init() {
auto policy = this->context->get_context(0)->execution_policy();
roots.resize(n_vertices);
min_weights.resize(n_vertices);
min_neighbors.resize(n_vertices);
mst_edges.resize(1);
super_vertices.resize(1);
auto d_mst_weight = thrust::device_pointer_cast(this->result.mst_weight);
thrust::fill(policy, min_weights.begin(), min_weights.end(),
std::numeric_limits<weight_t>::max());
thrust::fill(policy, d_mst_weight, d_mst_weight + 1, 0);
thrust::fill(policy, min_neighbors.begin(), min_neighbors.end(), -1);
thrust::sequence(policy, roots.begin(), roots.end(), 0);
thrust::sequence(policy, super_vertices.begin(), super_vertices.end(), n_vertices);
}
void reset() {
// TODO: reset
return;
}
};
// <boilerplate>
template <typename problem_t>
struct enactor_t : gunrock::enactor_t<problem_t> {
enactor_t(problem_t* _problem,
std::shared_ptr<cuda::multi_context_t> _context)
: gunrock::enactor_t<problem_t>(_problem, _context) {}
using vertex_t = typename problem_t::vertex_t;
using edge_t = typename problem_t::edge_t;
using weight_t = typename problem_t::weight_t;
using frontier_t = typename enactor_t<problem_t>::frontier_t;
// </boilerplate>
// How to initialize the frontier at the beginning of the application.
void prepare_frontier(frontier_t* f,
cuda::multi_context_t& context) override {
// get pointer to the problem
auto P = this->get_problem();
auto n_vertices = P->get_graph().get_number_of_vertices();
// Fill the frontier with a sequence of vertices from 0 -> n_vertices.
f->sequence((vertex_t)0, n_vertices, context.get_context(0)->stream());
}
// One iteration of the application
void loop(cuda::multi_context_t& context) override {
auto E = this->get_enactor();
auto P = this->get_problem();
auto G = P->get_graph();
auto mst_weight = P->result.mst_weight;
auto mst_edges = P->mst_edges.data().get();
auto super_vertices = P->super_vertices.data().get();
auto min_neighbors = P->min_neighbors.data().get();
auto roots = P->roots.data().get();
auto min_weights = P->min_weights.data().get();
auto policy = this->context->get_context(0)->execution_policy();
thrust::fill_n(policy, min_weights, P->n_vertices,
std::numeric_limits<weight_t>::max());
thrust::fill_n(policy, min_neighbors, P->n_vertices, -1);
// Find minimum weight for each vertex
// TODO: update for multi-directional edges?
auto get_min_weights = [min_weights, roots, G] __host__ __device__(
edge_t const& e // id of edge
) -> void {
auto source = G.get_source_vertex(e);
auto neighbor = G.get_destination_vertex(e);
auto weight = G.get_edge_weight(e);
// If they are already part of same super vertex, do not check
if (roots[source] != roots[neighbor]) {
// Store minimum weight
auto old_weight =
math::atomic::min(&(min_weights[roots[source]]), weight);
printf(
"1: source %i roots[source] %i weight %f min weight %f weight < "
"old weight %i\n",
source, roots[source], weight, min_weights[roots[source]],
weight < old_weight);
}
};
// TODO: technically this is non-deterministic between edges that are tied
auto get_min_neighbors =
[G, min_weights, min_neighbors, roots] __host__ __device__(
edge_t const& e // id of edge
) -> void {
auto source = G.get_source_vertex(e);
auto neighbor = G.get_destination_vertex(e);
auto weight = G.get_edge_weight(e);
// Keep neighbor if it is the min
if (weight == min_weights[roots[source]]) {
atomicCAS(&min_neighbors[roots[source]], -1, e);
printf("source %i root %i min_neighbor %i\n", source, roots[source],
min_neighbors[roots[source]]);
}
};
// Add weights to MST
auto add_to_mst = [G, roots, mst_weight, mst_edges, super_vertices,
min_neighbors, min_weights] __host__
__device__(vertex_t const& v) -> void {
if (min_weights[v] != std::numeric_limits<weight_t>::max()) {
auto source = G.get_source_vertex(min_neighbors[v]);
auto dest = G.get_destination_vertex(min_neighbors[v]);
auto weight = min_weights[v];
// TODO: technically there is a race between reads/writes to
// roots[dest]; not allowing duplicate edges would remove this check
// requirement
if (source < dest ||
G.get_destination_vertex(min_neighbors[roots[dest]]) != source) {
printf("v %i\n", source);
printf("u %i\n", dest);
// printf("add mst v %i\n", v);
// printf("add mst u %i\n", u);
// printf("add mst v root %i\n", roots[v]);
// printf("add mst u root %i\n", roots[u]);
// Not sure cycle comparison for inc/dec vs add; using atomic::add for
// now because it is in our math.hxx
math::atomic::add(&mst_weight[0], weight);
printf("weight %f\n", mst_weight[0]);
printf("adding source %i weight %f\n", source, weight);
math::atomic::add(&mst_edges[0], 1);
math::atomic::add(&super_vertices[0], -1);
printf("super vertices %i\n", super_vertices[0]);
atomicExch((&roots[v]), roots[dest]);
return;
}
}
};
// Jump pointers in parallel for
// TODO: technically there will be races between reads/writes to roots
// entries, but this will just impact the number of hops
auto jump_pointers_parallel =
[roots] __host__ __device__(vertex_t const& v) -> void {
vertex_t u = roots[v];
while (roots[u] != u) {
u = roots[u];
}
roots[v] = u;
return;
};
// Execute advance operator to get min weights
auto in_frontier = &(this->frontiers[0]);
auto out_frontier = &(this->frontiers[1]);
operators::parallel_for::execute<operators::parallel_for_each_t::edge>(
G, get_min_weights, context);
frontier_t it = *out_frontier;
// Execute filter operator to get min neighbors
operators::parallel_for::execute<operators::parallel_for_each_t::edge>(
G, get_min_neighbors, context);
// Execute parallel for to add weights to MST
operators::parallel_for::execute<operators::parallel_for_each_t::vertex>(
G, // graph
add_to_mst, // lambda function
context // context
);
// TODO: remove cycles (because we can't check that roots aren't equal when
// adding due to races)
// TODO: exit on error if super_vertices not decremented
// Execute parallel for to jump pointers
operators::parallel_for::execute<operators::parallel_for_each_t::vertex>(
G, // graph
jump_pointers_parallel, // lambda function
context // context
);
}
virtual bool is_converged(cuda::multi_context_t& context) {
//if (this->iteration > 1) {
// return true;
//}
//return false;
auto P = this->get_problem();
return (P->super_vertices[0] == 1);
}
};
template <typename graph_t>
float run(
graph_t& G,
typename graph_t::weight_type* mst_weight, // Output
// Context for application (eg, GPU + CUDA stream it will be
// executed on)
std::shared_ptr<cuda::multi_context_t> context =
std::shared_ptr<cuda::multi_context_t>(new cuda::multi_context_t(0))) {
using vertex_t = typename graph_t::vertex_type;
using weight_t = typename graph_t::weight_type;
// instantiate `param` and `result` templates
using param_type = param_t<vertex_t>;
using result_type = result_t<vertex_t, weight_t>;
// initialize `param` and `result` w/ the appropriate parameters / data
// structures
param_type param;
result_type result(mst_weight);
// <boilerplate> This code probably should be the same across all
// applications, unless maybe you're doing something like multi-gpu /
// concurrent function calls
// instantiate `problem` and `enactor` templates.
using problem_type = problem_t<graph_t, param_type, result_type>;
using enactor_type = enactor_t<problem_type>;
// initialize problem; call `init` and `reset` to prepare data structures
problem_type problem(G, param, result, context);
problem.init();
// problem.reset();
// initialize enactor; call enactor, returning GPU elapsed time
enactor_type enactor(&problem, context);
return enactor.enact();
// </boilerplate>
}
} // namespace mst
} // namespace gunrock<commit_msg>partially resolve races<commit_after>#pragma once
#include <gunrock/algorithms/algorithms.hxx>
using vertex_t = int;
using edge_t = int;
using weight_t = float;
namespace gunrock {
namespace mst {
template <typename vertex_t>
struct param_t {
// No parameters for this algorithm
};
template <typename vertex_t, typename weight_t>
struct result_t {
weight_t* mst_weight;
result_t(weight_t* _mst_weight) : mst_weight(_mst_weight) {}
};
// <boilerplate>
template <typename graph_t, typename param_type, typename result_type>
struct problem_t : gunrock::problem_t<graph_t> {
param_type param;
result_type result;
problem_t(graph_t& G,
param_type& _param,
result_type& _result,
std::shared_ptr<cuda::multi_context_t> _context)
: gunrock::problem_t<graph_t>(G, _context),
param(_param),
result(_result) {}
using vertex_t = typename graph_t::vertex_type;
using edge_t = typename graph_t::edge_type;
using weight_t = typename graph_t::weight_type;
// </boilerplate>
graph_t g = this->get_graph();
int n_vertices = g.get_number_of_vertices();
thrust::device_vector<vertex_t> roots;
thrust::device_vector<vertex_t> new_roots;
thrust::device_vector<weight_t> min_weights;
thrust::device_vector<int> mst_edges;
thrust::device_vector<int> super_vertices;
thrust::device_vector<int> min_neighbors;
void init() {
auto policy = this->context->get_context(0)->execution_policy();
roots.resize(n_vertices);
new_roots.resize(n_vertices);
min_weights.resize(n_vertices);
min_neighbors.resize(n_vertices);
mst_edges.resize(1);
super_vertices.resize(1);
auto d_mst_weight = thrust::device_pointer_cast(this->result.mst_weight);
thrust::fill(policy, min_weights.begin(), min_weights.end(),
std::numeric_limits<weight_t>::max());
thrust::fill(policy, d_mst_weight, d_mst_weight + 1, 0);
thrust::fill(policy, min_neighbors.begin(), min_neighbors.end(), -1);
thrust::sequence(policy, roots.begin(), roots.end(), 0);
thrust::sequence(policy, new_roots.begin(), new_roots.end(), 0);
thrust::sequence(policy, super_vertices.begin(), super_vertices.end(),
n_vertices);
}
void reset() {
// TODO: reset
return;
}
};
// <boilerplate>
template <typename problem_t>
struct enactor_t : gunrock::enactor_t<problem_t> {
enactor_t(problem_t* _problem,
std::shared_ptr<cuda::multi_context_t> _context)
: gunrock::enactor_t<problem_t>(_problem, _context) {}
using vertex_t = typename problem_t::vertex_t;
using edge_t = typename problem_t::edge_t;
using weight_t = typename problem_t::weight_t;
using frontier_t = typename enactor_t<problem_t>::frontier_t;
// </boilerplate>
// How to initialize the frontier at the beginning of the application.
void prepare_frontier(frontier_t* f,
cuda::multi_context_t& context) override {
// get pointer to the problem
auto P = this->get_problem();
auto n_vertices = P->get_graph().get_number_of_vertices();
// Fill the frontier with a sequence of vertices from 0 -> n_vertices.
f->sequence((vertex_t)0, n_vertices, context.get_context(0)->stream());
}
// One iteration of the application
void loop(cuda::multi_context_t& context) override {
auto E = this->get_enactor();
auto P = this->get_problem();
auto G = P->get_graph();
auto mst_weight = P->result.mst_weight;
auto mst_edges = P->mst_edges.data().get();
auto super_vertices = P->super_vertices.data().get();
auto min_neighbors = P->min_neighbors.data().get();
auto roots = P->roots.data().get();
auto new_roots = P->new_roots.data().get();
auto min_weights = P->min_weights.data().get();
auto policy = this->context->get_context(0)->execution_policy();
thrust::fill_n(policy, min_weights, P->n_vertices,
std::numeric_limits<weight_t>::max());
thrust::fill_n(policy, min_neighbors, P->n_vertices, -1);
// Find minimum weight for each vertex
// TODO: update for multi-directional edges?
auto get_min_weights = [min_weights, roots, G] __host__ __device__(
edge_t const& e // id of edge
) -> void {
auto source = G.get_source_vertex(e);
auto neighbor = G.get_destination_vertex(e);
auto weight = G.get_edge_weight(e);
// If they are already part of same super vertex, do not check
if (roots[source] != roots[neighbor]) {
// Store minimum weight
auto old_weight =
math::atomic::min(&(min_weights[roots[source]]), weight);
printf(
"1: source %i roots[source] %i weight %f min weight %f weight < "
"old weight %i\n",
source, roots[source], weight, min_weights[roots[source]],
weight < old_weight);
}
};
// TODO: technically this is non-deterministic between edges that are tied
auto get_min_neighbors =
[G, min_weights, min_neighbors, roots] __host__ __device__(
edge_t const& e // id of edge
) -> void {
auto source = G.get_source_vertex(e);
auto neighbor = G.get_destination_vertex(e);
auto weight = G.get_edge_weight(e);
// Keep neighbor if it is the min
if (weight == min_weights[roots[source]]) {
atomicCAS(&min_neighbors[roots[source]], -1, e);
printf("source %i root %i min_neighbor %i\n", source, roots[source],
min_neighbors[roots[source]]);
}
};
// Add weights to MST
auto add_to_mst = [G, roots, mst_weight, mst_edges, super_vertices,
min_neighbors, min_weights, new_roots] __host__
__device__(vertex_t const& v) -> void {
if (min_weights[v] != std::numeric_limits<weight_t>::max()) {
auto source = G.get_source_vertex(min_neighbors[v]);
auto dest = G.get_destination_vertex(min_neighbors[v]);
auto weight = min_weights[v];
// TODO: technically there is a race between reads/writes to
// roots[dest];
if (source < dest ||
G.get_destination_vertex(min_neighbors[roots[dest]]) != source ||
G.get_source_vertex(min_neighbors[roots[dest]]) != dest) {
printf("v %i\n", source);
printf("u %i\n", dest);
// printf("add mst v %i\n", v);
// printf("add mst u %i\n", u);
// printf("add mst v root %i\n", roots[v]);
// printf("add mst u root %i\n", roots[u]);
// Not sure cycle comparison for inc/dec vs add; using atomic::add for
// now because it is in our math.hxx
math::atomic::add(&mst_weight[0], weight);
printf("adding source %i dest %i weight %f\n", source, dest, weight);
printf("mst weight %f\n", mst_weight[0]);
math::atomic::add(&mst_edges[0], 1);
math::atomic::add(&super_vertices[0], -1);
printf("super vertices %i\n", super_vertices[0]);
atomicExch((&new_roots[v]), new_roots[dest]);
return;
}
}
};
// Jump pointers in parallel for
// TODO: technically there will be races between reads/writes to roots
// entries, but this will just impact the number of hops
// read and write from different copies to resolve
auto jump_pointers_parallel =
[roots, new_roots] __host__ __device__(vertex_t const& v) -> void {
vertex_t u = roots[v];
while (roots[u] != u) {
u = roots[u];
}
new_roots[v] = u;
return;
};
// Execute advance operator to get min weights
auto in_frontier = &(this->frontiers[0]);
auto out_frontier = &(this->frontiers[1]);
operators::parallel_for::execute<operators::parallel_for_each_t::edge>(
G, get_min_weights, context);
frontier_t it = *out_frontier;
// Execute filter operator to get min neighbors
operators::parallel_for::execute<operators::parallel_for_each_t::edge>(
G, get_min_neighbors, context);
// Execute parallel for to add weights to MST
operators::parallel_for::execute<operators::parallel_for_each_t::vertex>(
G, // graph
add_to_mst, // lambda function
context // context
);
// TODO: remove cycles (because we can't check that roots aren't equal when
// adding due to races)
// TODO: exit on error if super_vertices not decremented
// Execute parallel for to jump pointers
thrust::copy_n(policy, new_roots, P->n_vertices, roots);
operators::parallel_for::execute<operators::parallel_for_each_t::vertex>(
G, // graph
jump_pointers_parallel, // lambda function
context // context
);
thrust::copy_n(policy, new_roots, P->n_vertices, roots);
}
virtual bool is_converged(cuda::multi_context_t& context) {
if (this->iteration > 1) {
return true;
}
return false;
// auto P = this->get_problem();
// return (P->super_vertices[0] == 1);
}
};
template <typename graph_t>
float run(
graph_t& G,
typename graph_t::weight_type* mst_weight, // Output
// Context for application (eg, GPU + CUDA stream it will be
// executed on)
std::shared_ptr<cuda::multi_context_t> context =
std::shared_ptr<cuda::multi_context_t>(new cuda::multi_context_t(0))) {
using vertex_t = typename graph_t::vertex_type;
using weight_t = typename graph_t::weight_type;
// instantiate `param` and `result` templates
using param_type = param_t<vertex_t>;
using result_type = result_t<vertex_t, weight_t>;
// initialize `param` and `result` w/ the appropriate parameters / data
// structures
param_type param;
result_type result(mst_weight);
// <boilerplate> This code probably should be the same across all
// applications, unless maybe you're doing something like multi-gpu /
// concurrent function calls
// instantiate `problem` and `enactor` templates.
using problem_type = problem_t<graph_t, param_type, result_type>;
using enactor_type = enactor_t<problem_type>;
// initialize problem; call `init` and `reset` to prepare data structures
problem_type problem(G, param, result, context);
problem.init();
// problem.reset();
// initialize enactor; call enactor, returning GPU elapsed time
enactor_type enactor(&problem, context);
return enactor.enact();
// </boilerplate>
}
} // namespace mst
} // namespace gunrock<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: ResultSetMetaData.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: ihi $ $Date: 2007-11-27 12:04:25 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _CONNECTIVITY_JAVA_SQL_RESULTSETMETADATA_HXX_
#define _CONNECTIVITY_JAVA_SQL_RESULTSETMETADATA_HXX_
#ifndef _CONNECTIVITY_JAVA_LANG_OBJECT_HXX_
#include "java/lang/Object.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBC_XRESULTSETMETADATA_HPP_
#include <com/sun/star/sdbc/XResultSetMetaData.hpp>
#endif
#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif
#include "java/sql/ConnectionLog.hxx"
namespace connectivity
{
//**************************************************************
//************ Class: java.sql.ResultSetMetaData
//**************************************************************
class java_sql_Connection;
class java_sql_ResultSetMetaData : public ::cppu::WeakImplHelper1< ::com::sun::star::sdbc::XResultSetMetaData>,
public java_lang_Object
{
protected:
java::sql::ConnectionLog m_aLogger;
java_sql_Connection* m_pConnection;
// statische Daten fuer die Klasse
static jclass theClass;
// der Destruktor um den Object-Counter zu aktualisieren
static void saveClassRef( jclass pClass );
virtual ~java_sql_ResultSetMetaData();
public:
static jclass getMyClass();
// ein Konstruktor, der fuer das Returnen des Objektes benoetigt wird:
java_sql_ResultSetMetaData( JNIEnv * pEnv, jobject myObj, const java::sql::ConnectionLog& _rResultSetLogger, java_sql_Connection& _rCon );
virtual sal_Int32 SAL_CALL getColumnCount( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL isAutoIncrement( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL isCaseSensitive( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL isSearchable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL isCurrency( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL isNullable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL isSigned( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL getColumnDisplaySize( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getColumnLabel( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getColumnName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getSchemaName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL getPrecision( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL getScale( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getTableName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getCatalogName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL getColumnType( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getColumnTypeName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL isReadOnly( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL isWritable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL isDefinitelyWritable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getColumnServiceName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
};
}
#endif // _CONNECTIVITY_JAVA_SQL_RESULTSETMETADATA_HXX_
<commit_msg>INTEGRATION: CWS changefileheader (1.5.62); FILE MERGED 2008/04/01 15:09:15 thb 1.5.62.3: #i85898# Stripping all external header guards 2008/04/01 10:53:37 thb 1.5.62.2: #i85898# Stripping all external header guards 2008/03/28 15:24:30 rt 1.5.62.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: ResultSetMetaData.hxx,v $
* $Revision: 1.6 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _CONNECTIVITY_JAVA_SQL_RESULTSETMETADATA_HXX_
#define _CONNECTIVITY_JAVA_SQL_RESULTSETMETADATA_HXX_
#include "java/lang/Object.hxx"
#include <com/sun/star/sdbc/XResultSetMetaData.hpp>
#include <cppuhelper/implbase1.hxx>
#include "java/sql/ConnectionLog.hxx"
namespace connectivity
{
//**************************************************************
//************ Class: java.sql.ResultSetMetaData
//**************************************************************
class java_sql_Connection;
class java_sql_ResultSetMetaData : public ::cppu::WeakImplHelper1< ::com::sun::star::sdbc::XResultSetMetaData>,
public java_lang_Object
{
protected:
java::sql::ConnectionLog m_aLogger;
java_sql_Connection* m_pConnection;
// statische Daten fuer die Klasse
static jclass theClass;
// der Destruktor um den Object-Counter zu aktualisieren
static void saveClassRef( jclass pClass );
virtual ~java_sql_ResultSetMetaData();
public:
static jclass getMyClass();
// ein Konstruktor, der fuer das Returnen des Objektes benoetigt wird:
java_sql_ResultSetMetaData( JNIEnv * pEnv, jobject myObj, const java::sql::ConnectionLog& _rResultSetLogger, java_sql_Connection& _rCon );
virtual sal_Int32 SAL_CALL getColumnCount( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL isAutoIncrement( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL isCaseSensitive( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL isSearchable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL isCurrency( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL isNullable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL isSigned( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL getColumnDisplaySize( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getColumnLabel( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getColumnName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getSchemaName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL getPrecision( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL getScale( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getTableName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getCatalogName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL getColumnType( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getColumnTypeName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL isReadOnly( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL isWritable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL isDefinitelyWritable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getColumnServiceName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
};
}
#endif // _CONNECTIVITY_JAVA_SQL_RESULTSETMETADATA_HXX_
<|endoftext|>
|
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2011 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
*
*****************************************************************************/
#ifndef MAPNIK_WKT_GRAMMAR_HPP
#define MAPNIK_WKT_GRAMMAR_HPP
#include <boost/assert.hpp>
#include <boost/ptr_container/ptr_vector.hpp>
// spirit::qi
#include <boost/spirit/include/qi.hpp>
// spirit::phoenix
#include <boost/spirit/include/phoenix_function.hpp>
#include <boost/spirit/include/phoenix_core.hpp>
#include <boost/spirit/include/phoenix_operator.hpp>
#include <boost/spirit/include/phoenix_fusion.hpp>
#include <boost/spirit/home/phoenix/object/new.hpp>
#include <boost/spirit/include/phoenix_stl.hpp>
// mapnik
#include <mapnik/geometry.hpp>
namespace mapnik { namespace wkt {
using namespace boost::spirit;
using namespace boost::fusion;
using namespace boost::phoenix;
struct push_vertex
{
template <typename T0,typename T1, typename T2, typename T3>
struct result
{
typedef void type;
};
template <typename T0,typename T1, typename T2, typename T3>
void operator() (T0 c, T1 path, T2 x, T3 y) const
{
BOOST_ASSERT( path!=0 );
path->push_vertex(x,y,c);
}
};
struct cleanup
{
template <typename T0>
struct result
{
typedef void type;
};
template <typename T0>
void operator() (T0 & path) const
{
if (path) delete path,path=0;
}
};
template <typename Iterator>
struct wkt_grammar : qi::grammar<Iterator, geometry_type*(), ascii::space_type>
{
wkt_grammar()
: wkt_grammar::base_type(start)
{
using qi::no_case;
start %= point | linestring | polygon | multipoint | multilinestring | multipolygon | eps[cleanup_(_val)][_pass = false];
// <point tagged text> ::= point <point text>
point = no_case[lit("POINT")] [ _val = new_<geometry_type>(Point) ]
>> (empty_set | lit('(') >> coord(SEG_MOVETO,_val) >> lit(')'));
// <linestring tagged text> ::= linestring <linestring text>
linestring = no_case[lit("LINESTRING")] [ _val = new_<geometry_type>(LineString) ] >> (empty_set | points(_val));
// <polygon tagged text> ::= polygon <polygon text>
polygon = no_case[lit("POLYGON")] [ _val = new_<geometry_type>(Polygon) ] >>
(empty_set | lit('(') >> points(_val) % lit(',') >> lit(')'));
// multi point
multipoint = no_case[lit("MULTIPOINT")] [ _val = new_<geometry_type>(MultiPoint) ]
>> (empty_set | lit('(') >> coord(SEG_MOVETO,_val) % lit(',') >> ')');
// multi linestring
multilinestring = no_case[lit("MULTILINESTRING")] [ _val = new_<geometry_type>(MultiLineString) ]>>
(empty_set | lit('(') >> points(_val) % lit(',') >> ')');
// multi polygon
multipolygon = no_case[lit("MULTIPOLYGON")] [ _val = new_<geometry_type>(MultiPolygon)] >>
(empty_set | lit('(') >> (lit('(') >>
points(_val) % ',' >> ')') % ',' >> ')');
// points
points = lit('(')[_a = SEG_MOVETO] >> coord (_a,_r1) % lit(',') [_a = SEG_LINETO] >> ')';
coord = (double_ >> double_) [push_vertex_(_r1,_r2,_1,_2)];
// <empty set>
empty_set = no_case[lit("EMPTY")];
}
qi::rule<Iterator,geometry_type*(),ascii::space_type> start;
qi::rule<Iterator,geometry_type*(),ascii::space_type> point;
qi::rule<Iterator,geometry_type*(),ascii::space_type> multipoint;
qi::rule<Iterator,geometry_type*(),ascii::space_type> linestring;
qi::rule<Iterator,geometry_type*(),ascii::space_type> multilinestring;
qi::rule<Iterator,geometry_type*(),ascii::space_type> polygon;
qi::rule<Iterator,geometry_type*(),ascii::space_type> multipolygon;
qi::rule<Iterator,void(CommandType,geometry_type*),ascii::space_type> coord;
qi::rule<Iterator,qi::locals<CommandType>,void(geometry_type*),ascii::space_type> points;
qi::rule<Iterator,ascii::space_type> empty_set;
boost::phoenix::function<push_vertex> push_vertex_;
boost::phoenix::function<cleanup> cleanup_;
};
template <typename Iterator>
struct wkt_collection_grammar : qi::grammar<Iterator, boost::ptr_vector<mapnik::geometry_type>(), ascii::space_type>
{
wkt_collection_grammar()
: wkt_collection_grammar::base_type(start)
{
using qi::no_case;
using boost::phoenix::push_back;
start = wkt [push_back(_val,_1)] | no_case[lit("GEOMETRYCOLLECTION")]
>> (lit("(") >> *wkt[push_back(_val,_1)] % lit(",") >> lit(")"));
}
qi::rule<Iterator,boost::ptr_vector<mapnik::geometry_type>(),ascii::space_type> start;
wkt_grammar<Iterator> wkt;
};
}}
#endif // MAPNIK_WKT_GRAMMAR_HPP
<commit_msg>+ qualify boost::spirit::qi placeholders to avoid ambiguity<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2011 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
*
*****************************************************************************/
#ifndef MAPNIK_WKT_GRAMMAR_HPP
#define MAPNIK_WKT_GRAMMAR_HPP
#include <boost/assert.hpp>
#include <boost/ptr_container/ptr_vector.hpp>
// spirit::qi
#include <boost/spirit/include/qi.hpp>
// spirit::phoenix
#include <boost/spirit/include/phoenix_function.hpp>
#include <boost/spirit/include/phoenix_core.hpp>
#include <boost/spirit/include/phoenix_operator.hpp>
#include <boost/spirit/include/phoenix_fusion.hpp>
#include <boost/spirit/home/phoenix/object/new.hpp>
#include <boost/spirit/include/phoenix_stl.hpp>
// mapnik
#include <mapnik/geometry.hpp>
namespace mapnik { namespace wkt {
using namespace boost::spirit;
using namespace boost::fusion;
using namespace boost::phoenix;
struct push_vertex
{
template <typename T0,typename T1, typename T2, typename T3>
struct result
{
typedef void type;
};
template <typename T0,typename T1, typename T2, typename T3>
void operator() (T0 c, T1 path, T2 x, T3 y) const
{
BOOST_ASSERT( path!=0 );
path->push_vertex(x,y,c);
}
};
struct cleanup
{
template <typename T0>
struct result
{
typedef void type;
};
template <typename T0>
void operator() (T0 & path) const
{
if (path) delete path,path=0;
}
};
template <typename Iterator>
struct wkt_grammar : qi::grammar<Iterator, geometry_type*(), ascii::space_type>
{
wkt_grammar()
: wkt_grammar::base_type(start)
{
using qi::_1;
using qi::_2;
using qi::_val;
using qi::no_case;
start %= point | linestring | polygon | multipoint | multilinestring | multipolygon | eps[cleanup_(_val)][_pass = false];
// <point tagged text> ::= point <point text>
point = no_case[lit("POINT")] [ _val = new_<geometry_type>(Point) ]
>> (empty_set | lit('(') >> coord(SEG_MOVETO,_val) >> lit(')'));
// <linestring tagged text> ::= linestring <linestring text>
linestring = no_case[lit("LINESTRING")] [ _val = new_<geometry_type>(LineString) ] >> (empty_set | points(_val));
// <polygon tagged text> ::= polygon <polygon text>
polygon = no_case[lit("POLYGON")] [ _val = new_<geometry_type>(Polygon) ] >>
(empty_set | lit('(') >> points(_val) % lit(',') >> lit(')'));
// multi point
multipoint = no_case[lit("MULTIPOINT")] [ _val = new_<geometry_type>(MultiPoint) ]
>> (empty_set | lit('(') >> coord(SEG_MOVETO,_val) % lit(',') >> ')');
// multi linestring
multilinestring = no_case[lit("MULTILINESTRING")] [ _val = new_<geometry_type>(MultiLineString) ]>>
(empty_set | lit('(') >> points(_val) % lit(',') >> ')');
// multi polygon
multipolygon = no_case[lit("MULTIPOLYGON")] [ _val = new_<geometry_type>(MultiPolygon)] >>
(empty_set | lit('(') >> (lit('(') >>
points(_val) % ',' >> ')') % ',' >> ')');
// points
points = lit('(')[_a = SEG_MOVETO] >> coord (_a,_r1) % lit(',') [_a = SEG_LINETO] >> ')';
coord = (double_ >> double_) [push_vertex_(_r1,_r2,_1,_2)];
// <empty set>
empty_set = no_case[lit("EMPTY")];
}
qi::rule<Iterator,geometry_type*(),ascii::space_type> start;
qi::rule<Iterator,geometry_type*(),ascii::space_type> point;
qi::rule<Iterator,geometry_type*(),ascii::space_type> multipoint;
qi::rule<Iterator,geometry_type*(),ascii::space_type> linestring;
qi::rule<Iterator,geometry_type*(),ascii::space_type> multilinestring;
qi::rule<Iterator,geometry_type*(),ascii::space_type> polygon;
qi::rule<Iterator,geometry_type*(),ascii::space_type> multipolygon;
qi::rule<Iterator,void(CommandType,geometry_type*),ascii::space_type> coord;
qi::rule<Iterator,qi::locals<CommandType>,void(geometry_type*),ascii::space_type> points;
qi::rule<Iterator,ascii::space_type> empty_set;
boost::phoenix::function<push_vertex> push_vertex_;
boost::phoenix::function<cleanup> cleanup_;
};
template <typename Iterator>
struct wkt_collection_grammar : qi::grammar<Iterator, boost::ptr_vector<mapnik::geometry_type>(), ascii::space_type>
{
wkt_collection_grammar()
: wkt_collection_grammar::base_type(start)
{
using qi::_1;
using qi::_val;
using qi::no_case;
using boost::phoenix::push_back;
start = wkt [push_back(_val,_1)] | no_case[lit("GEOMETRYCOLLECTION")]
>> (lit("(") >> *wkt[push_back(_val,_1)] % lit(",") >> lit(")"));
}
qi::rule<Iterator,boost::ptr_vector<mapnik::geometry_type>(),ascii::space_type> start;
wkt_grammar<Iterator> wkt;
};
}}
#endif // MAPNIK_WKT_GRAMMAR_HPP
<|endoftext|>
|
<commit_before>#ifndef INC_METTLE_DRIVER_LOG_TERM_HPP
#define INC_METTLE_DRIVER_LOG_TERM_HPP
#include <cstdint>
#include <sstream>
#include <string>
#include <type_traits>
namespace term {
namespace detail {
inline int stream_flag() {
static int flag = std::ios_base::xalloc();
return flag;
}
template<typename T, typename ...>
struct are_same : std::true_type {};
template<typename T, typename First, typename ...Rest>
struct are_same<T, First, Rest...> : std::integral_constant<
bool, std::is_same<T, First>::value && are_same<T, Rest...>::value
> {};
}
inline void enable(std::ios_base &ios, bool enabled) {
ios.iword(detail::stream_flag()) = enabled;
}
enum class sgr {
reset = 0,
bold = 1,
faint = 2,
italic = 3,
underline = 4,
blink = 5,
blink_fast = 6,
inverse = 7,
conceal = 8,
crossed_out = 9
};
enum class color {
black = 0,
red = 1,
green = 2,
yellow = 3,
blue = 4,
magenta = 5,
cyan = 6,
white = 7,
normal = 9
};
inline sgr fg(color c) {
return static_cast<sgr>(30 + static_cast<std::size_t>(c));
}
inline sgr bg(color c) {
return static_cast<sgr>(40 + static_cast<std::size_t>(c));
}
class format {
friend std::ostream & operator <<(std::ostream &, const format &);
public:
template<typename ...Args>
explicit format(Args &&...args) {
static_assert(sizeof...(Args) > 0,
"term::format must have at least one argument");
static_assert(detail::are_same<sgr, Args...>::value,
"term::format's arguments must be of type term::sgr");
int values[] = {static_cast<int>(std::forward<Args>(args))...};
std::ostringstream ss;
ss << "\033[" << values[0];
for(std::size_t i = 1; i != sizeof...(Args); i++)
ss << ";" << values[i];
ss << "m";
string_ = ss.str();
}
private:
std::string string_;
};
inline format reset() {
return format(sgr::reset);
}
inline std::ostream & operator <<(std::ostream &o, const format &fmt) {
if(o.iword(detail::stream_flag()))
return o << fmt.string_;
return o;
}
} // namespace term
#endif
<commit_msg>Support colors under Windows terminals<commit_after>#ifndef INC_METTLE_DRIVER_LOG_TERM_HPP
#define INC_METTLE_DRIVER_LOG_TERM_HPP
#include <cstdint>
#include <sstream>
#include <string>
#include <type_traits>
#ifdef _WIN32
# include <cassert>
# include <vector>
# include <windows.h>
#endif
namespace term {
namespace detail {
inline int enabled_flag() {
static int flag = std::ios_base::xalloc();
return flag;
}
template<typename T, typename ...>
struct are_same : std::true_type {};
template<typename T, typename First, typename ...Rest>
struct are_same<T, First, Rest...> : std::integral_constant<
bool, std::is_same<T, First>::value && are_same<T, Rest...>::value
> {};
}
enum class sgr {
reset = 0,
bold = 1,
faint = 2,
italic = 3,
underline = 4,
blink = 5,
blink_fast = 6,
inverse = 7,
conceal = 8,
crossed_out = 9
};
enum class color {
black = 0,
red = 1,
green = 2,
yellow = 3,
blue = 4,
magenta = 5,
cyan = 6,
white = 7,
normal = 9
};
inline sgr fg(color c) {
return static_cast<sgr>(30 + static_cast<std::size_t>(c));
}
inline sgr bg(color c) {
return static_cast<sgr>(40 + static_cast<std::size_t>(c));
}
#ifndef _WIN32
inline void enable(std::ios_base &ios, bool enabled) {
ios.iword(detail::enabled_flag()) = enabled;
}
class format {
friend std::ostream & operator <<(std::ostream &, const format &);
public:
template<typename ...Args>
explicit format(Args &&...args) {
static_assert(sizeof...(Args) > 0,
"term::format must have at least one argument");
static_assert(detail::are_same<sgr, Args...>::value,
"term::format's arguments must be of type term::sgr");
int values[] = {static_cast<int>(std::forward<Args>(args))...};
std::ostringstream ss;
ss << "\033[" << values[0];
for(std::size_t i = 1; i != sizeof...(Args); i++)
ss << ";" << values[i];
ss << "m";
string_ = ss.str();
}
private:
void do_format(std::ostream &ios) const {
ios << string_;
}
std::string string_;
};
#else
namespace detail {
inline int console_flag() {
static int flag = std::ios_base::xalloc();
return flag;
}
inline int current_attrs(std::ios_base &ios) {
CONSOLE_SCREEN_BUFFER_INFO info;
GetConsoleScreenBufferInfo(ios.pword(detail::console_flag()), &info);
return info.wAttributes;
}
inline int default_attrs(std::ios_base &ios) {
return ios.iword(detail::console_flag());
}
inline int default_fg(std::ios_base &ios) {
return ios.iword(detail::console_flag()) & 0x0f;
}
inline int default_bg(std::ios_base &ios) {
return ios.iword(detail::console_flag()) & 0xf0;
}
inline int ansi_to_win_fg(int val) {
switch(val) {
case 30: return 0;
case 31: return FOREGROUND_RED;
case 32: return FOREGROUND_GREEN;
case 33: return FOREGROUND_RED | FOREGROUND_GREEN;
case 34: return FOREGROUND_BLUE;
case 35: return FOREGROUND_RED | FOREGROUND_BLUE;
case 36: return FOREGROUND_GREEN | FOREGROUND_BLUE;
case 37: return FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE;
default: assert(false && "disallowed color value");
}
}
inline int ansi_to_win_bg(int val) {
switch(val) {
case 40: return 0;
case 41: return BACKGROUND_RED;
case 42: return BACKGROUND_GREEN;
case 43: return BACKGROUND_RED | BACKGROUND_GREEN;
case 44: return BACKGROUND_BLUE;
case 45: return BACKGROUND_RED | BACKGROUND_BLUE;
case 46: return BACKGROUND_GREEN | BACKGROUND_BLUE;
case 47: return BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_BLUE;
default: assert(false && "disallowed color value");
}
}
}
inline void enable(std::ios_base &ios, bool enabled) {
// XXX: Make sure we're actually talking on CONOUT$.
HANDLE handle = CreateFileA(
"CONOUT$", GENERIC_READ | GENERIC_WRITE, FILE_SHARE_WRITE, nullptr,
OPEN_EXISTING, 0, nullptr
);
CONSOLE_SCREEN_BUFFER_INFO info;
GetConsoleScreenBufferInfo(handle, &info);
int console_flag = detail::console_flag();
ios.iword(console_flag) = info.wAttributes;
ios.pword(console_flag) = handle;
ios.register_callback([](std::ios_base::event type, std::ios_base &ios,
int flag) {
if(type == std::ios_base::erase_event)
CloseHandle(ios.pword(flag));
}, console_flag);
ios.iword(detail::enabled_flag()) = enabled;
}
class format {
friend std::ostream & operator <<(std::ostream &, const format &);
public:
template<typename ...Args>
explicit format(Args &&...args) {
static_assert(sizeof...(Args) > 0,
"term::format must have at least one argument");
static_assert(detail::are_same<sgr, Args...>::value,
"term::format's arguments must be of type term::sgr");
values_ = {std::forward<Args>(args)...};
}
private:
void do_format(std::ostream &o) const {
WORD value = detail::current_attrs(o);
for(auto i : values_) {
if(i == sgr::reset) {
value = detail::default_attrs(o);
}
else if(i == sgr::bold) {
value |= 0x08;
}
else {
int val = static_cast<int>(i);
if(val >= 30 && val < 38) { // Foreground
value &= 0xf8;
value |= detail::ansi_to_win_fg(val);
}
else if(val == 39) { // Default foreground
value &= 0xf8;
value |= detail::default_fg(o);
}
else if(val >= 40 && val < 48) { // Background
value &= 0x8f;
value |= detail::ansi_to_win_bg(val);
}
else if(val == 49) { // Default background
value &= detail::default_fg(o);
}
}
}
SetConsoleTextAttribute(o.pword(detail::console_flag()), value);
}
std::vector<sgr> values_;
};
#endif
inline format reset() {
return format(sgr::reset);
}
inline std::ostream & operator <<(std::ostream &o, const format &fmt) {
if(o.iword(detail::enabled_flag()))
fmt.do_format(o);
return o;
}
} // namespace term
#endif
<|endoftext|>
|
<commit_before>#pragma once
#include "ImplicitParam.h"
#include "GenerationParams.h"
#include "Traits.h"
#include "rapidcheck/Generator.h"
template<typename T>
void doShow(const T &value, std::ostream &os)
{
using namespace rc;
show(value, os);
}
namespace rc {
namespace detail {
template<typename T>
T RoseNode::pick(gen::GeneratorUP<T> &&generator)
{
auto i = m_nextChild;
if (m_nextChild >= m_children.size())
m_children.emplace_back(this);
m_nextChild++;
auto &child = m_children[i];
// TODO we should probably not set this every time
child.setGenerator(std::move(generator));
ImplicitParam<ShrinkMode> shrinkMode;
if (*shrinkMode && (i == m_shrinkChild)) {
bool didShrink;
T value(child.nextShrink<T>(didShrink));
if (!didShrink)
m_shrinkChild++;
return std::move(value);
} else {
return child.currentValue<T>();
}
}
template<typename T>
void RoseNode::setGenerator(gen::GeneratorUP<T> &&generator)
{ m_canonicalGenerator = std::move(generator); }
template<typename T>
T RoseNode::currentValue()
{
ImplicitParam<ShrinkMode> shrinkMode;
shrinkMode.let(false);
return generate<T>();
}
template<typename T>
T RoseNode::nextShrink(bool &didShrink)
{
ImplicitParam<param::NoShrink> noShrink;
if (*noShrink) {
didShrink = false;
return currentValue<T>();
} else {
return nextShrink<T>(didShrink, IsCopyConstructible<T>());
}
}
// For copy-constructible types
template<typename T>
T RoseNode::nextShrink(bool &didShrink, std::true_type)
{
if (!m_shrinkIterator) {
// If we don't have a shrink iterator, shrink the children first.
T value(nextShrinkChildren<T>(didShrink));
// If any child did shrink, then we shouldn't shrink ourselves just yet.
if (didShrink)
return std::move(value);
// Otherwise, we should make a shrink iterator
// The already generated value is a last restort, set as accepted.
m_acceptedGenerator = gen::GeneratorUP<T>(new gen::Constant<T>(value));
// Always use the canonical generator to make a shrink iterator
auto typedCanonical = generatorCast<T>(m_canonicalGenerator.get());
m_shrinkIterator = shrink::UntypedIteratorUP(
typedCanonical->shrink(std::move(value)));
// Since the value of every child is now fixed, the number of
// children won't change so we can get rid of any unused ones.
m_children.resize(m_nextChild);
}
auto typedIterator = iteratorCast<T>(m_shrinkIterator);
if (typedIterator->hasNext()) {
// Current iterator still has more shrinks, use that.
didShrink = true;
auto gen = new gen::Constant<T>(typedIterator->next());
m_currentGenerator = gen::GeneratorUP<T>(gen);
return gen->generate();
} else {
// Exhausted
didShrink = false;
// Replace with shrink::nothing since that is likely smaller than the
// existing iterator.
m_shrinkIterator = shrink::nothing<T>();
m_currentGenerator = nullptr;
return currentValue<T>();
}
}
// For non-copy-constructible types.
template<typename T>
T RoseNode::nextShrink(bool &didShrink, std::false_type)
{
// Only shrink children, cannot explicitly shrink non-copy-constructible
// types.
return nextShrinkChildren<T>(didShrink);
}
// Returns the next shrink by shrinking the children or the currently accepted
// if there are no more possible shrinks of the children. `didShrink` is set to
// true if any of them were shrunk.
template<typename T>
T RoseNode::nextShrinkChildren(bool &didShrink)
{
ImplicitParam<ShrinkMode> shrinkMode;
shrinkMode.let(true);
T value(generate<T>());
didShrink = m_shrinkChild < m_nextChild;
return std::move(value);
}
template<typename T>
T RoseNode::generate()
{
ImplicitParam<param::CurrentNode> currentNode;
currentNode.let(this);
m_nextChild = 0;
return generatorCast<T>(currentGenerator())->generate();
}
template<typename T>
gen::Generator<T> *RoseNode::generatorCast(gen::UntypedGenerator *gen)
{
gen::Generator<T> *typed = dynamic_cast<gen::Generator<T> *>(gen);
if (typed == nullptr)
throw UnexpectedType(typeid(T), gen->generatedTypeInfo());
return typed;
}
template<typename T>
shrink::Iterator<T> *RoseNode::iteratorCast(
const shrink::UntypedIteratorUP &it)
{
shrink::Iterator<T> *typed = dynamic_cast<shrink::Iterator<T> *>(it.get());
// TODO use typeid of ShrunkTypes, not iterators themselves
if (typed == nullptr)
throw UnexpectedType(typeid(shrink::Iterator<T>), typeid(it));
return typed;
}
template<typename T>
template<typename Gen>
Rose<T>::Rose(Gen generator, const TestCase &testCase)
: Rose(gen::GeneratorUP<T>(new Gen(std::move(generator))), testCase)
{
static_assert(
std::is_same<T, GeneratedT<Gen>>::value,
"Generated type of generator must be the same as T");
}
template<typename T>
Rose<T>::Rose(gen::GeneratorUP<T> &&generator, const TestCase &testCase)
: m_testCase(testCase)
{
m_randomEngine.seed(testCase.seed);
m_root.setGenerator(std::move(generator));
// Initialize the tree with the test case.
currentValue();
}
template<typename T>
T Rose<T>::currentValue()
{
ImplicitParam<param::RandomEngine> randomEngine;
randomEngine.let(&m_randomEngine);
ImplicitParam<param::Size> size;
size.let(m_testCase.size);
return m_root.currentValue<T>();
}
template<typename T>
T Rose<T>::nextShrink(bool &didShrink)
{
ImplicitParam<param::RandomEngine> randomEngine;
randomEngine.let(&m_randomEngine);
ImplicitParam<param::Size> size;
size.let(m_testCase.size);
return m_root.nextShrink<T>(didShrink);
}
template<typename T>
void Rose<T>::acceptShrink()
{
return m_root.acceptShrink();
}
template<typename T>
std::vector<ValueDescription> Rose<T>::example()
{
return m_root.example();
}
} // namespace detail
} // namespace rc
<commit_msg>Fix missing implicit params in Rose<commit_after>#pragma once
#include "ImplicitParam.h"
#include "GenerationParams.h"
#include "Traits.h"
#include "rapidcheck/Generator.h"
template<typename T>
void doShow(const T &value, std::ostream &os)
{
using namespace rc;
show(value, os);
}
namespace rc {
namespace detail {
template<typename T>
T RoseNode::pick(gen::GeneratorUP<T> &&generator)
{
auto i = m_nextChild;
if (m_nextChild >= m_children.size())
m_children.emplace_back(this);
m_nextChild++;
auto &child = m_children[i];
// TODO we should probably not set this every time
child.setGenerator(std::move(generator));
ImplicitParam<ShrinkMode> shrinkMode;
if (*shrinkMode && (i == m_shrinkChild)) {
bool didShrink;
T value(child.nextShrink<T>(didShrink));
if (!didShrink)
m_shrinkChild++;
return std::move(value);
} else {
return child.currentValue<T>();
}
}
template<typename T>
void RoseNode::setGenerator(gen::GeneratorUP<T> &&generator)
{ m_canonicalGenerator = std::move(generator); }
template<typename T>
T RoseNode::currentValue()
{
ImplicitParam<ShrinkMode> shrinkMode;
shrinkMode.let(false);
return generate<T>();
}
template<typename T>
T RoseNode::nextShrink(bool &didShrink)
{
ImplicitParam<param::NoShrink> noShrink;
if (*noShrink) {
didShrink = false;
return currentValue<T>();
} else {
return nextShrink<T>(didShrink, IsCopyConstructible<T>());
}
}
// For copy-constructible types
template<typename T>
T RoseNode::nextShrink(bool &didShrink, std::true_type)
{
if (!m_shrinkIterator) {
// If we don't have a shrink iterator, shrink the children first.
T value(nextShrinkChildren<T>(didShrink));
// If any child did shrink, then we shouldn't shrink ourselves just yet.
if (didShrink)
return std::move(value);
// Otherwise, we should make a shrink iterator
// The already generated value is a last restort, set as accepted.
m_acceptedGenerator = gen::GeneratorUP<T>(new gen::Constant<T>(value));
// Always use the canonical generator to make a shrink iterator
auto typedCanonical = generatorCast<T>(m_canonicalGenerator.get());
m_shrinkIterator = shrink::UntypedIteratorUP(
typedCanonical->shrink(std::move(value)));
// Since the value of every child is now fixed, the number of
// children won't change so we can get rid of any unused ones.
m_children.resize(m_nextChild);
}
auto typedIterator = iteratorCast<T>(m_shrinkIterator);
if (typedIterator->hasNext()) {
// Current iterator still has more shrinks, use that.
didShrink = true;
auto gen = new gen::Constant<T>(typedIterator->next());
m_currentGenerator = gen::GeneratorUP<T>(gen);
return gen->generate();
} else {
// Exhausted
didShrink = false;
// Replace with shrink::nothing since that is likely smaller than the
// existing iterator.
m_shrinkIterator = shrink::nothing<T>();
m_currentGenerator = nullptr;
return currentValue<T>();
}
}
// For non-copy-constructible types.
template<typename T>
T RoseNode::nextShrink(bool &didShrink, std::false_type)
{
// Only shrink children, cannot explicitly shrink non-copy-constructible
// types.
return nextShrinkChildren<T>(didShrink);
}
// Returns the next shrink by shrinking the children or the currently accepted
// if there are no more possible shrinks of the children. `didShrink` is set to
// true if any of them were shrunk.
template<typename T>
T RoseNode::nextShrinkChildren(bool &didShrink)
{
ImplicitParam<ShrinkMode> shrinkMode;
shrinkMode.let(true);
T value(generate<T>());
didShrink = m_shrinkChild < m_nextChild;
return std::move(value);
}
template<typename T>
T RoseNode::generate()
{
ImplicitParam<param::CurrentNode> currentNode;
currentNode.let(this);
m_nextChild = 0;
return generatorCast<T>(currentGenerator())->generate();
}
template<typename T>
gen::Generator<T> *RoseNode::generatorCast(gen::UntypedGenerator *gen)
{
gen::Generator<T> *typed = dynamic_cast<gen::Generator<T> *>(gen);
if (typed == nullptr)
throw UnexpectedType(typeid(T), gen->generatedTypeInfo());
return typed;
}
template<typename T>
shrink::Iterator<T> *RoseNode::iteratorCast(
const shrink::UntypedIteratorUP &it)
{
shrink::Iterator<T> *typed = dynamic_cast<shrink::Iterator<T> *>(it.get());
// TODO use typeid of ShrunkTypes, not iterators themselves
if (typed == nullptr)
throw UnexpectedType(typeid(shrink::Iterator<T>), typeid(it));
return typed;
}
template<typename T>
template<typename Gen>
Rose<T>::Rose(Gen generator, const TestCase &testCase)
: Rose(gen::GeneratorUP<T>(new Gen(std::move(generator))), testCase)
{
static_assert(
std::is_same<T, GeneratedT<Gen>>::value,
"Generated type of generator must be the same as T");
}
template<typename T>
Rose<T>::Rose(gen::GeneratorUP<T> &&generator, const TestCase &testCase)
: m_testCase(testCase)
{
m_randomEngine.seed(testCase.seed);
m_root.setGenerator(std::move(generator));
// Initialize the tree with the test case.
currentValue();
}
template<typename T>
T Rose<T>::currentValue()
{
ImplicitParam<param::RandomEngine> randomEngine;
randomEngine.let(&m_randomEngine);
ImplicitParam<param::Size> size;
size.let(m_testCase.size);
return m_root.currentValue<T>();
}
template<typename T>
T Rose<T>::nextShrink(bool &didShrink)
{
ImplicitParam<param::RandomEngine> randomEngine;
randomEngine.let(&m_randomEngine);
ImplicitParam<param::Size> size;
size.let(m_testCase.size);
return m_root.nextShrink<T>(didShrink);
}
template<typename T>
void Rose<T>::acceptShrink()
{
return m_root.acceptShrink();
}
template<typename T>
std::vector<ValueDescription> Rose<T>::example()
{
ImplicitParam<param::RandomEngine> randomEngine;
randomEngine.let(&m_randomEngine);
ImplicitParam<param::Size> size;
size.let(m_testCase.size);
return m_root.example();
}
} // namespace detail
} // namespace rc
<|endoftext|>
|
<commit_before>namespace libcozmo {
namespace statespace {
// Custom Hash function for a discretized state
class StateHasher {
public:
std::size_t operator()(const Eigen::Vector3i& state) const {
using boost::hash_value;
using boost::hash_combine;
std::size_t seed = 0;
hash_combine(seed, hash_value(state.x()));
hash_combine(seed, hash_value(state.y()));
hash_combine(seed, hash_value(state.z()));
return seed;
}
};
} // namespace statespace
} // namespace libcozmo<commit_msg>Removed unused file<commit_after><|endoftext|>
|
<commit_before>#include "stdafx.h"
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include <string>
#include <shlwapi.h>
#pragma comment(lib, "Shlwapi.lib")
#include "FileSystem.h"
bool filesystem::exists(const std::string& path)
{
return PathFileExistsA(path.c_str()) != 0;
}
bool filesystem::is_directory(const std::string& path)
{
return PathIsDirectoryA(path.c_str()) != 0;
}
bool filesystem::is_file(const std::string& path)
{
return !is_directory(path);
}
bool filesystem::remove_all(const std::string& path)
{
WIN32_FIND_DATAA find_data {};
const std::string str_search(move(combine_path(path, "*.*")));
const HANDLE find_handle = FindFirstFileA(str_search.c_str(), &find_data);
if (find_handle == INVALID_HANDLE_VALUE)
{
return false;
}
do
{
const std::string file_name = find_data.cFileName;
if (file_name == "." || file_name == "..")
{
continue;
}
std::string file_path(move(combine_path(path, find_data.cFileName)));
if (find_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
remove_all(file_path);
}
else
{
remove(file_path.c_str());
}
} while (FindNextFileA(find_handle, &find_data) == TRUE);
FindClose(find_handle);
return remove(path.c_str());
}
bool filesystem::remove(const std::string& path)
{
if (!exists(path))
{
return false;
}
if (is_directory(path))
{
return !!RemoveDirectoryA(path.c_str());
}
return !!DeleteFileA(path.c_str());
}
std::string filesystem::get_directory(const std::string& path)
{
std::string result;
const auto npos = path.npos;
auto slash = path.find_last_of('\\');
if (slash == npos)
{
slash = path.find_last_of('/');
if (slash == npos)
{
result = "";
return result;
}
}
if (slash != path.size() - 1)
{
result = path.substr(0, slash);
return result;
}
const auto last = slash;
slash = path.find_last_of('\\', last);
if (slash == npos)
{
slash = path.find_last_of('/', last);
}
if (slash == npos)
{
result = "";
return result;
}
result = path.substr(last);
return result;
}
bool filesystem::create_directory(const std::string& path)
{
return !!CreateDirectoryA(path.c_str(), nullptr);
}
std::string filesystem::get_base_name(const std::string& path)
{
std::string result;
const auto npos = path.npos;
auto slash = path.find_last_of('\\');
if (slash == npos)
{
slash = path.find_last_of('/');
if (slash == npos)
{
result = path;
return result;
}
}
if (slash != path.size() - 1)
{
result = path.substr(++slash);
return result;
}
const auto last = slash - 1;
slash = path.find_last_of('\\', last);
if (slash == npos)
{
slash = path.find_last_of('/', last);
}
result = (!slash || slash == npos) ? "" : path.substr(slash + 1, last - slash);
return result;
}
void filesystem::strip_extension(std::string& path)
{
const auto dot = path.find('.');
if (dot == path.npos)
{
return;
}
path = path.substr(0, dot);
}
std::string filesystem::get_extension(const std::string& path, bool include_dot)
{
auto dot = path.find('.');
if (dot == path.npos)
{
return std::string();
}
if (!include_dot)
{
++dot;
}
return path.substr(dot);
}
std::string filesystem::get_working_directory()
{
const auto length = GetCurrentDirectoryA(0, nullptr);
if (length < 1)
{
return "";
}
const auto buffer = new char[length];
GetCurrentDirectoryA(length, buffer);
std::string str(buffer);
delete[] buffer;
return str;
}
std::string filesystem::combine_path(const std::string& path_a, const std::string& path_b)
{
char buffer[MAX_PATH] = {};
const auto result = PathCombineA(buffer, path_a.c_str(), path_b.c_str());
if (result == nullptr)
{
return "";
}
std::string str(result);
return str;
}
<commit_msg>cleaned up some stuff in FileSystem - that was pretty bad actually<commit_after>#include "stdafx.h"
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include <string>
#include <shlwapi.h>
#pragma comment(lib, "Shlwapi.lib")
#include "FileSystem.h"
bool filesystem::exists(const std::string& path)
{
return PathFileExistsA(path.c_str()) != 0;
}
bool filesystem::is_directory(const std::string& path)
{
return PathIsDirectoryA(path.c_str()) != 0;
}
bool filesystem::is_file(const std::string& path)
{
return !is_directory(path);
}
bool filesystem::remove_all(const std::string& path)
{
WIN32_FIND_DATAA find_data {};
const std::string str_search(move(combine_path(path, "*.*")));
const HANDLE find_handle = FindFirstFileA(str_search.c_str(), &find_data);
if (find_handle == INVALID_HANDLE_VALUE)
{
return false;
}
do
{
const std::string file_name = find_data.cFileName;
if (file_name == "." || file_name == "..")
{
continue;
}
const std::string file_path(move(combine_path(path, find_data.cFileName)));
if (find_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
remove_all(file_path);
}
else
{
remove(file_path);
}
} while (FindNextFileA(find_handle, &find_data) == TRUE);
FindClose(find_handle);
return remove(path);
}
bool filesystem::remove(const std::string& path)
{
if (!exists(path))
{
return false;
}
if (is_directory(path))
{
return !!RemoveDirectoryA(path.c_str());
}
return !!DeleteFileA(path.c_str());
}
std::string filesystem::get_directory(const std::string& path)
{
const auto npos = path.npos;
auto slash = path.find_last_of('\\');
if (slash == npos)
{
slash = path.find_last_of('/');
if (slash == npos)
{
return std::string();
}
}
if (slash != path.size() - 1)
{
return path.substr(0, slash);
}
const auto last = slash;
slash = path.find_last_of('\\', last);
if (slash == npos)
{
slash = path.find_last_of('/', last);
}
if (slash == npos)
{
return std::string();
}
return path.substr(last);
}
bool filesystem::create_directory(const std::string& path)
{
return !!CreateDirectoryA(path.c_str(), nullptr);
}
std::string filesystem::get_base_name(const std::string& path)
{
const auto npos = path.npos;
auto slash = path.find_last_of('\\');
if (slash == npos)
{
slash = path.find_last_of('/');
if (slash == npos)
{
return path;
}
}
if (slash != path.size() - 1)
{
return path.substr(++slash);
}
const auto last = slash - 1;
slash = path.find_last_of('\\', last);
if (slash == npos)
{
slash = path.find_last_of('/', last);
}
if (!slash || slash == npos)
{
return std::string();
}
return path.substr(slash + 1, last - slash);
}
void filesystem::strip_extension(std::string& path)
{
const auto dot = path.find('.');
if (dot == path.npos)
{
return;
}
path = path.substr(0, dot);
}
std::string filesystem::get_extension(const std::string& path, bool include_dot)
{
auto dot = path.find('.');
if (dot == path.npos)
{
return std::string();
}
if (!include_dot)
{
++dot;
}
return path.substr(dot);
}
std::string filesystem::get_working_directory()
{
const auto length = GetCurrentDirectoryA(0, nullptr);
if (length < 1)
{
return std::string();
}
const auto buffer = new char[length];
GetCurrentDirectoryA(length, buffer);
std::string result(buffer);
delete[] buffer;
return result;
}
std::string filesystem::combine_path(const std::string& path_a, const std::string& path_b)
{
char buffer[MAX_PATH] {};
const LPSTR result = PathCombineA(buffer, path_a.c_str(), path_b.c_str());
if (result == nullptr)
{
return std::string();
}
return std::string(result);
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "sandbox/src/win2k_threadpool.h"
#include "base/logging.h"
#include "sandbox/src/win_utils.h"
namespace sandbox {
bool Win2kThreadPool::RegisterWait(const void* client, HANDLE waitable_object,
CrossCallIPCCallback callback,
void* context) {
if (0 == client) {
return false;
}
HANDLE pool_object = NULL;
// create a wait for a kernel object, with no timeout
if (!::RegisterWaitForSingleObject(&pool_object, waitable_object, callback,
context, INFINITE, WT_EXECUTEDEFAULT)) {
return false;
}
PoolObject pool_obj = {client, pool_object};
AutoLock lock(&lock_);
pool_objects_.push_back(pool_obj);
return true;
}
bool Win2kThreadPool::UnRegisterWaits(void* cookie) {
if (0 == cookie) {
return false;
}
AutoLock lock(&lock_);
PoolObjects::iterator it;
for (it = pool_objects_.begin(); it != pool_objects_.end(); ++it) {
if (it->cookie == cookie) {
if (!::UnregisterWaitEx(it->wait, INVALID_HANDLE_VALUE))
return false;
it->cookie = 0;
}
}
return true;
}
size_t Win2kThreadPool::OutstandingWaits() {
size_t count =0;
AutoLock lock(&lock_);
PoolObjects::iterator it;
for (it = pool_objects_.begin(); it != pool_objects_.end(); ++it) {
if (it->cookie != 0) {
++count;
}
}
return count;
}
Win2kThreadPool::~Win2kThreadPool() {
// Here we used to unregister all the pool wait handles. Now, following the
// rest of the code we avoid lengthy or blocking calls given that the process
// is being torn down.
}
} // namespace sandbox<commit_msg>We need to delete this critical section otherwise application verifier warns all the time.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "sandbox/src/win2k_threadpool.h"
#include "base/logging.h"
#include "sandbox/src/win_utils.h"
namespace sandbox {
bool Win2kThreadPool::RegisterWait(const void* client, HANDLE waitable_object,
CrossCallIPCCallback callback,
void* context) {
if (0 == client) {
return false;
}
HANDLE pool_object = NULL;
// create a wait for a kernel object, with no timeout
if (!::RegisterWaitForSingleObject(&pool_object, waitable_object, callback,
context, INFINITE, WT_EXECUTEDEFAULT)) {
return false;
}
PoolObject pool_obj = {client, pool_object};
AutoLock lock(&lock_);
pool_objects_.push_back(pool_obj);
return true;
}
bool Win2kThreadPool::UnRegisterWaits(void* cookie) {
if (0 == cookie) {
return false;
}
AutoLock lock(&lock_);
PoolObjects::iterator it;
for (it = pool_objects_.begin(); it != pool_objects_.end(); ++it) {
if (it->cookie == cookie) {
if (!::UnregisterWaitEx(it->wait, INVALID_HANDLE_VALUE))
return false;
it->cookie = 0;
}
}
return true;
}
size_t Win2kThreadPool::OutstandingWaits() {
size_t count =0;
AutoLock lock(&lock_);
PoolObjects::iterator it;
for (it = pool_objects_.begin(); it != pool_objects_.end(); ++it) {
if (it->cookie != 0) {
++count;
}
}
return count;
}
Win2kThreadPool::~Win2kThreadPool() {
// Here we used to unregister all the pool wait handles. Now, following the
// rest of the code we avoid lengthy or blocking calls given that the process
// is being torn down.
::DeleteCriticalSection(&lock_);
}
} // namespace sandbox<|endoftext|>
|
<commit_before>//===- IteratorTest.cpp - Unit tests for iterator utilities ---------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/iterator.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallVector.h"
#include "gtest/gtest.h"
using namespace llvm;
namespace {
template <int> struct Shadow;
struct WeirdIter : std::iterator<std::input_iterator_tag, Shadow<0>, Shadow<1>,
Shadow<2>, Shadow<3>> {};
struct AdaptedIter : iterator_adaptor_base<AdaptedIter, WeirdIter> {};
// Test that iterator_adaptor_base forwards typedefs, if value_type is
// unchanged.
static_assert(std::is_same<typename AdaptedIter::value_type, Shadow<0>>::value,
"");
static_assert(
std::is_same<typename AdaptedIter::difference_type, Shadow<1>>::value, "");
static_assert(std::is_same<typename AdaptedIter::pointer, Shadow<2>>::value,
"");
static_assert(std::is_same<typename AdaptedIter::reference, Shadow<3>>::value,
"");
TEST(PointeeIteratorTest, Basic) {
int arr[4] = { 1, 2, 3, 4 };
SmallVector<int *, 4> V;
V.push_back(&arr[0]);
V.push_back(&arr[1]);
V.push_back(&arr[2]);
V.push_back(&arr[3]);
auto Begin = make_pointee_iterator(V.begin());
auto End = make_pointee_iterator(V.end());
static_assert(
std::is_same<decltype(Begin),
pointee_iterator<SmallVectorImpl<int *>::iterator>>::value,
"Wrong type returned by make_pointee_iterator");
auto I = Begin;
for (int i = 0; i < 4; ++i) {
EXPECT_EQ(*V[i], *I);
EXPECT_EQ(I, Begin + i);
EXPECT_EQ(I, std::next(Begin, i));
auto J = Begin;
J += i;
EXPECT_EQ(I, J);
EXPECT_EQ(*V[i], Begin[i]);
EXPECT_NE(I, End);
EXPECT_GT(End, I);
EXPECT_LT(I, End);
EXPECT_GE(I, Begin);
EXPECT_LE(Begin, I);
EXPECT_EQ(i, I - Begin);
EXPECT_EQ(i, std::distance(Begin, I));
EXPECT_EQ(Begin, I - i);
auto K = I++;
EXPECT_EQ(K, std::prev(I));
}
EXPECT_EQ(End, I);
}
TEST(PointeeIteratorTest, SmartPointer) {
SmallVector<std::unique_ptr<int>, 4> V;
V.push_back(make_unique<int>(1));
V.push_back(make_unique<int>(2));
V.push_back(make_unique<int>(3));
V.push_back(make_unique<int>(4));
auto Begin = make_pointee_iterator(V.begin());
auto End = make_pointee_iterator(V.end());
static_assert(
std::is_same<decltype(Begin),
pointee_iterator<
SmallVectorImpl<std::unique_ptr<int>>::iterator>>::value,
"Wrong type returned by make_pointee_iterator");
auto I = Begin;
for (int i = 0; i < 4; ++i) {
EXPECT_EQ(*V[i], *I);
EXPECT_EQ(I, Begin + i);
EXPECT_EQ(I, std::next(Begin, i));
auto J = Begin;
J += i;
EXPECT_EQ(I, J);
EXPECT_EQ(*V[i], Begin[i]);
EXPECT_NE(I, End);
EXPECT_GT(End, I);
EXPECT_LT(I, End);
EXPECT_GE(I, Begin);
EXPECT_LE(Begin, I);
EXPECT_EQ(i, I - Begin);
EXPECT_EQ(i, std::distance(Begin, I));
EXPECT_EQ(Begin, I - i);
auto K = I++;
EXPECT_EQ(K, std::prev(I));
}
EXPECT_EQ(End, I);
}
TEST(FilterIteratorTest, Lambda) {
auto IsOdd = [](int N) { return N % 2 == 1; };
int A[] = {0, 1, 2, 3, 4, 5, 6};
auto Range = make_filter_range(A, IsOdd);
SmallVector<int, 3> Actual(Range.begin(), Range.end());
EXPECT_EQ((SmallVector<int, 3>{1, 3, 5}), Actual);
}
TEST(FilterIteratorTest, CallableObject) {
int Counter = 0;
struct Callable {
int &Counter;
Callable(int &Counter) : Counter(Counter) {}
bool operator()(int N) {
Counter++;
return N % 2 == 1;
}
};
Callable IsOdd(Counter);
int A[] = {0, 1, 2, 3, 4, 5, 6};
auto Range = make_filter_range(A, IsOdd);
EXPECT_EQ(2, Counter);
SmallVector<int, 3> Actual(Range.begin(), Range.end());
EXPECT_GE(Counter, 7);
EXPECT_EQ((SmallVector<int, 3>{1, 3, 5}), Actual);
}
TEST(FilterIteratorTest, FunctionPointer) {
bool (*IsOdd)(int) = [](int N) { return N % 2 == 1; };
int A[] = {0, 1, 2, 3, 4, 5, 6};
auto Range = make_filter_range(A, IsOdd);
SmallVector<int, 3> Actual(Range.begin(), Range.end());
EXPECT_EQ((SmallVector<int, 3>{1, 3, 5}), Actual);
}
TEST(FilterIteratorTest, Composition) {
auto IsOdd = [](int N) { return N % 2 == 1; };
std::unique_ptr<int> A[] = {make_unique<int>(0), make_unique<int>(1),
make_unique<int>(2), make_unique<int>(3),
make_unique<int>(4), make_unique<int>(5),
make_unique<int>(6)};
using PointeeIterator = pointee_iterator<std::unique_ptr<int> *>;
auto Range = make_filter_range(
make_range(PointeeIterator(std::begin(A)), PointeeIterator(std::end(A))),
IsOdd);
SmallVector<int, 3> Actual(Range.begin(), Range.end());
EXPECT_EQ((SmallVector<int, 3>{1, 3, 5}), Actual);
}
TEST(FilterIteratorTest, InputIterator) {
struct InputIterator
: iterator_adaptor_base<InputIterator, int *, std::input_iterator_tag> {
using BaseT =
iterator_adaptor_base<InputIterator, int *, std::input_iterator_tag>;
InputIterator(int *It) : BaseT(It) {}
};
auto IsOdd = [](int N) { return N % 2 == 1; };
int A[] = {0, 1, 2, 3, 4, 5, 6};
auto Range = make_filter_range(
make_range(InputIterator(std::begin(A)), InputIterator(std::end(A))),
IsOdd);
SmallVector<int, 3> Actual(Range.begin(), Range.end());
EXPECT_EQ((SmallVector<int, 3>{1, 3, 5}), Actual);
}
TEST(PointerIterator, Basic) {
int A[] = {1, 2, 3, 4};
auto Begin = make_pointer_iterator(std::begin(A));
auto End = make_pointer_iterator(std::end(A));
static_assert(std::is_same<decltype(Begin), pointer_iterator<int *>>::value,
"Wrong type returned by make_pointer_iterator");
EXPECT_EQ(A, *Begin);
++Begin;
EXPECT_EQ(A + 1, *Begin);
++Begin;
EXPECT_EQ(A + 2, *Begin);
++Begin;
EXPECT_EQ(A + 3, *Begin);
++Begin;
EXPECT_EQ(Begin, End);
}
TEST(PointerIterator, Const) {
int A[] = {1, 2, 3, 4};
auto Begin = make_pointer_iterator(std::begin(A));
EXPECT_EQ(A, *Begin);
EXPECT_EQ(A + 1, std::next(*Begin, 1));
EXPECT_EQ(A + 2, std::next(*Begin, 2));
EXPECT_EQ(A + 3, std::next(*Begin, 3));
EXPECT_EQ(A + 4, std::next(*Begin, 4));
}
} // anonymous namespace
<commit_msg>[ADT] Don't use make_pointee_iterator in IteratorTest.<commit_after>//===- IteratorTest.cpp - Unit tests for iterator utilities ---------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/iterator.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallVector.h"
#include "gtest/gtest.h"
using namespace llvm;
namespace {
template <int> struct Shadow;
struct WeirdIter : std::iterator<std::input_iterator_tag, Shadow<0>, Shadow<1>,
Shadow<2>, Shadow<3>> {};
struct AdaptedIter : iterator_adaptor_base<AdaptedIter, WeirdIter> {};
// Test that iterator_adaptor_base forwards typedefs, if value_type is
// unchanged.
static_assert(std::is_same<typename AdaptedIter::value_type, Shadow<0>>::value,
"");
static_assert(
std::is_same<typename AdaptedIter::difference_type, Shadow<1>>::value, "");
static_assert(std::is_same<typename AdaptedIter::pointer, Shadow<2>>::value,
"");
static_assert(std::is_same<typename AdaptedIter::reference, Shadow<3>>::value,
"");
TEST(PointeeIteratorTest, Basic) {
int arr[4] = { 1, 2, 3, 4 };
SmallVector<int *, 4> V;
V.push_back(&arr[0]);
V.push_back(&arr[1]);
V.push_back(&arr[2]);
V.push_back(&arr[3]);
typedef pointee_iterator<SmallVectorImpl<int *>::const_iterator> test_iterator;
test_iterator Begin, End;
Begin = V.begin();
End = test_iterator(V.end());
test_iterator I = Begin;
for (int i = 0; i < 4; ++i) {
EXPECT_EQ(*V[i], *I);
EXPECT_EQ(I, Begin + i);
EXPECT_EQ(I, std::next(Begin, i));
test_iterator J = Begin;
J += i;
EXPECT_EQ(I, J);
EXPECT_EQ(*V[i], Begin[i]);
EXPECT_NE(I, End);
EXPECT_GT(End, I);
EXPECT_LT(I, End);
EXPECT_GE(I, Begin);
EXPECT_LE(Begin, I);
EXPECT_EQ(i, I - Begin);
EXPECT_EQ(i, std::distance(Begin, I));
EXPECT_EQ(Begin, I - i);
test_iterator K = I++;
EXPECT_EQ(K, std::prev(I));
}
EXPECT_EQ(End, I);
}
TEST(PointeeIteratorTest, SmartPointer) {
SmallVector<std::unique_ptr<int>, 4> V;
V.push_back(make_unique<int>(1));
V.push_back(make_unique<int>(2));
V.push_back(make_unique<int>(3));
V.push_back(make_unique<int>(4));
typedef pointee_iterator<
SmallVectorImpl<std::unique_ptr<int>>::const_iterator> test_iterator;
test_iterator Begin, End;
Begin = V.begin();
End = test_iterator(V.end());
test_iterator I = Begin;
for (int i = 0; i < 4; ++i) {
EXPECT_EQ(*V[i], *I);
EXPECT_EQ(I, Begin + i);
EXPECT_EQ(I, std::next(Begin, i));
test_iterator J = Begin;
J += i;
EXPECT_EQ(I, J);
EXPECT_EQ(*V[i], Begin[i]);
EXPECT_NE(I, End);
EXPECT_GT(End, I);
EXPECT_LT(I, End);
EXPECT_GE(I, Begin);
EXPECT_LE(Begin, I);
EXPECT_EQ(i, I - Begin);
EXPECT_EQ(i, std::distance(Begin, I));
EXPECT_EQ(Begin, I - i);
test_iterator K = I++;
EXPECT_EQ(K, std::prev(I));
}
EXPECT_EQ(End, I);
}
TEST(FilterIteratorTest, Lambda) {
auto IsOdd = [](int N) { return N % 2 == 1; };
int A[] = {0, 1, 2, 3, 4, 5, 6};
auto Range = make_filter_range(A, IsOdd);
SmallVector<int, 3> Actual(Range.begin(), Range.end());
EXPECT_EQ((SmallVector<int, 3>{1, 3, 5}), Actual);
}
TEST(FilterIteratorTest, CallableObject) {
int Counter = 0;
struct Callable {
int &Counter;
Callable(int &Counter) : Counter(Counter) {}
bool operator()(int N) {
Counter++;
return N % 2 == 1;
}
};
Callable IsOdd(Counter);
int A[] = {0, 1, 2, 3, 4, 5, 6};
auto Range = make_filter_range(A, IsOdd);
EXPECT_EQ(2, Counter);
SmallVector<int, 3> Actual(Range.begin(), Range.end());
EXPECT_GE(Counter, 7);
EXPECT_EQ((SmallVector<int, 3>{1, 3, 5}), Actual);
}
TEST(FilterIteratorTest, FunctionPointer) {
bool (*IsOdd)(int) = [](int N) { return N % 2 == 1; };
int A[] = {0, 1, 2, 3, 4, 5, 6};
auto Range = make_filter_range(A, IsOdd);
SmallVector<int, 3> Actual(Range.begin(), Range.end());
EXPECT_EQ((SmallVector<int, 3>{1, 3, 5}), Actual);
}
TEST(FilterIteratorTest, Composition) {
auto IsOdd = [](int N) { return N % 2 == 1; };
std::unique_ptr<int> A[] = {make_unique<int>(0), make_unique<int>(1),
make_unique<int>(2), make_unique<int>(3),
make_unique<int>(4), make_unique<int>(5),
make_unique<int>(6)};
using PointeeIterator = pointee_iterator<std::unique_ptr<int> *>;
auto Range = make_filter_range(
make_range(PointeeIterator(std::begin(A)), PointeeIterator(std::end(A))),
IsOdd);
SmallVector<int, 3> Actual(Range.begin(), Range.end());
EXPECT_EQ((SmallVector<int, 3>{1, 3, 5}), Actual);
}
TEST(FilterIteratorTest, InputIterator) {
struct InputIterator
: iterator_adaptor_base<InputIterator, int *, std::input_iterator_tag> {
using BaseT =
iterator_adaptor_base<InputIterator, int *, std::input_iterator_tag>;
InputIterator(int *It) : BaseT(It) {}
};
auto IsOdd = [](int N) { return N % 2 == 1; };
int A[] = {0, 1, 2, 3, 4, 5, 6};
auto Range = make_filter_range(
make_range(InputIterator(std::begin(A)), InputIterator(std::end(A))),
IsOdd);
SmallVector<int, 3> Actual(Range.begin(), Range.end());
EXPECT_EQ((SmallVector<int, 3>{1, 3, 5}), Actual);
}
TEST(PointerIterator, Basic) {
int A[] = {1, 2, 3, 4};
pointer_iterator<int *> Begin(std::begin(A)), End(std::end(A));
EXPECT_EQ(A, *Begin);
++Begin;
EXPECT_EQ(A + 1, *Begin);
++Begin;
EXPECT_EQ(A + 2, *Begin);
++Begin;
EXPECT_EQ(A + 3, *Begin);
++Begin;
EXPECT_EQ(Begin, End);
}
TEST(PointerIterator, Const) {
int A[] = {1, 2, 3, 4};
const pointer_iterator<int *> Begin(std::begin(A));
EXPECT_EQ(A, *Begin);
EXPECT_EQ(A + 1, std::next(*Begin, 1));
EXPECT_EQ(A + 2, std::next(*Begin, 2));
EXPECT_EQ(A + 3, std::next(*Begin, 3));
EXPECT_EQ(A + 4, std::next(*Begin, 4));
}
} // anonymous namespace
<|endoftext|>
|
<commit_before>//===- unittests/Analysis/CFGTest.cpp - CFG tests -------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "CFGBuildResult.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include "clang/Analysis/CFG.h"
#include "clang/Tooling/Tooling.h"
#include "gtest/gtest.h"
#include <string>
#include <vector>
namespace clang {
namespace analysis {
namespace {
// Constructing a CFG for a range-based for over a dependent type fails (but
// should not crash).
TEST(CFG, RangeBasedForOverDependentType) {
const char *Code = "class Foo;\n"
"template <typename T>\n"
"void f(const T &Range) {\n"
" for (const Foo *TheFoo : Range) {\n"
" }\n"
"}\n";
EXPECT_EQ(BuildResult::SawFunctionBody, BuildCFG(Code).getStatus());
}
// Constructing a CFG containing a delete expression on a dependent type should
// not crash.
TEST(CFG, DeleteExpressionOnDependentType) {
const char *Code = "template<class T>\n"
"void f(T t) {\n"
" delete t;\n"
"}\n";
EXPECT_EQ(BuildResult::BuiltCFG, BuildCFG(Code).getStatus());
}
// Constructing a CFG on a function template with a variable of incomplete type
// should not crash.
TEST(CFG, VariableOfIncompleteType) {
const char *Code = "template<class T> void f() {\n"
" class Undefined;\n"
" Undefined u;\n"
"}\n";
EXPECT_EQ(BuildResult::BuiltCFG, BuildCFG(Code).getStatus());
}
TEST(CFG, IsLinear) {
auto expectLinear = [](bool IsLinear, const char *Code) {
BuildResult B = BuildCFG(Code);
EXPECT_EQ(BuildResult::BuiltCFG, B.getStatus());
EXPECT_EQ(IsLinear, B.getCFG()->isLinear());
};
expectLinear(true, "void foo() {}");
expectLinear(true, "void foo() { if (true) return; }");
expectLinear(true, "void foo() { if constexpr (false); }");
expectLinear(false, "void foo(bool coin) { if (coin) return; }");
expectLinear(false, "void foo() { for(;;); }");
expectLinear(false, "void foo() { do {} while (true); }");
expectLinear(true, "void foo() { do {} while (false); }");
expectLinear(true, "void foo() { foo(); }"); // Recursion is not our problem.
}
TEST(CFG, ConditionExpr) {
const char *Code = R"(void f(bool A, bool B, bool C) {
if (A && B && C)
int x;
})";
BuildResult Result = BuildCFG(Code);
EXPECT_EQ(BuildResult::BuiltCFG, Result.getStatus());
// [B5 (ENTRY)] -> [B4] -> [B3] -> [B2] -> [B1] -> [B0 (EXIT)]
// \ \ \ /
// ------------------------------->
CFG *cfg = Result.getCFG();
auto GetBlock = [cfg] (unsigned Index) -> CFGBlock * {
assert(Index < cfg->size());
return *(cfg->begin() + Index);
};
auto GetExprText = [] (const Expr *E) -> std::string {
// It's very awkward trying to recover the actual expression text without
// a real source file, so use this as a workaround. We know that the
// condition expression looks like this:
//
// ImplicitCastExpr 0xd07bf8 '_Bool' <LValueToRValue>
// `-DeclRefExpr 0xd07bd8 '_Bool' lvalue ParmVar 0xd07960 'C' '_Bool'
assert(isa<ImplicitCastExpr>(E));
assert(++E->child_begin() == E->child_end());
const auto *D = dyn_cast<DeclRefExpr>(*E->child_begin());
return D->getFoundDecl()->getNameAsString();
};
EXPECT_EQ(GetBlock(1)->getLastCondition(), nullptr);
EXPECT_EQ(GetExprText(GetBlock(4)->getLastCondition()), "A");
EXPECT_EQ(GetExprText(GetBlock(3)->getLastCondition()), "B");
EXPECT_EQ(GetExprText(GetBlock(2)->getLastCondition()), "C");
//===--------------------------------------------------------------------===//
Code = R"(void foo(int x, int y) {
(void)(x + y);
})";
Result = BuildCFG(Code);
EXPECT_EQ(BuildResult::BuiltCFG, Result.getStatus());
// [B2 (ENTRY)] -> [B1] -> [B0 (EXIT)]
cfg = Result.getCFG();
EXPECT_EQ(GetBlock(1)->getLastCondition(), nullptr);
}
} // namespace
} // namespace analysis
} // namespace clang
<commit_msg>Fix a buildbot failure due to the AST's lifetime ending before the test<commit_after>//===- unittests/Analysis/CFGTest.cpp - CFG tests -------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "CFGBuildResult.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include "clang/Analysis/CFG.h"
#include "clang/Tooling/Tooling.h"
#include "gtest/gtest.h"
#include <string>
#include <vector>
namespace clang {
namespace analysis {
namespace {
// Constructing a CFG for a range-based for over a dependent type fails (but
// should not crash).
TEST(CFG, RangeBasedForOverDependentType) {
const char *Code = "class Foo;\n"
"template <typename T>\n"
"void f(const T &Range) {\n"
" for (const Foo *TheFoo : Range) {\n"
" }\n"
"}\n";
EXPECT_EQ(BuildResult::SawFunctionBody, BuildCFG(Code).getStatus());
}
// Constructing a CFG containing a delete expression on a dependent type should
// not crash.
TEST(CFG, DeleteExpressionOnDependentType) {
const char *Code = "template<class T>\n"
"void f(T t) {\n"
" delete t;\n"
"}\n";
EXPECT_EQ(BuildResult::BuiltCFG, BuildCFG(Code).getStatus());
}
// Constructing a CFG on a function template with a variable of incomplete type
// should not crash.
TEST(CFG, VariableOfIncompleteType) {
const char *Code = "template<class T> void f() {\n"
" class Undefined;\n"
" Undefined u;\n"
"}\n";
EXPECT_EQ(BuildResult::BuiltCFG, BuildCFG(Code).getStatus());
}
TEST(CFG, IsLinear) {
auto expectLinear = [](bool IsLinear, const char *Code) {
BuildResult B = BuildCFG(Code);
EXPECT_EQ(BuildResult::BuiltCFG, B.getStatus());
EXPECT_EQ(IsLinear, B.getCFG()->isLinear());
};
expectLinear(true, "void foo() {}");
expectLinear(true, "void foo() { if (true) return; }");
expectLinear(true, "void foo() { if constexpr (false); }");
expectLinear(false, "void foo(bool coin) { if (coin) return; }");
expectLinear(false, "void foo() { for(;;); }");
expectLinear(false, "void foo() { do {} while (true); }");
expectLinear(true, "void foo() { do {} while (false); }");
expectLinear(true, "void foo() { foo(); }"); // Recursion is not our problem.
}
TEST(CFG, ConditionExpr) {
const char *Code = R"(void f(bool A, bool B, bool C) {
if (A && B && C)
int x;
})";
BuildResult Result = BuildCFG(Code);
EXPECT_EQ(BuildResult::BuiltCFG, Result.getStatus());
// [B5 (ENTRY)] -> [B4] -> [B3] -> [B2] -> [B1] -> [B0 (EXIT)]
// \ \ \ /
// ------------------------------->
CFG *cfg = Result.getCFG();
auto GetBlock = [cfg] (unsigned Index) -> CFGBlock * {
assert(Index < cfg->size());
return *(cfg->begin() + Index);
};
EXPECT_EQ(GetBlock(1)->getLastCondition(), nullptr);
// Unfortunately, we can't check whether the correct Expr was returned by
// getLastCondition, because the lifetime of the AST ends by the time we
// retrieve the CFG.
//===--------------------------------------------------------------------===//
Code = R"(void foo(int x, int y) {
(void)(x + y);
})";
Result = BuildCFG(Code);
EXPECT_EQ(BuildResult::BuiltCFG, Result.getStatus());
// [B2 (ENTRY)] -> [B1] -> [B0 (EXIT)]
cfg = Result.getCFG();
EXPECT_EQ(GetBlock(1)->getLastCondition(), nullptr);
}
} // namespace
} // namespace analysis
} // namespace clang
<|endoftext|>
|
<commit_before><commit_msg>Used constants if possible.<commit_after><|endoftext|>
|
<commit_before>#pragma once
#include <cstddef>
// Return ceil(log2(x)).
static inline std::size_t
ceil_log2(std::size_t x)
{
auto bits = sizeof(long long) * 8 - __builtin_clzll(x);
if (x == (std::size_t)1 << (bits - 1))
return bits - 1;
return bits;
}
// Return ceil(log2(x)). This is slow, but can be evaluated in a
// constexpr context.
static inline constexpr std::size_t
ceil_log2_const(std::size_t x, bool exact = true)
{
return (x == 0) ? (1/x)
: (x == 1) ? (exact ? 0 : 1)
: 1 + ceil_log2_const(x >> 1, ((x & 1) == 1) ? false : exact);
}
// Round up to the nearest power of 2
static inline std::size_t
round_up_to_pow2(std::size_t x)
{
auto bits = sizeof(long long) * 8 - __builtin_clzll(x);
if (x == (std::size_t)1 << (bits - 1))
return x;
return (std::size_t)1 << bits;
}
<commit_msg>log2: More utilities<commit_after>#pragma once
#include <cstddef>
// Return ceil(log2(x)).
static inline std::size_t
ceil_log2(std::size_t x)
{
auto bits = sizeof(long long) * 8 - __builtin_clzll(x);
if (x == (std::size_t)1 << (bits - 1))
return bits - 1;
return bits;
}
// Return ceil(log2(x)). This is slow, but can be evaluated in a
// constexpr context. 'exact' is used internally and should not be
// provided by the caller.
static inline constexpr std::size_t
ceil_log2_const(std::size_t x, bool exact = true)
{
return (x == 0) ? (1/x)
: (x == 1) ? (exact ? 0 : 1)
: 1 + ceil_log2_const(x >> 1, ((x & 1) == 1) ? false : exact);
}
// Round up to the nearest power of 2
static inline std::size_t
round_up_to_pow2(std::size_t x)
{
auto bits = sizeof(long long) * 8 - __builtin_clzll(x);
if (x == (std::size_t)1 << (bits - 1))
return x;
return (std::size_t)1 << bits;
}
static inline constexpr std::size_t
round_up_to_pow2_const(std::size_t x)
{
return (std::size_t)1 << ceil_log2_const(x);
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: exp_op.hxx,v $
*
* $Revision: 1.12 $
*
* last change: $Author: obo $ $Date: 2006-03-22 12:07:02 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _EXP_OP_HXX
#define _EXP_OP_HXX
#ifndef SC_FILTER_HXX
#include "filter.hxx"
#endif
#ifndef _ROOT_HXX
#include "root.hxx"
#endif
#ifndef SC_XEROOT_HXX
#include "xeroot.hxx"
#endif
class ScDocument;
class ScPatternAttr;
class ScFormulaCell;
class ExcDocument;
class SotStorage;
class ExportTyp
{
protected:
SvStream& aOut; // Ausgabe-Stream
ScDocument* pD; // Dokument
CharSet eZielChar; // Ziel-Zeichensatz
public:
ExportTyp( SvStream& aStream, ScDocument* pDoc, CharSet eDest ):
aOut( aStream )
{
eZielChar = eDest;
pD = pDoc;
}
virtual FltError Write() = 0;
};
class ExportWK1 : public ExportTyp
{
private:
BYTE GenFormByte( const ScPatternAttr& );
void Bof();
void Eof();
void Calcmode();
void Calcorder();
void Split();
void Sync();
void Dimensions();
void Window1();
void Colw();
void Blank( const UINT16 nC, const UINT16 nR, const ScPatternAttr& );
void Number( const UINT16 nC, const UINT16 nR, const double f, const ScPatternAttr& );
void Label( const UINT16 nC, const UINT16 nR, const String&, const ScPatternAttr& );
void Formula( const UINT16 nC, const UINT16 nR, const ScFormulaCell*, const ScPatternAttr& );
void Protect();
void Footer();
void Header();
void Margins();
void Labelfmt();
void Calccount();
void Cursorw12();
void WKString( const UINT16 nC, const UINT16 nR, const ScFormulaCell*, const ScPatternAttr& );
void Snrange();
void Hidcol();
void Cpi();
public:
static const USHORT WK1MAXCOL;
static const USHORT WK1MAXROW;
inline ExportWK1( SvStream& r, ScDocument* p, CharSet e ) :
ExportTyp( r, p, e ) {};
FltError Write();
};
class ExportBiff5 : public ExportTyp, protected XclExpRoot
{
private:
ExcDocument* pExcDoc;
protected:
RootData* pExcRoot;
public:
ExportBiff5( XclExpRootData& rExpData, SvStream& rStrm );
virtual ~ExportBiff5();
FltError Write();
};
class ExportBiff8 : public ExportBiff5
{
public:
ExportBiff8( XclExpRootData& rExpData, SvStream& rStrm );
virtual ~ExportBiff8();
};
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.12.584); FILE MERGED 2008/04/01 12:36:19 thb 1.12.584.2: #i85898# Stripping all external header guards 2008/03/31 17:14:42 rt 1.12.584.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: exp_op.hxx,v $
* $Revision: 1.13 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _EXP_OP_HXX
#define _EXP_OP_HXX
#include "filter.hxx"
#include "root.hxx"
#include "xeroot.hxx"
class ScDocument;
class ScPatternAttr;
class ScFormulaCell;
class ExcDocument;
class SotStorage;
class ExportTyp
{
protected:
SvStream& aOut; // Ausgabe-Stream
ScDocument* pD; // Dokument
CharSet eZielChar; // Ziel-Zeichensatz
public:
ExportTyp( SvStream& aStream, ScDocument* pDoc, CharSet eDest ):
aOut( aStream )
{
eZielChar = eDest;
pD = pDoc;
}
virtual FltError Write() = 0;
};
class ExportWK1 : public ExportTyp
{
private:
BYTE GenFormByte( const ScPatternAttr& );
void Bof();
void Eof();
void Calcmode();
void Calcorder();
void Split();
void Sync();
void Dimensions();
void Window1();
void Colw();
void Blank( const UINT16 nC, const UINT16 nR, const ScPatternAttr& );
void Number( const UINT16 nC, const UINT16 nR, const double f, const ScPatternAttr& );
void Label( const UINT16 nC, const UINT16 nR, const String&, const ScPatternAttr& );
void Formula( const UINT16 nC, const UINT16 nR, const ScFormulaCell*, const ScPatternAttr& );
void Protect();
void Footer();
void Header();
void Margins();
void Labelfmt();
void Calccount();
void Cursorw12();
void WKString( const UINT16 nC, const UINT16 nR, const ScFormulaCell*, const ScPatternAttr& );
void Snrange();
void Hidcol();
void Cpi();
public:
static const USHORT WK1MAXCOL;
static const USHORT WK1MAXROW;
inline ExportWK1( SvStream& r, ScDocument* p, CharSet e ) :
ExportTyp( r, p, e ) {};
FltError Write();
};
class ExportBiff5 : public ExportTyp, protected XclExpRoot
{
private:
ExcDocument* pExcDoc;
protected:
RootData* pExcRoot;
public:
ExportBiff5( XclExpRootData& rExpData, SvStream& rStrm );
virtual ~ExportBiff5();
FltError Write();
};
class ExportBiff8 : public ExportBiff5
{
public:
ExportBiff8( XclExpRootData& rExpData, SvStream& rStrm );
virtual ~ExportBiff8();
};
#endif
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: xeroot.hxx,v $
*
* $Revision: 1.19 $
*
* last change: $Author: obo $ $Date: 2006-07-10 13:55:52 $
*
* 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_XEROOT_HXX
#define SC_XEROOT_HXX
#ifndef SC_XLROOT_HXX
#include "xlroot.hxx"
#endif
// Forward declarations of objects in public use ==============================
class XclExpStream;
class XclExpRecordBase;
class XclExpString;
typedef ScfRef< XclExpRecordBase > XclExpRecordRef;
typedef ScfRef< XclExpString > XclExpStringRef;
// Global data ================================================================
class XclExpTabInfo;
class XclExpAddressConverter;
class XclExpFormulaCompiler;
class XclExpProgressBar;
class XclExpSst;
class XclExpPalette;
class XclExpFontBuffer;
class XclExpNumFmtBuffer;
class XclExpXFBuffer;
class XclExpLinkManager;
class XclExpNameManager;
class XclExpFilterManager;
class XclExpPivotTableManager;
/** Stores global buffers and data needed for Excel export filter. */
struct XclExpRootData : public XclRootData
{
typedef ScfRef< XclExpTabInfo > XclExpTabInfoRef;
typedef ScfRef< XclExpAddressConverter > XclExpAddrConvRef;
typedef ScfRef< XclExpFormulaCompiler > XclExpFmlaCompRef;
typedef ScfRef< XclExpProgressBar > XclExpProgressRef;
typedef ScfRef< XclExpSst > XclExpSstRef;
typedef ScfRef< XclExpPalette > XclExpPaletteRef;
typedef ScfRef< XclExpFontBuffer > XclExpFontBfrRef;
typedef ScfRef< XclExpNumFmtBuffer > XclExpNumFmtBfrRef;
typedef ScfRef< XclExpXFBuffer > XclExpXFBfrRef;
typedef ScfRef< XclExpNameManager > XclExpNameMgrRef;
typedef ScfRef< XclExpLinkManager > XclExpLinkMgrRef;
typedef ScfRef< XclExpFilterManager > XclExpFilterMgrRef;
typedef ScfRef< XclExpPivotTableManager > XclExpPTableMgrRef;
XclExpTabInfoRef mxTabInfo; /// Calc->Excel sheet index conversion.
XclExpAddrConvRef mxAddrConv; /// The address converter.
XclExpFmlaCompRef mxFmlaComp; /// The formula compiler.
XclExpProgressRef mxProgress; /// The export progress bar.
XclExpSstRef mxSst; /// The shared string table.
XclExpPaletteRef mxPalette; /// The color buffer.
XclExpFontBfrRef mxFontBfr; /// All fonts in the file.
XclExpNumFmtBfrRef mxNumFmtBfr; /// All number formats in the file.
XclExpXFBfrRef mxXFBfr; /// All XF records in the file.
XclExpNameMgrRef mxNameMgr; /// Internal defined names.
XclExpLinkMgrRef mxGlobLinkMgr; /// Global link manager for defined names.
XclExpLinkMgrRef mxLocLinkMgr; /// Local link manager for a sheet.
XclExpFilterMgrRef mxFilterMgr; /// Manager for filtered areas in all sheets.
XclExpPTableMgrRef mxPTableMgr; /// All pivot tables and pivot caches.
bool mbRelUrl; /// true = Store URLs relative.
explicit XclExpRootData( XclBiff eBiff, SfxMedium& rMedium,
SotStorageRef xRootStrg, ScDocument& rDoc, CharSet eCharSet );
virtual ~XclExpRootData();
};
// ----------------------------------------------------------------------------
/** Access to global data from other classes. */
class XclExpRoot : public XclRoot
{
public:
explicit XclExpRoot( XclExpRootData& rExpRootData );
/** 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 buffer for Calc->Excel sheet index conversion. */
XclExpTabInfo& GetTabInfo() const;
/** Returns the address converter. */
XclExpAddressConverter& GetAddressConverter() const;
/** Returns the formula compiler to produce formula token arrays. */
XclExpFormulaCompiler& GetFormulaCompiler() const;
/** Returns the export progress bar. */
XclExpProgressBar& GetProgressBar() const;
/** 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 global link manager for defined names. */
XclExpLinkManager& GetGlobalLinkManager() const;
/** Returns the local link manager for the current sheet. */
XclExpLinkManager& GetLocalLinkManager() const;
/** Returns the buffer that contains internal defined names. */
XclExpNameManager& GetNameManager() const;
/** Returns the filter manager. */
XclExpFilterManager& GetFilterManager() const;
/** Returns the pivot table manager. */
XclExpPivotTableManager& GetPivotTableManager() const;
/** Is called when export filter starts to create the Excel document (all BIFF versions). */
void InitializeConvert();
/** Is called when export filter starts to create the workbook global data (>=BIFF5). */
void InitializeGlobals();
/** Is called when export filter starts to create data for a single sheet (all BIFF versions). */
void InitializeTable( SCTAB nScTab );
/** Is called before export filter starts to write the records to the stream. */
void InitializeSave();
/** Returns the reference to a record (or record list) representing a root object.
@param nRecId Identifier that specifies which record is returned. */
XclExpRecordRef CreateRecord( sal_uInt16 nRecId ) const;
private:
/** Returns the local or global link manager, depending on current context. */
XclExpRootData::XclExpLinkMgrRef GetLocalLinkMgrRef() const;
private:
mutable XclExpRootData& mrExpData; /// Reference to the global export data struct.
};
// ============================================================================
#endif
<commit_msg>INTEGRATION: CWS dr51 (1.19.92); FILE MERGED 2006/11/08 09:30:36 dr 1.19.92.1: #i71033# use app-font text encoding if CODEPAGE is missing, remane 'CharSet' -> 'rtl_TextEncoding'<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: xeroot.hxx,v $
*
* $Revision: 1.20 $
*
* last change: $Author: ihi $ $Date: 2006-12-19 13:24:06 $
*
* 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_XEROOT_HXX
#define SC_XEROOT_HXX
#ifndef SC_XLROOT_HXX
#include "xlroot.hxx"
#endif
// Forward declarations of objects in public use ==============================
class XclExpStream;
class XclExpRecordBase;
class XclExpString;
typedef ScfRef< XclExpRecordBase > XclExpRecordRef;
typedef ScfRef< XclExpString > XclExpStringRef;
// Global data ================================================================
class XclExpTabInfo;
class XclExpAddressConverter;
class XclExpFormulaCompiler;
class XclExpProgressBar;
class XclExpSst;
class XclExpPalette;
class XclExpFontBuffer;
class XclExpNumFmtBuffer;
class XclExpXFBuffer;
class XclExpLinkManager;
class XclExpNameManager;
class XclExpFilterManager;
class XclExpPivotTableManager;
/** Stores global buffers and data needed for Excel export filter. */
struct XclExpRootData : public XclRootData
{
typedef ScfRef< XclExpTabInfo > XclExpTabInfoRef;
typedef ScfRef< XclExpAddressConverter > XclExpAddrConvRef;
typedef ScfRef< XclExpFormulaCompiler > XclExpFmlaCompRef;
typedef ScfRef< XclExpProgressBar > XclExpProgressRef;
typedef ScfRef< XclExpSst > XclExpSstRef;
typedef ScfRef< XclExpPalette > XclExpPaletteRef;
typedef ScfRef< XclExpFontBuffer > XclExpFontBfrRef;
typedef ScfRef< XclExpNumFmtBuffer > XclExpNumFmtBfrRef;
typedef ScfRef< XclExpXFBuffer > XclExpXFBfrRef;
typedef ScfRef< XclExpNameManager > XclExpNameMgrRef;
typedef ScfRef< XclExpLinkManager > XclExpLinkMgrRef;
typedef ScfRef< XclExpFilterManager > XclExpFilterMgrRef;
typedef ScfRef< XclExpPivotTableManager > XclExpPTableMgrRef;
XclExpTabInfoRef mxTabInfo; /// Calc->Excel sheet index conversion.
XclExpAddrConvRef mxAddrConv; /// The address converter.
XclExpFmlaCompRef mxFmlaComp; /// The formula compiler.
XclExpProgressRef mxProgress; /// The export progress bar.
XclExpSstRef mxSst; /// The shared string table.
XclExpPaletteRef mxPalette; /// The color buffer.
XclExpFontBfrRef mxFontBfr; /// All fonts in the file.
XclExpNumFmtBfrRef mxNumFmtBfr; /// All number formats in the file.
XclExpXFBfrRef mxXFBfr; /// All XF records in the file.
XclExpNameMgrRef mxNameMgr; /// Internal defined names.
XclExpLinkMgrRef mxGlobLinkMgr; /// Global link manager for defined names.
XclExpLinkMgrRef mxLocLinkMgr; /// Local link manager for a sheet.
XclExpFilterMgrRef mxFilterMgr; /// Manager for filtered areas in all sheets.
XclExpPTableMgrRef mxPTableMgr; /// All pivot tables and pivot caches.
bool mbRelUrl; /// true = Store URLs relative.
explicit XclExpRootData( XclBiff eBiff, SfxMedium& rMedium,
SotStorageRef xRootStrg, ScDocument& rDoc, rtl_TextEncoding eTextEnc );
virtual ~XclExpRootData();
};
// ----------------------------------------------------------------------------
/** Access to global data from other classes. */
class XclExpRoot : public XclRoot
{
public:
explicit XclExpRoot( XclExpRootData& rExpRootData );
/** 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 buffer for Calc->Excel sheet index conversion. */
XclExpTabInfo& GetTabInfo() const;
/** Returns the address converter. */
XclExpAddressConverter& GetAddressConverter() const;
/** Returns the formula compiler to produce formula token arrays. */
XclExpFormulaCompiler& GetFormulaCompiler() const;
/** Returns the export progress bar. */
XclExpProgressBar& GetProgressBar() const;
/** 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 global link manager for defined names. */
XclExpLinkManager& GetGlobalLinkManager() const;
/** Returns the local link manager for the current sheet. */
XclExpLinkManager& GetLocalLinkManager() const;
/** Returns the buffer that contains internal defined names. */
XclExpNameManager& GetNameManager() const;
/** Returns the filter manager. */
XclExpFilterManager& GetFilterManager() const;
/** Returns the pivot table manager. */
XclExpPivotTableManager& GetPivotTableManager() const;
/** Is called when export filter starts to create the Excel document (all BIFF versions). */
void InitializeConvert();
/** Is called when export filter starts to create the workbook global data (>=BIFF5). */
void InitializeGlobals();
/** Is called when export filter starts to create data for a single sheet (all BIFF versions). */
void InitializeTable( SCTAB nScTab );
/** Is called before export filter starts to write the records to the stream. */
void InitializeSave();
/** Returns the reference to a record (or record list) representing a root object.
@param nRecId Identifier that specifies which record is returned. */
XclExpRecordRef CreateRecord( sal_uInt16 nRecId ) const;
private:
/** Returns the local or global link manager, depending on current context. */
XclExpRootData::XclExpLinkMgrRef GetLocalLinkMgrRef() const;
private:
mutable XclExpRootData& mrExpData; /// Reference to the global export data struct.
};
// ============================================================================
#endif
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: tbinsert.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: nn $ $Date: 2002-05-29 18:10: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): _______________________________________
*
*
************************************************************************/
// System - Includes -----------------------------------------------------
#include <string> // HACK: prevent conflict between STLPORT and Workshop headers
#ifdef PCH
#include "ui_pch.hxx"
#endif
#pragma hdrstop
// INCLUDE ---------------------------------------------------------------
#include <tools/shl.hxx>
#include <svtools/intitem.hxx>
#include <sfx2/dispatch.hxx>
#include <sfx2/dispatch.hxx>
#include "tbinsert.hxx"
#include "tbinsert.hrc"
#include "global.hxx"
#include "scmod.hxx"
#include "scresid.hxx"
#include "sc.hrc"
// -----------------------------------------------------------------------
SFX_IMPL_TOOLBOX_CONTROL( ScTbxInsertCtrl, SfxUInt16Item);
//------------------------------------------------------------------
//
// ToolBox - Controller
//
//------------------------------------------------------------------
ScTbxInsertCtrl::ScTbxInsertCtrl( USHORT nId, ToolBox& rTbx, SfxBindings& rBind ) :
SfxToolBoxControl( nId, rTbx, rBind ),
nLastSlotId(0)
{
}
__EXPORT ScTbxInsertCtrl::~ScTbxInsertCtrl()
{
}
void __EXPORT ScTbxInsertCtrl::StateChanged( USHORT nSID, SfxItemState eState,
const SfxPoolItem* pState )
{
GetToolBox().EnableItem( GetId(), (GetItemState(pState) != SFX_ITEM_DISABLED) );
if( eState == SFX_ITEM_AVAILABLE )
{
const SfxUInt16Item* pItem = PTR_CAST( SfxUInt16Item, pState );
if(pItem)
{
nLastSlotId = pItem->GetValue();
USHORT nImageId = nLastSlotId ? nLastSlotId : GetId();
Image aImage = GetBindings().GetImageManager()->GetImage( nImageId,
GetToolBox().GetDisplayBackground().GetColor().IsDark(),
SC_MOD() );
GetToolBox().SetItemImage(GetId(), aImage);
}
}
}
SfxPopupWindow* __EXPORT ScTbxInsertCtrl::CreatePopupWindow()
{
USHORT nWinResId, nTbxResId;
USHORT nSlotId = GetId();
if (nSlotId == SID_TBXCTL_INSERT)
{
nWinResId = RID_TBXCTL_INSERT;
nTbxResId = RID_TOOLBOX_INSERT;
}
else if (nSlotId == SID_TBXCTL_INSCELLS)
{
nWinResId = RID_TBXCTL_INSCELLS;
nTbxResId = RID_TOOLBOX_INSCELLS;
}
else /* SID_TBXCTL_INSOBJ */
{
nWinResId = RID_TBXCTL_INSOBJ;
nTbxResId = RID_TOOLBOX_INSOBJ;
}
WindowAlign eNewAlign = ( GetToolBox().IsHorizontal() ) ? WINDOWALIGN_LEFT : WINDOWALIGN_TOP;
ScTbxInsertPopup *pWin = new ScTbxInsertPopup( nSlotId, eNewAlign,
ScResId(nWinResId), ScResId(nTbxResId), GetBindings() );
pWin->StartPopupMode(&GetToolBox(), TRUE);
pWin->StartSelection();
pWin->Show();
return pWin;
}
SfxPopupWindowType __EXPORT ScTbxInsertCtrl::GetPopupWindowType() const
{
return nLastSlotId ? SFX_POPUPWINDOW_ONTIMEOUT : SFX_POPUPWINDOW_ONCLICK;
}
void __EXPORT ScTbxInsertCtrl::Select( BOOL bMod1 )
{
if (nLastSlotId)
GetBindings().GetDispatcher()->Execute(nLastSlotId);
}
//------------------------------------------------------------------
//
// Popup - Window
//
//------------------------------------------------------------------
ScTbxInsertPopup::ScTbxInsertPopup( USHORT nId, WindowAlign eNewAlign,
const ResId& rRIdWin, const ResId& rRIdTbx,
SfxBindings& rBindings ) :
SfxPopupWindow ( nId, rRIdWin, rBindings),
aTbx ( this, GetBindings(), rRIdTbx ),
aRIdWinTemp(rRIdWin),
aRIdTbxTemp(rRIdTbx)
{
aTbx.UseDefault();
FreeResource();
aTbx.GetToolBox().SetAlign( eNewAlign );
if (eNewAlign == WINDOWALIGN_LEFT || eNewAlign == WINDOWALIGN_RIGHT)
SetText( EMPTY_STRING );
Size aSize = aTbx.CalcWindowSizePixel();
aTbx.SetPosSizePixel( Point(), aSize );
SetOutputSizePixel( aSize );
aTbx.GetToolBox().SetSelectHdl( LINK(this, ScTbxInsertPopup, TbxSelectHdl));
aTbxClickHdl = aTbx.GetToolBox().GetClickHdl();
aTbx.GetToolBox().SetClickHdl( LINK(this, ScTbxInsertPopup, TbxClickHdl));
}
ScTbxInsertPopup::~ScTbxInsertPopup()
{
}
SfxPopupWindow* __EXPORT ScTbxInsertPopup::Clone() const
{
return new ScTbxInsertPopup( GetId(), aTbx.GetToolBox().GetAlign(),
aRIdWinTemp, aRIdTbxTemp,
(SfxBindings&) GetBindings() );
}
void ScTbxInsertPopup::StartSelection()
{
aTbx.GetToolBox().StartSelection();
}
IMPL_LINK(ScTbxInsertPopup, TbxSelectHdl, ToolBox*, pBox)
{
EndPopupMode();
USHORT nLastSlotId = pBox->GetCurItemId();
SfxUInt16Item aItem( GetId(), nLastSlotId );
SfxDispatcher* pDisp = GetBindings().GetDispatcher();
pDisp->Execute( GetId(), SFX_CALLMODE_SYNCHRON, &aItem, 0L );
pDisp->Execute( nLastSlotId, SFX_CALLMODE_ASYNCHRON );
return 0;
}
IMPL_LINK(ScTbxInsertPopup, TbxClickHdl, ToolBox*, pBox)
{
USHORT nLastSlotId = pBox->GetCurItemId();
SfxUInt16Item aItem( GetId(), nLastSlotId );
GetBindings().GetDispatcher()->Execute( GetId(), SFX_CALLMODE_SYNCHRON, &aItem, 0L );
if(aTbxClickHdl.IsSet())
aTbxClickHdl.Call(pBox);
return 0;
}
void __EXPORT ScTbxInsertPopup::PopupModeEnd()
{
aTbx.GetToolBox().EndSelection();
SfxPopupWindow::PopupModeEnd();
}
<commit_msg>INTEGRATION: CWS docking1 (1.4.408); FILE MERGED 2004/05/05 16:17:45 cd 1.4.408.2: #i26252# Fixed wrong item type for some slots and added state slots for CTL and vertical text 2004/04/25 05:43:31 cd 1.4.408.1: #i26252# Transition of toolbar controllers<commit_after>/*************************************************************************
*
* $RCSfile: tbinsert.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: obo $ $Date: 2004-07-06 12:53:48 $
*
* 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): _______________________________________
*
*
************************************************************************/
// System - Includes -----------------------------------------------------
#include <string> // HACK: prevent conflict between STLPORT and Workshop headers
#ifdef PCH
#include "ui_pch.hxx"
#endif
#pragma hdrstop
// INCLUDE ---------------------------------------------------------------
#include <tools/shl.hxx>
#include <svtools/intitem.hxx>
#include <sfx2/dispatch.hxx>
#include <sfx2/dispatch.hxx>
#include <sfx2/viewsh.hxx>
#include <sfx2/viewfrm.hxx>
#include <sfx2/imagemgr.hxx>
#include "tbinsert.hxx"
#include "tbinsert.hrc"
#include "global.hxx"
#include "scmod.hxx"
#include "scresid.hxx"
#include "sc.hrc"
// -----------------------------------------------------------------------
SFX_IMPL_TOOLBOX_CONTROL( ScTbxInsertCtrl, SfxUInt16Item);
//------------------------------------------------------------------
//
// ToolBox - Controller
//
//------------------------------------------------------------------
ScTbxInsertCtrl::ScTbxInsertCtrl( USHORT nSlotId, USHORT nId, ToolBox& rTbx ) :
SfxToolBoxControl( nSlotId, nId, rTbx ),
nLastSlotId(0)
{
rTbx.SetItemBits( nId, TIB_DROPDOWN | rTbx.GetItemBits( nId ) );
}
__EXPORT ScTbxInsertCtrl::~ScTbxInsertCtrl()
{
}
void __EXPORT ScTbxInsertCtrl::StateChanged( USHORT nSID, SfxItemState eState,
const SfxPoolItem* pState )
{
GetToolBox().EnableItem( GetId(), (GetItemState(pState) != SFX_ITEM_DISABLED) );
if( eState == SFX_ITEM_AVAILABLE )
{
const SfxUInt16Item* pItem = PTR_CAST( SfxUInt16Item, pState );
if(pItem)
{
nLastSlotId = pItem->GetValue();
USHORT nImageId = nLastSlotId ? nLastSlotId : GetSlotId();
rtl::OUString aSlotURL( RTL_CONSTASCII_USTRINGPARAM( "slot:" ));
aSlotURL += rtl::OUString::valueOf( sal_Int32( nImageId ));
Image aImage = GetImage( m_xFrame,
aSlotURL,
hasBigImages(),
GetToolBox().GetDisplayBackground().GetColor().IsDark() );
/*
Image aImage = GetBindings().GetImageManager()->GetImage( nImageId,
GetToolBox().GetDisplayBackground().GetColor().IsDark(),
SC_MOD() );
*/
GetToolBox().SetItemImage(GetId(), aImage);
}
}
}
SfxPopupWindow* __EXPORT ScTbxInsertCtrl::CreatePopupWindow()
{
USHORT nWinResId, nTbxResId;
USHORT nSlotId = GetSlotId();
if (nSlotId == SID_TBXCTL_INSERT)
{
rtl::OUString aInsertBarResStr( RTL_CONSTASCII_USTRINGPARAM( "private:resource/toolbar/insertbar" ));
createAndPositionSubToolBar( aInsertBarResStr );
// nWinResId = RID_TBXCTL_INSERT;
// nTbxResId = RID_TOOLBOX_INSERT;
}
else if (nSlotId == SID_TBXCTL_INSCELLS)
{
rtl::OUString aInsertCellsBarResStr( RTL_CONSTASCII_USTRINGPARAM( "private:resource/toolbar/insertcellsbar" ));
createAndPositionSubToolBar( aInsertCellsBarResStr );
// nWinResId = RID_TBXCTL_INSCELLS;
// nTbxResId = RID_TOOLBOX_INSCELLS;
}
else /* SID_TBXCTL_INSOBJ */
{
rtl::OUString aInsertObjectBarResStr( RTL_CONSTASCII_USTRINGPARAM( "private:resource/toolbar/insertobjectbar" ));
createAndPositionSubToolBar( aInsertObjectBarResStr );
// nWinResId = RID_TBXCTL_INSOBJ;
// nTbxResId = RID_TOOLBOX_INSOBJ;
}
/*
WindowAlign eNewAlign = ( GetToolBox().IsHorizontal() ) ? WINDOWALIGN_LEFT : WINDOWALIGN_TOP;
ScTbxInsertPopup *pWin = new ScTbxInsertPopup( nSlotId, eNewAlign,
ScResId(nWinResId), ScResId(nTbxResId), GetBindings() );
pWin->StartPopupMode(&GetToolBox(), TRUE);
pWin->StartSelection();
pWin->Show();
return pWin;
*/
return NULL;
}
SfxPopupWindowType __EXPORT ScTbxInsertCtrl::GetPopupWindowType() const
{
return nLastSlotId ? SFX_POPUPWINDOW_ONTIMEOUT : SFX_POPUPWINDOW_ONCLICK;
}
void __EXPORT ScTbxInsertCtrl::Select( BOOL bMod1 )
{
SfxViewShell* pCurSh( SfxViewShell::Current() );
SfxDispatcher* pDispatch( 0 );
if ( pCurSh )
{
SfxViewFrame* pViewFrame = pCurSh->GetViewFrame();
if ( pViewFrame )
pDispatch = pViewFrame->GetDispatcher();
}
if ( pDispatch )
pDispatch->Execute(nLastSlotId);
}
/*
//------------------------------------------------------------------
//
// Popup - Window
//
//------------------------------------------------------------------
ScTbxInsertPopup::ScTbxInsertPopup( USHORT nId, WindowAlign eNewAlign,
const ResId& rRIdWin, const ResId& rRIdTbx,
SfxBindings& rBindings ) :
SfxPopupWindow ( nId, rRIdWin, rBindings),
aTbx ( this, GetBindings(), rRIdTbx ),
aRIdWinTemp(rRIdWin),
aRIdTbxTemp(rRIdTbx)
{
aTbx.UseDefault();
FreeResource();
aTbx.GetToolBox().SetAlign( eNewAlign );
if (eNewAlign == WINDOWALIGN_LEFT || eNewAlign == WINDOWALIGN_RIGHT)
SetText( EMPTY_STRING );
Size aSize = aTbx.CalcWindowSizePixel();
aTbx.SetPosSizePixel( Point(), aSize );
SetOutputSizePixel( aSize );
aTbx.GetToolBox().SetSelectHdl( LINK(this, ScTbxInsertPopup, TbxSelectHdl));
aTbxClickHdl = aTbx.GetToolBox().GetClickHdl();
aTbx.GetToolBox().SetClickHdl( LINK(this, ScTbxInsertPopup, TbxClickHdl));
}
ScTbxInsertPopup::~ScTbxInsertPopup()
{
}
SfxPopupWindow* __EXPORT ScTbxInsertPopup::Clone() const
{
return new ScTbxInsertPopup( GetId(), aTbx.GetToolBox().GetAlign(),
aRIdWinTemp, aRIdTbxTemp,
(SfxBindings&) GetBindings() );
}
void ScTbxInsertPopup::StartSelection()
{
aTbx.GetToolBox().StartSelection();
}
IMPL_LINK(ScTbxInsertPopup, TbxSelectHdl, ToolBox*, pBox)
{
EndPopupMode();
USHORT nLastSlotId = pBox->GetCurItemId();
SfxUInt16Item aItem( GetId(), nLastSlotId );
SfxDispatcher* pDisp = GetBindings().GetDispatcher();
pDisp->Execute( GetId(), SFX_CALLMODE_SYNCHRON, &aItem, 0L );
pDisp->Execute( nLastSlotId, SFX_CALLMODE_ASYNCHRON );
return 0;
}
IMPL_LINK(ScTbxInsertPopup, TbxClickHdl, ToolBox*, pBox)
{
USHORT nLastSlotId = pBox->GetCurItemId();
SfxUInt16Item aItem( GetId(), nLastSlotId );
GetBindings().GetDispatcher()->Execute( GetId(), SFX_CALLMODE_SYNCHRON, &aItem, 0L );
if(aTbxClickHdl.IsSet())
aTbxClickHdl.Call(pBox);
return 0;
}
void __EXPORT ScTbxInsertPopup::PopupModeEnd()
{
aTbx.GetToolBox().EndSelection();
SfxPopupWindow::PopupModeEnd();
}
*/
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: pszctrl.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: kz $ $Date: 2005-01-21 15:10:18 $
*
* 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 _SVX_PSZCTRL_HXX
#define _SVX_PSZCTRL_HXX
// include ---------------------------------------------------------------
#ifndef _SFXSTBITEM_HXX //autogen
#include <sfx2/stbitem.hxx>
#endif
#ifndef INCLUDED_SVXDLLAPI_H
#include "svx/svxdllapi.h"
#endif
// forward ---------------------------------------------------------------
class SvxSizeItem;
struct SvxPosSizeStatusBarControl_Impl;
// class SvxPosSizeToolBoxControl ----------------------------------------
class SVX_DLLPUBLIC SvxPosSizeStatusBarControl : public SfxStatusBarControl
{
private:
SvxPosSizeStatusBarControl_Impl* pImp;
public:
SFX_DECL_STATUSBAR_CONTROL();
SvxPosSizeStatusBarControl( USHORT nSlotId, USHORT nId, StatusBar& rStb );
~SvxPosSizeStatusBarControl();
virtual void StateChanged( USHORT nSID, SfxItemState eState, const SfxPoolItem* pState );
virtual void Paint( const UserDrawEvent& rEvt );
virtual void Command( const CommandEvent& rCEvt );
static ULONG GetDefItemWidth( const StatusBar& rStb );
};
#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.3.430); FILE MERGED 2005/09/05 14:16:01 rt 1.3.430.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: pszctrl.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2005-09-08 18:22:48 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _SVX_PSZCTRL_HXX
#define _SVX_PSZCTRL_HXX
// include ---------------------------------------------------------------
#ifndef _SFXSTBITEM_HXX //autogen
#include <sfx2/stbitem.hxx>
#endif
#ifndef INCLUDED_SVXDLLAPI_H
#include "svx/svxdllapi.h"
#endif
// forward ---------------------------------------------------------------
class SvxSizeItem;
struct SvxPosSizeStatusBarControl_Impl;
// class SvxPosSizeToolBoxControl ----------------------------------------
class SVX_DLLPUBLIC SvxPosSizeStatusBarControl : public SfxStatusBarControl
{
private:
SvxPosSizeStatusBarControl_Impl* pImp;
public:
SFX_DECL_STATUSBAR_CONTROL();
SvxPosSizeStatusBarControl( USHORT nSlotId, USHORT nId, StatusBar& rStb );
~SvxPosSizeStatusBarControl();
virtual void StateChanged( USHORT nSID, SfxItemState eState, const SfxPoolItem* pState );
virtual void Paint( const UserDrawEvent& rEvt );
virtual void Command( const CommandEvent& rCEvt );
static ULONG GetDefItemWidth( const StatusBar& rStb );
};
#endif
<|endoftext|>
|
<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used 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. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qmessageaccountsortorder.h"
#include "qmessageaccountsortorder_p.h"
QTM_BEGIN_NAMESPACE
QMessageAccountSortOrderPrivate::QMessageAccountSortOrderPrivate(QMessageAccountSortOrder *sortOrder)
: q_ptr(sortOrder)
{
}
bool QMessageAccountSortOrderPrivate::lessThan(const QMessageAccountSortOrder &sortOrder,
const QMessageAccount &account1, const QMessageAccount &account2)
{
QMessageAccountSortOrderPrivate *d(sortOrder.d_ptr);
if (d && d->_order == Qt::AscendingOrder) { // Hack preventing null ointer
return (account1.name().compare(account2.name(), Qt::CaseInsensitive) < 0);
}
return (account1.name().compare(account2.name(), Qt::CaseInsensitive) > 0);
}
QMessageAccountSortOrder::QMessageAccountSortOrder()
: d_ptr(0)
{
}
QMessageAccountSortOrder::QMessageAccountSortOrder(const QMessageAccountSortOrder &other)
: d_ptr(new QMessageAccountSortOrderPrivate(this))
{
this->operator=(other);
}
QMessageAccountSortOrder::~QMessageAccountSortOrder()
{
delete d_ptr;
d_ptr = 0;
}
bool QMessageAccountSortOrder::isEmpty() const
{
return (d_ptr == 0);
}
bool QMessageAccountSortOrder::isSupported() const
{
return true;
}
bool QMessageAccountSortOrder::operator==(const QMessageAccountSortOrder& other) const
{
if (!d_ptr && !other.d_ptr) {
return true;
}
if (!d_ptr || !other.d_ptr) {
return false;
}
return (d_ptr->_order == other.d_ptr->_order);
}
QMessageAccountSortOrder& QMessageAccountSortOrder::operator=(const QMessageAccountSortOrder& other)
{
if (&other != this) {
if (!d_ptr) {
d_ptr = new QMessageAccountSortOrderPrivate(this);
}
d_ptr->_order = other.d_ptr->_order;
}
return *this;
}
QMessageAccountSortOrder QMessageAccountSortOrder::byName(Qt::SortOrder order)
{
QMessageAccountSortOrder sortOrder;
sortOrder.d_ptr = new QMessageAccountSortOrderPrivate(&sortOrder);
sortOrder.d_ptr->_order = order;
return sortOrder;
}
QTM_END_NAMESPACE
<commit_msg>Fix: MOBILITY-1589 Crash when using QMessageAccountSortOrder copy constructor<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used 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. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qmessageaccountsortorder.h"
#include "qmessageaccountsortorder_p.h"
QTM_BEGIN_NAMESPACE
QMessageAccountSortOrderPrivate::QMessageAccountSortOrderPrivate(QMessageAccountSortOrder *sortOrder)
: q_ptr(sortOrder)
{
}
bool QMessageAccountSortOrderPrivate::lessThan(const QMessageAccountSortOrder &sortOrder,
const QMessageAccount &account1, const QMessageAccount &account2)
{
QMessageAccountSortOrderPrivate *d(sortOrder.d_ptr);
if (d && d->_order == Qt::AscendingOrder) { // Hack preventing null ointer
return (account1.name().compare(account2.name(), Qt::CaseInsensitive) < 0);
}
return (account1.name().compare(account2.name(), Qt::CaseInsensitive) > 0);
}
QMessageAccountSortOrder::QMessageAccountSortOrder()
: d_ptr(0)
{
}
QMessageAccountSortOrder::QMessageAccountSortOrder(const QMessageAccountSortOrder &other)
: d_ptr(new QMessageAccountSortOrderPrivate(this))
{
this->operator=(other);
}
QMessageAccountSortOrder::~QMessageAccountSortOrder()
{
delete d_ptr;
d_ptr = 0;
}
bool QMessageAccountSortOrder::isEmpty() const
{
return (d_ptr == 0);
}
bool QMessageAccountSortOrder::isSupported() const
{
return true;
}
bool QMessageAccountSortOrder::operator==(const QMessageAccountSortOrder& other) const
{
if (!d_ptr && !other.d_ptr) {
return true;
}
if (!d_ptr || !other.d_ptr) {
return false;
}
return (d_ptr->_order == other.d_ptr->_order);
}
QMessageAccountSortOrder& QMessageAccountSortOrder::operator=(const QMessageAccountSortOrder& other)
{
if (&other != this) {
if (!other.d_ptr) {
delete d_ptr;
d_ptr = 0;
} else {
if (!d_ptr) {
d_ptr = new QMessageAccountSortOrderPrivate(this);
}
d_ptr->_order = other.d_ptr->_order;
}
}
return *this;
}
QMessageAccountSortOrder QMessageAccountSortOrder::byName(Qt::SortOrder order)
{
QMessageAccountSortOrder sortOrder;
sortOrder.d_ptr = new QMessageAccountSortOrderPrivate(&sortOrder);
sortOrder.d_ptr->_order = order;
return sortOrder;
}
QTM_END_NAMESPACE
<|endoftext|>
|
<commit_before>//
// File: overlap_integral.cc
// Author: James L
// calculates overlap integrals for molecular orbitals using libmoo
// usage:
// overlap_integral --coord1 <coordinate file for mol1>
// --coord2 <coordinate file for mol2>
// --listcrg <xml file containing the definition for the charge unit type>
//
//
#include <boost/program_options.hpp>
#include <string>
#include <jcalc.h>
#include <crgunit.h>
using namespace std;
int main(int argc, char **argv) {
// catches the exceptions if the program does not behave
// feenableexcept(FE_DIVBYZERO | FE_OVERFLOW | FE_INVALID);
// parser for the program arguments
namespace po = boost::program_options;
// declare the supported options
po::options_description desc("Allowed options");
string listcrg, pos1, pos2;
desc.add_options()
("help,h", "produce help message")
("listcharges,l", po::value<string > (&listcrg)-> default_value("list_charges.xml"), "xml filename containing the list of the charge unit type")
("posor1,1", po::value<string > (&pos1) -> default_value("posmol1"), "list of charge unit type, position and orientation for mol 1")
("posor2,2", po::value<string > (&pos2) -> default_value("posmol2"), " list of charge unit type, position and orientation for mol 2")
;
po::variables_map vm;
try {
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
} catch (po::error &err) {
cout << "error parsing command line: " << err.what() << endl;
return -1;
}
if (vm.count("help")) {
//help_text();
cout << desc << endl;
return 0;
}
try {
cout << "Reading Crg unit Types" << endl;
JCalc jcalc(listcrg);
cout << "Finished reading Crg unit Types" << endl;
ifstream in1(pos1.c_str());
ifstream in2(pos2.c_str());
while (in1 && in2) {
string name1, name2;
vec com1;
vec com2;
matrix or1;
matrix or2;
in1 >> name1 >> com1.x() >> com1.y() >> com1.z() >>
or1[0][0] >> or1[0][1] >> or1[0][2] >>
or1[1][0] >> or1[1][1] >> or1[1][2] >>
or1[2][0] >> or1[2][1] >> or1[2][2];
in2 >> name2 >> com2.x() >> com2.y() >> com2.z() >>
or2[0][0] >> or2[0][1] >> or2[0][2] >>
or2[1][0] >> or2[1][1] >> or2[1][2] >>
or2[2][0] >> or2[2][1] >> or2[2][2];
if (!in1 || !in2) break;
// cout << "mol1: " << name1 << com1 << or1<<endl;
// cout << "mol2: " << name2 << com2 << or2<<endl;
CrgUnit * A = jcalc.CreateCrgUnit(0, name1);
CrgUnit * B = jcalc.CreateCrgUnit(1, name2);
A->SetPos(0, com1);
B->SetPos(0, com2);
A->SetNorm(0, or1[2]);
A->SetPlane(0, or1[1]);
B->SetNorm(0, or2[2]);
B->SetPlane(0, or2[1]);
// cout << "Compute J" <<endl;
vector <double> Js = jcalc.CalcJ(*A, *B);
// cout << "Finished computing J" <<endl;
vector <double>::iterator itJ = Js.begin();
for (; itJ != Js.end(); ++itJ) cout << '\t' << *itJ << endl;
}
} catch (std::exception &err) {
cout << "error : " << err.what() << endl;
return -1;
}
}
<commit_msg>Added option for writing pdb file of used positions and configurations<commit_after>//
// File: overlap_integral.cc
// Author: James L
// calculates overlap integrals for molecular orbitals using libmoo
// usage:
// overlap_integral --coord1 <coordinate file for mol1>
// --coord2 <coordinate file for mol2>
// --listcrg <xml file containing the definition for the charge unit type>
//
//
#include <boost/program_options.hpp>
#include <string>
#include <jcalc.h>
#include <crgunit.h>
using namespace std;
int main(int argc, char **argv) {
// catches the exceptions if the program does not behave
// feenableexcept(FE_DIVBYZERO | FE_OVERFLOW | FE_INVALID);
// parser for the program arguments
namespace po = boost::program_options;
// declare the supported options
po::options_description desc("Allowed options");
string listcrg, pos1, pos2, pdbfile;
desc.add_options()
("help,h", "produce help message")
("listcharges,l", po::value<string > (&listcrg)-> default_value("list_charges.xml"), "xml filename containing the list of the charge unit type")
("posor1,1", po::value<string > (&pos1) -> default_value("posmol1"), "list of charge unit type, position and orientation for mol 1")
("posor2,2", po::value<string > (&pos2) -> default_value("posmol2"), "list of charge unit type, position and orientation for mol 2")
("pdb,p", po::value<string > (&pdbfile) -> default_value("posmol.pdb"), "write pdb file with used molecule positions and orientations")
;
po::variables_map vm;
try {
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
} catch (po::error &err) {
cout << "error parsing command line: " << err.what() << endl;
return -1;
}
if (vm.count("help")) {
//help_text();
cout << desc << endl;
return 0;
}
try {
cout << "Reading Crg unit Types" << endl;
JCalc jcalc(listcrg);
cout << "Finished reading Crg unit Types" << endl;
ifstream in1(pos1.c_str());
ifstream in2(pos2.c_str());
int written=0;
while (in1 && in2) {
string name1, name2;
vec com1;
vec com2;
matrix or1;
matrix or2;
in1 >> name1 >> com1.x() >> com1.y() >> com1.z() >>
or1[0][0] >> or1[0][1] >> or1[0][2] >>
or1[1][0] >> or1[1][1] >> or1[1][2] >>
or1[2][0] >> or1[2][1] >> or1[2][2];
in2 >> name2 >> com2.x() >> com2.y() >> com2.z() >>
or2[0][0] >> or2[0][1] >> or2[0][2] >>
or2[1][0] >> or2[1][1] >> or2[1][2] >>
or2[2][0] >> or2[2][1] >> or2[2][2];
if (!in1 || !in2) break;
// cout << "mol1: " << name1 << com1 << or1<<endl;
// cout << "mol2: " << name2 << com2 << or2<<endl;
CrgUnit * A = jcalc.CreateCrgUnit(0, name1);
CrgUnit * B = jcalc.CreateCrgUnit(1, name2);
A->SetPos(0, com1);
B->SetPos(0, com2);
A->SetNorm(0, or1[2]);
A->SetPlane(0, or1[1]);
B->SetNorm(0, or2[2]);
B->SetPlane(0, or2[1]);
//write pdb file
mol_and_orb *molecule = ( A -> rotate_translate_beads() );
(*molecule).write_pdb(pdbfile, "m1", written++);
delete molecule;
molecule = ( B -> rotate_translate_beads() );
(*molecule).write_pdb(pdbfile, "m2", written++);
delete molecule;
ofstream fl;
fl.open(pdbfile.c_str(), ios::app);
fl.setf(ios::fixed);
fl << "END" <<endl;
// cout << "Compute J" <<endl;
vector <double> Js = jcalc.CalcJ(*A, *B);
// cout << "Finished computing J" <<endl;
vector <double>::iterator itJ = Js.begin();
for (; itJ != Js.end(); ++itJ) cout << '\t' << *itJ << endl;
}
} catch (std::exception &err) {
cout << "error : " << err.what() << endl;
return -1;
}
}
<|endoftext|>
|
<commit_before>/****************************************************************************
*
* Copyright (C) 2015 Mark Charlebois. All rights reserved.
* Author: @author Mark Charlebois <charlebm#gmail.com>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/**
* @file px4_posix_tasks.c
* Implementation of existing task API for Linux
*/
#include <px4_log.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <stdbool.h>
#include <signal.h>
#include <fcntl.h>
#include <sched.h>
#include <unistd.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <string>
#include <px4_tasks.h>
#include <px4_posix.h>
#define MAX_CMD_LEN 100
#define PX4_MAX_TASKS 50
#define SHELL_TASK_ID (PX4_MAX_TASKS+1)
pthread_t _shell_task_id = 0;
pthread_mutex_t task_mutex = PTHREAD_MUTEX_INITIALIZER;
struct task_entry {
pthread_t pid;
std::string name;
bool isused;
task_entry() : isused(false) {}
};
static task_entry taskmap[PX4_MAX_TASKS] = {};
typedef struct {
px4_main_t entry;
const char* name;
int argc;
char *argv[];
// strings are allocated after the
} pthdata_t;
static void *entry_adapter(void *ptr)
{
pthdata_t *data = (pthdata_t *) ptr;
int rv;
// set the threads name
#ifdef __PX4_DARWIN
rv = pthread_setname_np(data->name);
#else
rv = pthread_setname_np(pthread_self(), data->name);
#endif
if (rv) {
PX4_ERR("px4_task_spawn_cmd: failed to set name of thread %d %d\n", rv, errno);
}
data->entry(data->argc, data->argv);
free(ptr);
PX4_DEBUG("Before px4_task_exit");
px4_task_exit(0);
PX4_DEBUG("After px4_task_exit");
return NULL;
}
void
px4_systemreset(bool to_bootloader)
{
PX4_WARN("Called px4_system_reset");
exit(0);
}
px4_task_t px4_task_spawn_cmd(const char *name, int scheduler, int priority, int stack_size, px4_main_t entry,
char *const argv[])
{
int rv;
int argc = 0;
int i;
unsigned int len = 0;
unsigned long offset;
unsigned long structsize;
char *p = (char *)argv;
pthread_attr_t attr;
struct sched_param param = {};
// Calculate argc
while (p != (char *)0) {
p = argv[argc];
if (p == (char *)0) {
break;
}
++argc;
len += strlen(p) + 1;
}
structsize = sizeof(pthdata_t) + (argc + 1) * sizeof(char *);
// not safe to pass stack data to the thread creation
pthdata_t *taskdata = (pthdata_t *)malloc(structsize + len);
memset(taskdata, 0, structsize + len);
offset = ((unsigned long)taskdata) + structsize;
taskdata->name = name;
taskdata->entry = entry;
taskdata->argc = argc;
for (i = 0; i < argc; i++) {
PX4_DEBUG("arg %d %s\n", i, argv[i]);
taskdata->argv[i] = (char *)offset;
strcpy((char *)offset, argv[i]);
offset += strlen(argv[i]) + 1;
}
// Must add NULL at end of argv
taskdata->argv[argc] = (char *)0;
PX4_DEBUG("starting task %s", name);
rv = pthread_attr_init(&attr);
if (rv != 0) {
PX4_WARN("px4_task_spawn_cmd: failed to init thread attrs");
return (rv < 0) ? rv : -rv;
}
rv = pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED);
if (rv != 0) {
PX4_WARN("px4_task_spawn_cmd: failed to set inherit sched");
return (rv < 0) ? rv : -rv;
}
rv = pthread_attr_setschedpolicy(&attr, scheduler);
if (rv != 0) {
PX4_WARN("px4_task_spawn_cmd: failed to set sched policy");
return (rv < 0) ? rv : -rv;
}
param.sched_priority = priority;
rv = pthread_attr_setschedparam(&attr, ¶m);
if (rv != 0) {
PX4_WARN("px4_task_spawn_cmd: failed to set sched param");
return (rv < 0) ? rv : -rv;
}
pthread_mutex_lock(&task_mutex);
int taskid = 0;
for (i = 0; i < PX4_MAX_TASKS; ++i) {
if (taskmap[i].isused == false) {
taskmap[i].name = name;
taskmap[i].isused = true;
taskid = i;
break;
}
}
rv = pthread_create(&taskmap[taskid].pid, &attr, &entry_adapter, (void *) taskdata);
if (rv != 0) {
if (rv == EPERM) {
//printf("WARNING: NOT RUNING AS ROOT, UNABLE TO RUN REALTIME THREADS\n");
rv = pthread_create(&taskmap[taskid].pid, NULL, &entry_adapter, (void *) taskdata);
if (rv != 0) {
PX4_ERR("px4_task_spawn_cmd: failed to create thread %d %d\n", rv, errno);
taskmap[taskid].isused = false;
return (rv < 0) ? rv : -rv;
}
} else {
return (rv < 0) ? rv : -rv;
}
}
pthread_mutex_unlock(&task_mutex);
if (i >= PX4_MAX_TASKS) {
return -ENOSPC;
}
return i;
}
int px4_task_delete(px4_task_t id)
{
int rv = 0;
pthread_t pid;
PX4_DEBUG("Called px4_task_delete");
if (id < PX4_MAX_TASKS && taskmap[id].isused) {
pid = taskmap[id].pid;
} else {
return -EINVAL;
}
pthread_mutex_lock(&task_mutex);
// If current thread then exit, otherwise cancel
if (pthread_self() == pid) {
taskmap[id].isused = false;
pthread_mutex_unlock(&task_mutex);
pthread_exit(0);
} else {
rv = pthread_cancel(pid);
}
taskmap[id].isused = false;
pthread_mutex_unlock(&task_mutex);
return rv;
}
void px4_task_exit(int ret)
{
int i;
pthread_t pid = pthread_self();
// Get pthread ID from the opaque ID
for (i = 0; i < PX4_MAX_TASKS; ++i) {
if (taskmap[i].pid == pid) {
pthread_mutex_lock(&task_mutex);
taskmap[i].isused = false;
break;
}
}
if (i >= PX4_MAX_TASKS) {
PX4_ERR("px4_task_exit: self task not found!");
} else {
PX4_DEBUG("px4_task_exit: %s", taskmap[i].name.c_str());
}
pthread_mutex_unlock(&task_mutex);
pthread_exit((void *)(unsigned long)ret);
}
int px4_task_kill(px4_task_t id, int sig)
{
int rv = 0;
pthread_t pid;
PX4_DEBUG("Called px4_task_kill %d", sig);
if (id < PX4_MAX_TASKS && taskmap[id].isused && taskmap[id].pid != 0) {
pthread_mutex_lock(&task_mutex);
pid = taskmap[id].pid;
pthread_mutex_unlock(&task_mutex);
} else {
return -EINVAL;
}
// If current thread then exit, otherwise cancel
rv = pthread_kill(pid, sig);
return rv;
}
void px4_show_tasks()
{
int idx;
int count = 0;
PX4_INFO("Active Tasks:");
for (idx = 0; idx < PX4_MAX_TASKS; idx++) {
if (taskmap[idx].isused) {
PX4_INFO(" %-10s %lu", taskmap[idx].name.c_str(), (unsigned long)taskmap[idx].pid);
count++;
}
}
if (count == 0) {
PX4_INFO(" No running tasks");
}
}
bool px4_task_is_running(const char *taskname)
{
int idx;
for (idx = 0; idx < PX4_MAX_TASKS; idx++) {
if (taskmap[idx].isused && (strcmp(taskmap[idx].name.c_str(), taskname) == 0)) {
return true;
}
}
return false;
}
__BEGIN_DECLS
unsigned long px4_getpid()
{
return (unsigned long)pthread_self();
}
const char *getprogname();
const char *getprogname()
{
pthread_t pid = pthread_self();
for (int i = 0; i < PX4_MAX_TASKS; i++) {
if (taskmap[i].isused && taskmap[i].pid == pid) {
pthread_mutex_lock(&task_mutex);
return taskmap[i].name.c_str();
pthread_mutex_unlock(&task_mutex);
}
}
return "Unknown App";
}
__END_DECLS
<commit_msg>posix tasks: Add px4_prctl() call<commit_after>/****************************************************************************
*
* Copyright (C) 2015 Mark Charlebois. All rights reserved.
* Author: @author Mark Charlebois <charlebm#gmail.com>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/**
* @file px4_posix_tasks.c
* Implementation of existing task API for Linux
*/
#include <px4_log.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <stdbool.h>
#include <signal.h>
#include <fcntl.h>
#include <sched.h>
#include <unistd.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <string>
#include <px4_tasks.h>
#include <px4_posix.h>
#define MAX_CMD_LEN 100
#define PX4_MAX_TASKS 50
#define SHELL_TASK_ID (PX4_MAX_TASKS+1)
pthread_t _shell_task_id = 0;
pthread_mutex_t task_mutex = PTHREAD_MUTEX_INITIALIZER;
struct task_entry {
pthread_t pid;
std::string name;
bool isused;
task_entry() : isused(false) {}
};
static task_entry taskmap[PX4_MAX_TASKS] = {};
typedef struct {
px4_main_t entry;
const char* name;
int argc;
char *argv[];
// strings are allocated after the
} pthdata_t;
static void *entry_adapter(void *ptr)
{
pthdata_t *data = (pthdata_t *) ptr;
int rv;
// set the threads name
#ifdef __PX4_DARWIN
rv = pthread_setname_np(data->name);
#else
rv = pthread_setname_np(pthread_self(), data->name);
#endif
if (rv) {
PX4_ERR("px4_task_spawn_cmd: failed to set name of thread %d %d\n", rv, errno);
}
data->entry(data->argc, data->argv);
free(ptr);
PX4_DEBUG("Before px4_task_exit");
px4_task_exit(0);
PX4_DEBUG("After px4_task_exit");
return NULL;
}
void
px4_systemreset(bool to_bootloader)
{
PX4_WARN("Called px4_system_reset");
exit(0);
}
px4_task_t px4_task_spawn_cmd(const char *name, int scheduler, int priority, int stack_size, px4_main_t entry,
char *const argv[])
{
int rv;
int argc = 0;
int i;
unsigned int len = 0;
unsigned long offset;
unsigned long structsize;
char *p = (char *)argv;
pthread_attr_t attr;
struct sched_param param = {};
// Calculate argc
while (p != (char *)0) {
p = argv[argc];
if (p == (char *)0) {
break;
}
++argc;
len += strlen(p) + 1;
}
structsize = sizeof(pthdata_t) + (argc + 1) * sizeof(char *);
// not safe to pass stack data to the thread creation
pthdata_t *taskdata = (pthdata_t *)malloc(structsize + len);
memset(taskdata, 0, structsize + len);
offset = ((unsigned long)taskdata) + structsize;
taskdata->name = name;
taskdata->entry = entry;
taskdata->argc = argc;
for (i = 0; i < argc; i++) {
PX4_DEBUG("arg %d %s\n", i, argv[i]);
taskdata->argv[i] = (char *)offset;
strcpy((char *)offset, argv[i]);
offset += strlen(argv[i]) + 1;
}
// Must add NULL at end of argv
taskdata->argv[argc] = (char *)0;
PX4_DEBUG("starting task %s", name);
rv = pthread_attr_init(&attr);
if (rv != 0) {
PX4_WARN("px4_task_spawn_cmd: failed to init thread attrs");
return (rv < 0) ? rv : -rv;
}
rv = pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED);
if (rv != 0) {
PX4_WARN("px4_task_spawn_cmd: failed to set inherit sched");
return (rv < 0) ? rv : -rv;
}
rv = pthread_attr_setschedpolicy(&attr, scheduler);
if (rv != 0) {
PX4_WARN("px4_task_spawn_cmd: failed to set sched policy");
return (rv < 0) ? rv : -rv;
}
param.sched_priority = priority;
rv = pthread_attr_setschedparam(&attr, ¶m);
if (rv != 0) {
PX4_WARN("px4_task_spawn_cmd: failed to set sched param");
return (rv < 0) ? rv : -rv;
}
pthread_mutex_lock(&task_mutex);
int taskid = 0;
for (i = 0; i < PX4_MAX_TASKS; ++i) {
if (taskmap[i].isused == false) {
taskmap[i].name = name;
taskmap[i].isused = true;
taskid = i;
break;
}
}
rv = pthread_create(&taskmap[taskid].pid, &attr, &entry_adapter, (void *) taskdata);
if (rv != 0) {
if (rv == EPERM) {
//printf("WARNING: NOT RUNING AS ROOT, UNABLE TO RUN REALTIME THREADS\n");
rv = pthread_create(&taskmap[taskid].pid, NULL, &entry_adapter, (void *) taskdata);
if (rv != 0) {
PX4_ERR("px4_task_spawn_cmd: failed to create thread %d %d\n", rv, errno);
taskmap[taskid].isused = false;
return (rv < 0) ? rv : -rv;
}
} else {
return (rv < 0) ? rv : -rv;
}
}
pthread_mutex_unlock(&task_mutex);
if (i >= PX4_MAX_TASKS) {
return -ENOSPC;
}
return i;
}
int px4_task_delete(px4_task_t id)
{
int rv = 0;
pthread_t pid;
PX4_DEBUG("Called px4_task_delete");
if (id < PX4_MAX_TASKS && taskmap[id].isused) {
pid = taskmap[id].pid;
} else {
return -EINVAL;
}
pthread_mutex_lock(&task_mutex);
// If current thread then exit, otherwise cancel
if (pthread_self() == pid) {
taskmap[id].isused = false;
pthread_mutex_unlock(&task_mutex);
pthread_exit(0);
} else {
rv = pthread_cancel(pid);
}
taskmap[id].isused = false;
pthread_mutex_unlock(&task_mutex);
return rv;
}
void px4_task_exit(int ret)
{
int i;
pthread_t pid = pthread_self();
// Get pthread ID from the opaque ID
for (i = 0; i < PX4_MAX_TASKS; ++i) {
if (taskmap[i].pid == pid) {
pthread_mutex_lock(&task_mutex);
taskmap[i].isused = false;
break;
}
}
if (i >= PX4_MAX_TASKS) {
PX4_ERR("px4_task_exit: self task not found!");
} else {
PX4_DEBUG("px4_task_exit: %s", taskmap[i].name.c_str());
}
pthread_mutex_unlock(&task_mutex);
pthread_exit((void *)(unsigned long)ret);
}
int px4_task_kill(px4_task_t id, int sig)
{
int rv = 0;
pthread_t pid;
PX4_DEBUG("Called px4_task_kill %d", sig);
if (id < PX4_MAX_TASKS && taskmap[id].isused && taskmap[id].pid != 0) {
pthread_mutex_lock(&task_mutex);
pid = taskmap[id].pid;
pthread_mutex_unlock(&task_mutex);
} else {
return -EINVAL;
}
// If current thread then exit, otherwise cancel
rv = pthread_kill(pid, sig);
return rv;
}
void px4_show_tasks()
{
int idx;
int count = 0;
PX4_INFO("Active Tasks:");
for (idx = 0; idx < PX4_MAX_TASKS; idx++) {
if (taskmap[idx].isused) {
PX4_INFO(" %-10s %lu", taskmap[idx].name.c_str(), (unsigned long)taskmap[idx].pid);
count++;
}
}
if (count == 0) {
PX4_INFO(" No running tasks");
}
}
bool px4_task_is_running(const char *taskname)
{
int idx;
for (idx = 0; idx < PX4_MAX_TASKS; idx++) {
if (taskmap[idx].isused && (strcmp(taskmap[idx].name.c_str(), taskname) == 0)) {
return true;
}
}
return false;
}
__BEGIN_DECLS
unsigned long px4_getpid()
{
return (unsigned long)pthread_self();
}
const char *getprogname();
const char *getprogname()
{
pthread_t pid = pthread_self();
for (int i = 0; i < PX4_MAX_TASKS; i++) {
if (taskmap[i].isused && taskmap[i].pid == pid) {
pthread_mutex_lock(&task_mutex);
return taskmap[i].name.c_str();
pthread_mutex_unlock(&task_mutex);
}
}
return "Unknown App";
}
int px4_prctl(int option, const char* arg2, unsigned pid)
{
int rv;
switch (option) {
case PR_SET_NAME:
// set the threads name
#ifdef __PX4_DARWIN
rv = pthread_setname_np(arg2);
#else
rv = pthread_setname_np(pthread_self(), arg2);
#endif
break;
default:
rv = -1;
PX4_WARN("FAILED SETTING TASK NAME");
break;
}
return rv;
}
__END_DECLS
<|endoftext|>
|
<commit_before>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2012 Utku Aydın <utkuaydin34@gmail.com>
//
#include "FoursquareModel.h"
#include "FoursquarePlugin.h"
#include "FoursquareItem.h"
#include "MarbleGlobal.h"
#include "MarbleModel.h"
#include "GeoDataCoordinates.h"
#include "GeoDataLatLonAltBox.h"
#include "MarbleDebug.h"
#include <QDebug>
#include <QtCore/QUrl>
#include <QtScript/QScriptEngine>
#include <QtScript/QScriptValue>
#include <QtScript/QScriptValueIterator>
namespace Marble
{
FoursquareModel::FoursquareModel(const PluginManager* pluginManager, QObject* parent)
: AbstractDataPluginModel("foursquare", pluginManager, parent)
{
// Enjoy laziness
}
FoursquareModel::~FoursquareModel()
{
}
void FoursquareModel::getAdditionalItems( const GeoDataLatLonAltBox& box, const MarbleModel *model, qint32 number )
{
if( model->planetId() != "earth" ) {
return;
}
QString clientId = "YPRWSYFW1RVL4PJQ2XS5G14RTOGTHOKZVHC1EP5KCCCYQPZF";
QString clientSecret = "5L2JDCAYQCEJWY5FNDU4A1RWATE4E5FIIXXRM41YBTFSERUH";
QString apiUrl( "https://api.foursquare.com/v2/venues/search" );
apiUrl += "?ll=" + QString::number( box.center().latitude(Marble::GeoDataCoordinates::Degree) );
apiUrl += "," + QString::number( box.center().longitude(Marble::GeoDataCoordinates::Degree) );
apiUrl += "&client_id=" + clientId;
apiUrl += "&client_secret=" + clientSecret;
apiUrl += "&v=20120601";
downloadDescriptionFile( QUrl( apiUrl ) );
}
void FoursquareModel::parseFile( const QByteArray& file )
{
QScriptValue data;
QScriptEngine engine;
// Qt requires parentheses around JSON
data = engine.evaluate( "(" + QString( file ) + ")" );
data = data.property("response");
// Parse if any result exists
if ( data.property( "venues" ).isArray() ) {
QScriptValueIterator iterator( data.property( "venues" ) );
// Add items to the list
do {
iterator.next();
QString id = iterator.value().property( "id" ).toString(); qDebug() << id;
QString name = iterator.value().property( "name" ).toString(); qDebug() << name;
double latitude = iterator.value().property( "location" ).property( "lat" ).toString().toDouble(); qDebug() << latitude;
double longitude = iterator.value().property( "location" ).property( "lng" ).toString().toDouble(); qDebug() << longitude;
int usersCount = iterator.value().property( "stats" ).property( "usersCount" ).toInteger();
if( !itemExists( id ) ) {
GeoDataCoordinates coordinates( longitude, latitude, 0.0, GeoDataCoordinates::Degree );
FoursquareItem *item = new FoursquareItem( this );
item->setId( id );
item->setCoordinate( coordinates );
item->setTarget( "earth" );
item->setName( name );
item->setUsersCount( usersCount );
addItemToList( item );
}
}
while ( iterator.hasNext() );
}
}
}
#include "FoursquareModel.moc"<commit_msg>Fix encoding<commit_after>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2012 Utku Aydın <utkuaydin34@gmail.com>
//
#include "FoursquareModel.h"
#include "FoursquarePlugin.h"
#include "FoursquareItem.h"
#include "MarbleGlobal.h"
#include "MarbleModel.h"
#include "GeoDataCoordinates.h"
#include "GeoDataLatLonAltBox.h"
#include "MarbleDebug.h"
#include <QDebug>
#include <QtCore/QUrl>
#include <QtScript/QScriptEngine>
#include <QtScript/QScriptValue>
#include <QtScript/QScriptValueIterator>
namespace Marble
{
FoursquareModel::FoursquareModel(const PluginManager* pluginManager, QObject* parent)
: AbstractDataPluginModel("foursquare", pluginManager, parent)
{
// Enjoy laziness
}
FoursquareModel::~FoursquareModel()
{
}
void FoursquareModel::getAdditionalItems( const GeoDataLatLonAltBox& box, const MarbleModel *model, qint32 number )
{
if( model->planetId() != "earth" ) {
return;
}
QString clientId = "YPRWSYFW1RVL4PJQ2XS5G14RTOGTHOKZVHC1EP5KCCCYQPZF";
QString clientSecret = "5L2JDCAYQCEJWY5FNDU4A1RWATE4E5FIIXXRM41YBTFSERUH";
QString apiUrl( "https://api.foursquare.com/v2/venues/search" );
apiUrl += "?ll=" + QString::number( box.center().latitude(Marble::GeoDataCoordinates::Degree) );
apiUrl += "," + QString::number( box.center().longitude(Marble::GeoDataCoordinates::Degree) );
apiUrl += "&client_id=" + clientId;
apiUrl += "&client_secret=" + clientSecret;
apiUrl += "&v=20120601";
downloadDescriptionFile( QUrl( apiUrl ) );
}
void FoursquareModel::parseFile( const QByteArray& file )
{
QScriptValue data;
QScriptEngine engine;
// Qt requires parentheses around JSON
data = engine.evaluate( "(" + QString::fromUtf8( file ) + ")" );
data = data.property("response");
// Parse if any result exists
if ( data.property( "venues" ).isArray() ) {
QScriptValueIterator iterator( data.property( "venues" ) );
// Add items to the list
do {
iterator.next();
QString id = iterator.value().property( "id" ).toString(); qDebug() << id;
QString name = iterator.value().property( "name" ).toString(); qDebug() << name;
double latitude = iterator.value().property( "location" ).property( "lat" ).toString().toDouble(); qDebug() << latitude;
double longitude = iterator.value().property( "location" ).property( "lng" ).toString().toDouble(); qDebug() << longitude;
int usersCount = iterator.value().property( "stats" ).property( "usersCount" ).toInteger();
if( !itemExists( id ) ) {
GeoDataCoordinates coordinates( longitude, latitude, 0.0, GeoDataCoordinates::Degree );
FoursquareItem *item = new FoursquareItem( this );
item->setId( id );
item->setCoordinate( coordinates );
item->setTarget( "earth" );
item->setName( name );
item->setUsersCount( usersCount );
addItemToList( item );
}
}
while ( iterator.hasNext() );
}
}
}
#include "FoursquareModel.moc"
<|endoftext|>
|
<commit_before>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2008 Torsten Rahn <tackat@kde.org>
//
#include "MapScaleFloatItem.h"
#include <QtCore/QRect>
#include <QtGui/QPixmap>
#include <QtGui/QApplication>
#include <QtGui/QPushButton>
#include <QtGui/QMenu>
#include <QtGui/QToolTip>
#include "ui_MapScaleConfigWidget.h"
#include "MarbleDebug.h"
#include "global.h"
#include "Projections/AbstractProjection.h"
#include "MarbleLocale.h"
#include "MarbleDataFacade.h"
#include "GeoPainter.h"
#include "ViewportParams.h"
namespace Marble
{
MapScaleFloatItem::MapScaleFloatItem( const QPointF &point, const QSizeF &size )
: AbstractFloatItem( point, size ),
m_aboutDialog(0),
m_configDialog(0),
m_radius(0),
m_invScale(0.0),
m_target(QString()),
m_leftBarMargin(0),
m_rightBarMargin(0),
m_scaleBarWidth(0),
m_viewportWidth(0),
m_scaleBarHeight(5),
m_scaleBarDistance(0.0),
m_bestDivisor(0),
m_pixelInterval(0),
m_valueInterval(0),
m_unit(tr("km")),
m_scaleInitDone( false ),
m_showRatioScale( false )
{
bool const smallScreen = MarbleGlobal::getInstance()->profiles() & MarbleGlobal::SmallScreen;
if ( smallScreen ) {
setPosition( QPointF( 220.0, 10.5 ) );
}
}
MapScaleFloatItem::~MapScaleFloatItem()
{
}
QStringList MapScaleFloatItem::backendTypes() const
{
return QStringList( "mapscale" );
}
QString MapScaleFloatItem::name() const
{
return tr("Scale Bar");
}
QString MapScaleFloatItem::guiString() const
{
return tr("&Scale Bar");
}
QString MapScaleFloatItem::nameId() const
{
return QString( "scalebar" );
}
QString MapScaleFloatItem::description() const
{
return tr("This is a float item that provides a map scale.");}
QIcon MapScaleFloatItem::icon () const
{
return QIcon();
}
void MapScaleFloatItem::initialize ()
{
}
bool MapScaleFloatItem::isInitialized () const
{
return true;
}
QDialog *MapScaleFloatItem::aboutDialog()
{
if ( !m_aboutDialog ) {
// Initializing about dialog
m_aboutDialog = new PluginAboutDialog();
m_aboutDialog->setName( "Scale Bar Plugin" );
m_aboutDialog->setVersion( "0.2" );
// FIXME: Can we store this string for all of Marble
m_aboutDialog->setAboutText( tr( "<br />(c) 2009, 2010 The Marble Project<br /><br /><a href=\"http://edu.kde.org/marble\">http://edu.kde.org/marble</a>" ) );
QList<Author> authors;
Author rahn;
rahn.name = "Torsten Rahn";
rahn.task = tr( "Original Developer" );
rahn.email = "tackat@kde.org";
authors.append( rahn );
Author nhan;
nhan.name = "Khanh-Nhan Nguyen";
nhan.task = tr( "Developer" );
nhan.email = "khanh.nhan@wpi.edu";
authors.append( nhan );
m_aboutDialog->setAuthors( authors );
//TODO: add data text
// m_aboutDialog->setPixmap( m_icon.pixmap( 62, 53 ) );
}
return m_aboutDialog;
}
void MapScaleFloatItem::changeViewport( ViewportParams *viewport )
{
int viewportWidth = viewport->width();
QString target = dataFacade()->target();
if ( !( m_radius == viewport->radius()
&& viewportWidth == m_viewportWidth
&& m_target == target
&& m_scaleInitDone ) )
{
int fontHeight = QFontMetrics( font() ).ascent();
if (m_showRatioScale) {
setContentSize( QSizeF( viewport->width() / 2,
fontHeight + 3 + m_scaleBarHeight + fontHeight + 7 ) );
} else {
setContentSize( QSizeF( viewport->width() / 2,
fontHeight + 3 + m_scaleBarHeight ) );
}
m_leftBarMargin = QFontMetrics( font() ).boundingRect( "0" ).width() / 2;
m_rightBarMargin = QFontMetrics( font() ).boundingRect( "0000" ).width() / 2;
m_scaleBarWidth = contentSize().width() - m_leftBarMargin - m_rightBarMargin;
m_viewportWidth = viewport->width();
m_radius = viewport->radius();
m_scaleInitDone = true;
update();
}
}
void MapScaleFloatItem::paintContent( GeoPainter *painter,
ViewportParams *viewport,
const QString& renderPos,
GeoSceneLayer * layer )
{
Q_UNUSED( layer )
Q_UNUSED( renderPos )
painter->save();
painter->setRenderHint( QPainter::Antialiasing, true );
int fontHeight = QFontMetrics( font() ).ascent();
qreal pixel2Length = dataFacade()->planetRadius() /
(qreal)(viewport->radius());
if ( viewport->currentProjection()->surfaceType() == AbstractProjection::Cylindrical )
{
qreal centerLatitude = viewport->viewLatLonAltBox().center().latitude();
// For flat maps we calculate the length of the 90 deg section of the
// central latitude circle. For flat maps this distance matches
// the pixel based radius propertyy.
pixel2Length *= M_PI / 2 * cos( centerLatitude );
}
//calculate scale ratio
qreal displayMMPerPixel = 1.0 * painter->device()->widthMM() / painter->device()->width();
qreal ratio = pixel2Length / (displayMMPerPixel * MM2M);
//round ratio to 3 most significant digits, assume that ratio >= 1, otherwise it may display "1 : 0"
//i made this assumption because as the primary use case we dont need to zoom in that much
qreal power = 1;
int iRatio = (int)(ratio + 0.5); //round ratio to the nearest integer
while (iRatio >= 1000) {
iRatio /= 10;
power *= 10;
}
iRatio *= power;
m_ratioString.setNum(iRatio);
m_ratioString = m_ratioString = "1 : " + m_ratioString;
m_scaleBarDistance = (qreal)(m_scaleBarWidth) * pixel2Length;
DistanceUnit distanceUnit;
distanceUnit = MarbleGlobal::getInstance()->locale()->distanceUnit();
if ( distanceUnit == MilesFeet ) {
m_scaleBarDistance *= KM2MI;
}
calcScaleBar();
painter->setPen( QColor( Qt::darkGray ) );
painter->setBrush( QColor( Qt::darkGray ) );
painter->drawRect( m_leftBarMargin, fontHeight + 3,
m_scaleBarWidth,
m_scaleBarHeight );
painter->setPen( QColor( Qt::black ) );
painter->setBrush( QColor( Qt::white ) );
painter->drawRect( m_leftBarMargin, fontHeight + 3,
m_bestDivisor * m_pixelInterval, m_scaleBarHeight );
painter->setBrush( QColor( Qt::black ) );
QString intervalStr;
int lastStringEnds = 0;
int currentStringBegin = 0;
for ( int j = 0; j <= m_bestDivisor; j += 2 ) {
if ( j < m_bestDivisor )
painter->drawRect( m_leftBarMargin + j * m_pixelInterval,
fontHeight + 3, m_pixelInterval - 1,
m_scaleBarHeight );
DistanceUnit distanceUnit;
distanceUnit = MarbleGlobal::getInstance()->locale()->distanceUnit();
if ( distanceUnit == Meter ) {
if ( m_bestDivisor * m_valueInterval > 10000 ) {
m_unit = tr("km");
intervalStr.setNum( j * m_valueInterval / 1000 );
}
else {
m_unit = tr("m");
intervalStr.setNum( j * m_valueInterval );
}
}
else {
m_unit = "mi";
intervalStr.setNum( j * m_valueInterval / 1000 );
}
painter->setFont( font() );
if ( j == 0 ) {
painter->drawText( 0, fontHeight, "0 " + m_unit );
lastStringEnds = QFontMetrics( font() ).width( "0 " + m_unit );
continue;
}
if( j == m_bestDivisor ) {
currentStringBegin = ( j * m_pixelInterval
- QFontMetrics( font() ).boundingRect( intervalStr ).width() );
}
else {
currentStringBegin = ( j * m_pixelInterval
- QFontMetrics( font() ).width( intervalStr ) / 2 );
}
if ( lastStringEnds < currentStringBegin ) {
painter->drawText( currentStringBegin, fontHeight, intervalStr );
lastStringEnds = currentStringBegin + QFontMetrics( font() ).width( intervalStr );
}
}
int leftRatioIndent = m_leftBarMargin + (m_scaleBarWidth - QFontMetrics( font() ).width(m_ratioString) ) / 2;
painter->drawText( leftRatioIndent, fontHeight + 3 + m_scaleBarHeight + fontHeight + 5, m_ratioString );
painter->restore();
}
void MapScaleFloatItem::calcScaleBar()
{
qreal magnitude = 1;
// First we calculate the exact length of the whole area that is possibly
// available to the scalebar in kilometers
int magValue = (int)( m_scaleBarDistance );
// We calculate the two most significant digits of the km-scalebar-length
// and store them in magValue.
while ( magValue >= 100 ) {
magValue /= 10;
magnitude *= 10;
}
m_bestDivisor = 4;
int bestMagValue = 1;
for ( int i = 0; i < magValue; i++ ) {
// We try to find the lowest divisor between 4 and 8 that
// divides magValue without remainder.
for ( int j = 4; j < 9; j++ ) {
if ( ( magValue - i ) % j == 0 ) {
// We store the very first result we find and store
// m_bestDivisor and bestMagValue as a final result.
m_bestDivisor = j;
bestMagValue = magValue - i;
// Stop all for loops and end search
i = magValue;
j = 9;
}
}
// If magValue doesn't divide through values between 4 and 8
// (e.g. because it's a prime number) try again with magValue
// decreased by i.
}
m_pixelInterval = (int)( m_scaleBarWidth * (qreal)( bestMagValue )
/ (qreal)( magValue ) / m_bestDivisor );
m_valueInterval = (int)( bestMagValue * magnitude / m_bestDivisor );
}
QDialog *MapScaleFloatItem::configDialog()
{
if ( !m_configDialog ) {
// Initializing configuration dialog
m_configDialog = new QDialog();
ui_configWidget = new Ui::MapScaleConfigWidget;
ui_configWidget->setupUi( m_configDialog );
readSettings();
connect( ui_configWidget->m_buttonBox, SIGNAL( accepted() ),
SLOT( writeSettings() ) );
connect( ui_configWidget->m_buttonBox, SIGNAL( rejected() ),
SLOT( readSettings() ) );
QPushButton *applyButton = ui_configWidget->m_buttonBox->button( QDialogButtonBox::Apply );
connect( applyButton, SIGNAL( clicked()) ,
this, SLOT( writeSettings() ) );
}
return m_configDialog;
}
void MapScaleFloatItem::contextMenuEvent( QWidget *w, QContextMenuEvent *e )
{
QMenu menu;
QAction *toggleaction = menu.addAction( "&Ratio Scale",
this,
SLOT( toggleRatioScaleVisibility() ) );
toggleaction->setCheckable( true );
toggleaction->setChecked( m_showRatioScale );
menu.exec( w->mapToGlobal( e->pos() ) );
}
void MapScaleFloatItem::toolTipEvent( QHelpEvent *e )
{
QToolTip::showText( e->globalPos(), m_ratioString );
}
void MapScaleFloatItem::readSettings()
{
if ( !m_configDialog )
return;
if ( m_showRatioScale ) {
ui_configWidget->m_showRatioScaleCheckBox->setCheckState( Qt::Checked );
}
else {
ui_configWidget->m_showRatioScaleCheckBox->setCheckState( Qt::Unchecked );
}
}
void MapScaleFloatItem::writeSettings()
{
if ( ui_configWidget->m_showRatioScaleCheckBox->checkState() == Qt::Checked ) {
m_showRatioScale = true;
} else {
m_showRatioScale = false;
}
emit settingsChanged( nameId() );
}
void MapScaleFloatItem::toggleRatioScaleVisibility()
{
m_showRatioScale = !m_showRatioScale;
readSettings();
emit settingsChanged( nameId() );
}
}
Q_EXPORT_PLUGIN2(MapScaleFloatItem, Marble::MapScaleFloatItem)
#include "MapScaleFloatItem.moc"
<commit_msg>- Hotfix for the mile 0-precision bug of the scale bar reported by Mustali Dalal:<commit_after>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2008 Torsten Rahn <tackat@kde.org>
//
#include "MapScaleFloatItem.h"
#include <QtCore/QRect>
#include <QtGui/QPixmap>
#include <QtGui/QApplication>
#include <QtGui/QPushButton>
#include <QtGui/QMenu>
#include <QtGui/QToolTip>
#include "ui_MapScaleConfigWidget.h"
#include "MarbleDebug.h"
#include "global.h"
#include "Projections/AbstractProjection.h"
#include "MarbleLocale.h"
#include "MarbleDataFacade.h"
#include "GeoPainter.h"
#include "ViewportParams.h"
namespace Marble
{
MapScaleFloatItem::MapScaleFloatItem( const QPointF &point, const QSizeF &size )
: AbstractFloatItem( point, size ),
m_aboutDialog(0),
m_configDialog(0),
m_radius(0),
m_invScale(0.0),
m_target(QString()),
m_leftBarMargin(0),
m_rightBarMargin(0),
m_scaleBarWidth(0),
m_viewportWidth(0),
m_scaleBarHeight(5),
m_scaleBarDistance(0.0),
m_bestDivisor(0),
m_pixelInterval(0),
m_valueInterval(0),
m_unit(tr("km")),
m_scaleInitDone( false ),
m_showRatioScale( false )
{
bool const smallScreen = MarbleGlobal::getInstance()->profiles() & MarbleGlobal::SmallScreen;
if ( smallScreen ) {
setPosition( QPointF( 220.0, 10.5 ) );
}
}
MapScaleFloatItem::~MapScaleFloatItem()
{
}
QStringList MapScaleFloatItem::backendTypes() const
{
return QStringList( "mapscale" );
}
QString MapScaleFloatItem::name() const
{
return tr("Scale Bar");
}
QString MapScaleFloatItem::guiString() const
{
return tr("&Scale Bar");
}
QString MapScaleFloatItem::nameId() const
{
return QString( "scalebar" );
}
QString MapScaleFloatItem::description() const
{
return tr("This is a float item that provides a map scale.");}
QIcon MapScaleFloatItem::icon () const
{
return QIcon();
}
void MapScaleFloatItem::initialize ()
{
}
bool MapScaleFloatItem::isInitialized () const
{
return true;
}
QDialog *MapScaleFloatItem::aboutDialog()
{
if ( !m_aboutDialog ) {
// Initializing about dialog
m_aboutDialog = new PluginAboutDialog();
m_aboutDialog->setName( "Scale Bar Plugin" );
m_aboutDialog->setVersion( "0.2" );
// FIXME: Can we store this string for all of Marble
m_aboutDialog->setAboutText( tr( "<br />(c) 2009, 2010 The Marble Project<br /><br /><a href=\"http://edu.kde.org/marble\">http://edu.kde.org/marble</a>" ) );
QList<Author> authors;
Author rahn;
rahn.name = "Torsten Rahn";
rahn.task = tr( "Original Developer" );
rahn.email = "tackat@kde.org";
authors.append( rahn );
Author nhan;
nhan.name = "Khanh-Nhan Nguyen";
nhan.task = tr( "Developer" );
nhan.email = "khanh.nhan@wpi.edu";
authors.append( nhan );
m_aboutDialog->setAuthors( authors );
//TODO: add data text
// m_aboutDialog->setPixmap( m_icon.pixmap( 62, 53 ) );
}
return m_aboutDialog;
}
void MapScaleFloatItem::changeViewport( ViewportParams *viewport )
{
int viewportWidth = viewport->width();
QString target = dataFacade()->target();
if ( !( m_radius == viewport->radius()
&& viewportWidth == m_viewportWidth
&& m_target == target
&& m_scaleInitDone ) )
{
int fontHeight = QFontMetrics( font() ).ascent();
if (m_showRatioScale) {
setContentSize( QSizeF( viewport->width() / 2,
fontHeight + 3 + m_scaleBarHeight + fontHeight + 7 ) );
} else {
setContentSize( QSizeF( viewport->width() / 2,
fontHeight + 3 + m_scaleBarHeight ) );
}
m_leftBarMargin = QFontMetrics( font() ).boundingRect( "0" ).width() / 2;
m_rightBarMargin = QFontMetrics( font() ).boundingRect( "0000" ).width() / 2;
m_scaleBarWidth = contentSize().width() - m_leftBarMargin - m_rightBarMargin;
m_viewportWidth = viewport->width();
m_radius = viewport->radius();
m_scaleInitDone = true;
update();
}
}
void MapScaleFloatItem::paintContent( GeoPainter *painter,
ViewportParams *viewport,
const QString& renderPos,
GeoSceneLayer * layer )
{
Q_UNUSED( layer )
Q_UNUSED( renderPos )
painter->save();
painter->setRenderHint( QPainter::Antialiasing, true );
int fontHeight = QFontMetrics( font() ).ascent();
qreal pixel2Length = dataFacade()->planetRadius() /
(qreal)(viewport->radius());
if ( viewport->currentProjection()->surfaceType() == AbstractProjection::Cylindrical )
{
qreal centerLatitude = viewport->viewLatLonAltBox().center().latitude();
// For flat maps we calculate the length of the 90 deg section of the
// central latitude circle. For flat maps this distance matches
// the pixel based radius propertyy.
pixel2Length *= M_PI / 2 * cos( centerLatitude );
}
//calculate scale ratio
qreal displayMMPerPixel = 1.0 * painter->device()->widthMM() / painter->device()->width();
qreal ratio = pixel2Length / (displayMMPerPixel * MM2M);
//round ratio to 3 most significant digits, assume that ratio >= 1, otherwise it may display "1 : 0"
//i made this assumption because as the primary use case we dont need to zoom in that much
qreal power = 1;
int iRatio = (int)(ratio + 0.5); //round ratio to the nearest integer
while (iRatio >= 1000) {
iRatio /= 10;
power *= 10;
}
iRatio *= power;
m_ratioString.setNum(iRatio);
m_ratioString = m_ratioString = "1 : " + m_ratioString;
m_scaleBarDistance = (qreal)(m_scaleBarWidth) * pixel2Length;
DistanceUnit distanceUnit;
distanceUnit = MarbleGlobal::getInstance()->locale()->distanceUnit();
if ( distanceUnit == MilesFeet ) {
m_scaleBarDistance *= KM2MI;
}
calcScaleBar();
painter->setPen( QColor( Qt::darkGray ) );
painter->setBrush( QColor( Qt::darkGray ) );
painter->drawRect( m_leftBarMargin, fontHeight + 3,
m_scaleBarWidth,
m_scaleBarHeight );
painter->setPen( QColor( Qt::black ) );
painter->setBrush( QColor( Qt::white ) );
painter->drawRect( m_leftBarMargin, fontHeight + 3,
m_bestDivisor * m_pixelInterval, m_scaleBarHeight );
painter->setBrush( QColor( Qt::black ) );
QString intervalStr;
int lastStringEnds = 0;
int currentStringBegin = 0;
for ( int j = 0; j <= m_bestDivisor; j += 2 ) {
if ( j < m_bestDivisor )
painter->drawRect( m_leftBarMargin + j * m_pixelInterval,
fontHeight + 3, m_pixelInterval - 1,
m_scaleBarHeight );
DistanceUnit distanceUnit;
distanceUnit = MarbleGlobal::getInstance()->locale()->distanceUnit();
if ( distanceUnit == Meter ) {
if ( m_bestDivisor * m_valueInterval > 10000 ) {
m_unit = tr("km");
intervalStr.setNum( j * m_valueInterval / 1000 );
}
else {
m_unit = tr("m");
intervalStr.setNum( j * m_valueInterval );
}
}
else {
m_unit = tr("mi");
intervalStr.setNum( j * m_valueInterval / 1000 );
if ( m_bestDivisor * m_valueInterval > 3800 ) {
intervalStr.setNum( j * m_valueInterval / 1000 );
}
else {
intervalStr.setNum( qreal(j * m_valueInterval ) / 1000.0, 'f', 2 );
}
}
painter->setFont( font() );
if ( j == 0 ) {
painter->drawText( 0, fontHeight, "0 " + m_unit );
lastStringEnds = QFontMetrics( font() ).width( "0 " + m_unit );
continue;
}
if( j == m_bestDivisor ) {
currentStringBegin = ( j * m_pixelInterval
- QFontMetrics( font() ).boundingRect( intervalStr ).width() );
}
else {
currentStringBegin = ( j * m_pixelInterval
- QFontMetrics( font() ).width( intervalStr ) / 2 );
}
if ( lastStringEnds < currentStringBegin ) {
painter->drawText( currentStringBegin, fontHeight, intervalStr );
lastStringEnds = currentStringBegin + QFontMetrics( font() ).width( intervalStr );
}
}
int leftRatioIndent = m_leftBarMargin + (m_scaleBarWidth - QFontMetrics( font() ).width(m_ratioString) ) / 2;
painter->drawText( leftRatioIndent, fontHeight + 3 + m_scaleBarHeight + fontHeight + 5, m_ratioString );
painter->restore();
}
void MapScaleFloatItem::calcScaleBar()
{
qreal magnitude = 1;
// First we calculate the exact length of the whole area that is possibly
// available to the scalebar in kilometers
int magValue = (int)( m_scaleBarDistance );
// We calculate the two most significant digits of the km-scalebar-length
// and store them in magValue.
while ( magValue >= 100 ) {
magValue /= 10;
magnitude *= 10;
}
m_bestDivisor = 4;
int bestMagValue = 1;
for ( int i = 0; i < magValue; i++ ) {
// We try to find the lowest divisor between 4 and 8 that
// divides magValue without remainder.
for ( int j = 4; j < 9; j++ ) {
if ( ( magValue - i ) % j == 0 ) {
// We store the very first result we find and store
// m_bestDivisor and bestMagValue as a final result.
m_bestDivisor = j;
bestMagValue = magValue - i;
// Stop all for loops and end search
i = magValue;
j = 9;
}
}
// If magValue doesn't divide through values between 4 and 8
// (e.g. because it's a prime number) try again with magValue
// decreased by i.
}
m_pixelInterval = (int)( m_scaleBarWidth * (qreal)( bestMagValue )
/ (qreal)( magValue ) / m_bestDivisor );
m_valueInterval = (int)( bestMagValue * magnitude / m_bestDivisor );
}
QDialog *MapScaleFloatItem::configDialog()
{
if ( !m_configDialog ) {
// Initializing configuration dialog
m_configDialog = new QDialog();
ui_configWidget = new Ui::MapScaleConfigWidget;
ui_configWidget->setupUi( m_configDialog );
readSettings();
connect( ui_configWidget->m_buttonBox, SIGNAL( accepted() ),
SLOT( writeSettings() ) );
connect( ui_configWidget->m_buttonBox, SIGNAL( rejected() ),
SLOT( readSettings() ) );
QPushButton *applyButton = ui_configWidget->m_buttonBox->button( QDialogButtonBox::Apply );
connect( applyButton, SIGNAL( clicked()) ,
this, SLOT( writeSettings() ) );
}
return m_configDialog;
}
void MapScaleFloatItem::contextMenuEvent( QWidget *w, QContextMenuEvent *e )
{
QMenu menu;
QAction *toggleaction = menu.addAction( "&Ratio Scale",
this,
SLOT( toggleRatioScaleVisibility() ) );
toggleaction->setCheckable( true );
toggleaction->setChecked( m_showRatioScale );
menu.exec( w->mapToGlobal( e->pos() ) );
}
void MapScaleFloatItem::toolTipEvent( QHelpEvent *e )
{
QToolTip::showText( e->globalPos(), m_ratioString );
}
void MapScaleFloatItem::readSettings()
{
if ( !m_configDialog )
return;
if ( m_showRatioScale ) {
ui_configWidget->m_showRatioScaleCheckBox->setCheckState( Qt::Checked );
}
else {
ui_configWidget->m_showRatioScaleCheckBox->setCheckState( Qt::Unchecked );
}
}
void MapScaleFloatItem::writeSettings()
{
if ( ui_configWidget->m_showRatioScaleCheckBox->checkState() == Qt::Checked ) {
m_showRatioScale = true;
} else {
m_showRatioScale = false;
}
emit settingsChanged( nameId() );
}
void MapScaleFloatItem::toggleRatioScaleVisibility()
{
m_showRatioScale = !m_showRatioScale;
readSettings();
emit settingsChanged( nameId() );
}
}
Q_EXPORT_PLUGIN2(MapScaleFloatItem, Marble::MapScaleFloatItem)
#include "MapScaleFloatItem.moc"
<|endoftext|>
|
<commit_before>/****************************************************************************
**
** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtSensors module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used 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. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "generictiltsensor.h"
#include <QDebug>
#define _USE_MATH_DEFINES
#include <qmath.h>
char const * const GenericTiltSensor::id("generic.tilt");
GenericTiltSensor::GenericTiltSensor(QSensor *sensor)
: QSensorBackend(sensor)
, radAccuracy(M_PI / 180)
, pitch(0)
, roll(0)
, calibratedPitch(0)
, calibratedRoll(0)
{
accelerometer = new QAccelerometer(this);
accelerometer->addFilter(this);
accelerometer->connectToBackend();
setReading<QTiltReading>(&m_reading);
setDataRates(accelerometer);
}
void GenericTiltSensor::start()
{
accelerometer->setDataRate(sensor()->dataRate());
accelerometer->setAlwaysOn(sensor()->isAlwaysOn());
accelerometer->start();
if (!accelerometer->isActive())
sensorStopped();
if (accelerometer->isBusy())
sensorBusy();
}
void GenericTiltSensor::stop()
{
accelerometer->stop();
}
/*
Angle between Ground and X
| Ax |
pitch = arctan| ----------------------- |
| sqrt(Ay * Ay + Az * Az)|
*/
static inline qreal calcPitch(double Ax, double Ay, double Az)
{
return -qAtan2(Ax, sqrt(Ay * Ay + Az * Az));
}
/*
Angle between Ground and Y
| Ay |
roll = arctan| ----------------------- |
| sqrt(Ax * Ax + Az * Az)|
*/
static inline qreal calcRoll(double Ax, double Ay, double Az)
{
return qAtan2(Ay, (sqrt(Ax * Ax + Az * Az)));
}
void GenericTiltSensor::calibrate()
{
calibratedPitch = pitch;
calibratedRoll = roll;
}
static qreal rad2deg(qreal rad)
{
return rad / (2 * M_PI) * 360;
}
bool GenericTiltSensor::filter(QAccelerometerReading *reading)
{
/*
z y
| /
|/___ x
*/
qreal ax = reading->x();
qreal ay = reading->y();
qreal az = reading->z();
#ifdef LOGCALIBRATION
qDebug() << "------------ new value -----------";
qDebug() << "old _pitch: " << _pitch;
qDebug() << "old _roll: " << _roll;
qDebug() << "_calibratedPitch: " << _calibratedPitch;
qDebug() << "_calibratedRoll: " << _calibratedRoll;
#endif
pitch = calcPitch(ax, ay, az);
roll = calcRoll (ax, ay, az);
#ifdef LOGCALIBRATION
qDebug() << "_pitch: " << _pitch;
qDebug() << "_roll: " << _roll;
#endif
qreal xrot = roll - calibratedRoll;
qreal yrot = pitch - calibratedPitch;
//get angle beteen 0 and 180 or 0 -180
qreal aG = 1 * sin(xrot);
qreal aK = 1 * cos(xrot);
xrot = qAtan2(aG, aK);
if (xrot > M_PI_2)
xrot = M_PI - xrot;
else if (xrot < -M_PI_2)
xrot = -(M_PI + xrot);
aG = 1 * sin(yrot);
aK = 1 * cos(yrot);
yrot = qAtan2(aG, aK);
if (yrot > M_PI_2)
yrot = M_PI - yrot;
else if (yrot < -M_PI_2)
yrot = -(M_PI + yrot);
#ifdef LOGCALIBRATION
qDebug() << "new xrot: " << xrot;
qDebug() << "new yrot: " << yrot;
qDebug() << "----------------------------------";
#endif
qreal dxrot = rad2deg(xrot) - xRotation;
qreal dyrot = rad2deg(yrot) - yRotation;
if (dxrot < 0) dxrot = -dxrot;
if (dyrot < 0) dyrot = -dyrot;
bool setNewReading = false;
if (dxrot >= rad2deg(radAccuracy) || !sensor()->skipDuplicates()) {
xRotation = rad2deg(xrot);
setNewReading = true;
}
if (dyrot >= rad2deg(radAccuracy) || !sensor()->skipDuplicates()) {
yRotation = rad2deg(yrot);
setNewReading = true;
}
if (setNewReading || m_reading.timestamp() == 0) {
m_reading.setTimestamp(reading->timestamp());
m_reading.setXRotation(xRotation);
m_reading.setYRotation(yRotation);
newReadingAvailable();
}
return false;
}
bool GenericTiltSensor::isFeatureSupported(QSensor::Feature feature) const
{
return (feature == QSensor::SkipDuplicates);
}
<commit_msg>Initialize variables<commit_after>/****************************************************************************
**
** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtSensors module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used 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. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "generictiltsensor.h"
#include <QDebug>
#define _USE_MATH_DEFINES
#include <qmath.h>
char const * const GenericTiltSensor::id("generic.tilt");
GenericTiltSensor::GenericTiltSensor(QSensor *sensor)
: QSensorBackend(sensor)
, radAccuracy(M_PI / 180)
, pitch(0)
, roll(0)
, calibratedPitch(0)
, calibratedRoll(0)
, xRotation(0)
, yRotation(0)
{
accelerometer = new QAccelerometer(this);
accelerometer->addFilter(this);
accelerometer->connectToBackend();
setReading<QTiltReading>(&m_reading);
setDataRates(accelerometer);
}
void GenericTiltSensor::start()
{
accelerometer->setDataRate(sensor()->dataRate());
accelerometer->setAlwaysOn(sensor()->isAlwaysOn());
accelerometer->start();
if (!accelerometer->isActive())
sensorStopped();
if (accelerometer->isBusy())
sensorBusy();
}
void GenericTiltSensor::stop()
{
accelerometer->stop();
}
/*
Angle between Ground and X
| Ax |
pitch = arctan| ----------------------- |
| sqrt(Ay * Ay + Az * Az)|
*/
static inline qreal calcPitch(double Ax, double Ay, double Az)
{
return -qAtan2(Ax, sqrt(Ay * Ay + Az * Az));
}
/*
Angle between Ground and Y
| Ay |
roll = arctan| ----------------------- |
| sqrt(Ax * Ax + Az * Az)|
*/
static inline qreal calcRoll(double Ax, double Ay, double Az)
{
return qAtan2(Ay, (sqrt(Ax * Ax + Az * Az)));
}
void GenericTiltSensor::calibrate()
{
calibratedPitch = pitch;
calibratedRoll = roll;
}
static qreal rad2deg(qreal rad)
{
return rad / (2 * M_PI) * 360;
}
bool GenericTiltSensor::filter(QAccelerometerReading *reading)
{
/*
z y
| /
|/___ x
*/
qreal ax = reading->x();
qreal ay = reading->y();
qreal az = reading->z();
#ifdef LOGCALIBRATION
qDebug() << "------------ new value -----------";
qDebug() << "old _pitch: " << _pitch;
qDebug() << "old _roll: " << _roll;
qDebug() << "_calibratedPitch: " << _calibratedPitch;
qDebug() << "_calibratedRoll: " << _calibratedRoll;
#endif
pitch = calcPitch(ax, ay, az);
roll = calcRoll (ax, ay, az);
#ifdef LOGCALIBRATION
qDebug() << "_pitch: " << _pitch;
qDebug() << "_roll: " << _roll;
#endif
qreal xrot = roll - calibratedRoll;
qreal yrot = pitch - calibratedPitch;
//get angle beteen 0 and 180 or 0 -180
qreal aG = 1 * sin(xrot);
qreal aK = 1 * cos(xrot);
xrot = qAtan2(aG, aK);
if (xrot > M_PI_2)
xrot = M_PI - xrot;
else if (xrot < -M_PI_2)
xrot = -(M_PI + xrot);
aG = 1 * sin(yrot);
aK = 1 * cos(yrot);
yrot = qAtan2(aG, aK);
if (yrot > M_PI_2)
yrot = M_PI - yrot;
else if (yrot < -M_PI_2)
yrot = -(M_PI + yrot);
#ifdef LOGCALIBRATION
qDebug() << "new xrot: " << xrot;
qDebug() << "new yrot: " << yrot;
qDebug() << "----------------------------------";
#endif
qreal dxrot = rad2deg(xrot) - xRotation;
qreal dyrot = rad2deg(yrot) - yRotation;
if (dxrot < 0) dxrot = -dxrot;
if (dyrot < 0) dyrot = -dyrot;
bool setNewReading = false;
if (dxrot >= rad2deg(radAccuracy) || !sensor()->skipDuplicates()) {
xRotation = rad2deg(xrot);
setNewReading = true;
}
if (dyrot >= rad2deg(radAccuracy) || !sensor()->skipDuplicates()) {
yRotation = rad2deg(yrot);
setNewReading = true;
}
if (setNewReading || m_reading.timestamp() == 0) {
m_reading.setTimestamp(reading->timestamp());
m_reading.setXRotation(xRotation);
m_reading.setYRotation(yRotation);
newReadingAvailable();
}
return false;
}
bool GenericTiltSensor::isFeatureSupported(QSensor::Feature feature) const
{
return (feature == QSensor::SkipDuplicates);
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <fstream>
#include <cmath>
#include "TH1.h"
#include "TH2.h"
#include "TH3.h"
#include "TCanvas.h"
#include "TRandom3.h"
#include "TVector2.h"
#include "TVector3.h"
#include "TLorentzVector.h"
/* Simulated experiment is a K_L->PiPi decay (CP violating)*/
const double K_energy_average /*GeV*/ = 2; // Around the value of Cronin-Fitch experiment
const double K_energy_sigma /*GeV*/ = 0.5;
const double K_path_average /* m */ = 15.34;
const double K_mass /*GeV*/ = 0.497611;
const double Pi_mass /*GeV*/ = 0.139570; // charged pi
const double Pi_energy_cm = K_mass/2;
const double Pi_momentum_mod_cm = sqrt(Pi_energy_cm*Pi_energy_cm - Pi_mass*Pi_mass);
/* Detector coordinates */
const double z1 /* m */ = 200;
const double z2 /* m */ = 201;
const double z3 /* m */ = 250;
const double z4 /* m */ = 251;
/* Detector smearing */
const double dx /* m */ = 0.01;
const double dy /* m */ = 0.01;
/* dp kick - applied at the center of the field region */
const double z_drift /* m */ = z3-z2;
const double z_kick /* m */ = (z2+z3)/2;
const double p_kick /* GeV */ = 1e-5*z_drift;
/* Plots constants */
const double hits_bound /* m */ = 100;
const int N_events = 1e5;
TRandom rng;
using namespace std;
ostream& operator<<(ostream& ost, TVector2& vec)
{
return ost << vec.X() << " " << vec.Y();
}
ostream& operator<<(ostream& ost, TVector3& vec)
{
return ost << vec.X() << " " << vec.Y() << " " << vec.Z();
}
inline double generate_K_energy()
{
return max(K_mass, rng.Gaus(K_energy_average, K_energy_sigma));
}
inline double generate_K_path()
{
return rng.Exp(K_path_average);
}
inline double gamma_from_K_energy(double K_energy)
{
return K_energy/K_mass;
}
inline TVector3 generate_Pi_momentum_cm()
{
double x,y,z;
rng.Sphere(x, y, z, Pi_momentum_mod_cm);
return TVector3(x, y, z);
}
inline TVector2 chamber_hit(TVector3 Pi_momentum, double z_chamber, double z_start, double x_start=0, double y_start=0)
{
double z_travelled = z_chamber - z_start;
double scale = z_travelled/Pi_momentum.Pz();
return TVector2(Pi_momentum.Px()*scale + x_start, Pi_momentum.Py()*scale + y_start);
}
inline TVector2 apply_chamber_smearing(TVector2 hit, double dx, double dy)
{
double x = rng.Gaus(hit.X(), dx);
double y = rng.Gaus(hit.Y(), dy);
return TVector2(x, y);
}
int experiment()
{
rng = TRandom3(12345); /* Fixed init */
// Histograms declaration
TCanvas* canv_K_energy = new TCanvas("canv_K_energy", "K energy distribution", 1000, 600);
TH1D* histo_K_energy = new TH1D("histo_K_energy", "K energy distribution; E (GeV); N",
180, K_energy_average - 3* K_energy_sigma, K_energy_average + 3* K_energy_sigma);
TCanvas* canv_K_path = new TCanvas("canv_K_path", "K path distribution", 1000, 600);
TH1D* histo_K_path = new TH1D("histo_K_path", "K path distribution; Path (m); N",
180, 0, 10*gamma_from_K_energy(K_energy_average)*K_path_average);
TCanvas* canv_Pi_momentum_cm = new TCanvas("canv_Pi_momentum_cm", "Pi momentum cm", 1000, 600);
TH3D* histo_Pi_momentum_cm = new TH3D("histo_Pi_momentum_cm", "Pi momentum cm; Px (GeV); Py (GeV); Pz (GeV)",
100, -Pi_momentum_mod_cm, +Pi_momentum_mod_cm,
100, -Pi_momentum_mod_cm, +Pi_momentum_mod_cm,
100, -Pi_momentum_mod_cm, +Pi_momentum_mod_cm);
TCanvas* canv_Pi_pos = new TCanvas("canv_Pi_pos", "Pi pos", 1000, 600);
TH3D* histo_Pi_pos = new TH3D("histo_Pi_pos", "Pi pos; Px (GeV); Py (GeV); Pz (GeV)",
100, -Pi_momentum_mod_cm, +Pi_momentum_mod_cm,
100, -Pi_momentum_mod_cm, +Pi_momentum_mod_cm,
100, 0, +2*K_energy_average);
TCanvas* canv_hit_p1 = new TCanvas("canv_hit_p1", "Hit pos ch1", 1000, 600);
TH2D* histo_hit_p1 = new TH2D("histo_hit_p1", "Hit pos ch1; x (m); y (m); N",
200, -hits_bound, +hits_bound, 200, -hits_bound, +hits_bound);
TCanvas* canv_hit_p1_smeared = new TCanvas("canv_hit_p1_smeared", "Hit pos ch1 smeared", 1000, 600);
TH2D* histo_hit_p1_smeared = new TH2D("histo_hit_p1_smeared", "Hit pos ch1 smeared; x (m); y (m); N",
200, -hits_bound, +hits_bound, 200, -hits_bound, +hits_bound);
TCanvas* canv_hit_p3 = new TCanvas("canv_hit_p13", "Hit pos ch3", 1000, 600);
TH2D* histo_hit_p3 = new TH2D("histo_hit_p3", "Hit pos ch3; x (m); y (m); N",
200, -hits_bound, +hits_bound, 200, -hits_bound, +hits_bound);
// Out file
ofstream outfile;
outfile.open("experiment.txt");
// Main loop
for (int nev=0; nev<N_events; ++nev) {
// Generate K energy
double K_energy = generate_K_energy();
histo_K_energy->Fill(K_energy);
// Generate K path
double path_cm = generate_K_path();
double path = gamma_from_K_energy(K_energy)*path_cm;
histo_K_path->Fill(path);
// Discard K that have not decayed before the first chamber
if (path > z1) continue;
// Generate cm dynamic
TVector3 Pi_momentum_cm = generate_Pi_momentum_cm();
histo_Pi_momentum_cm->Fill(Pi_momentum_cm.Px(), Pi_momentum_cm.Py(), Pi_momentum_cm.Pz());
// Boost to lab frame
double K_beta_z = sqrt(1 - pow(K_mass/K_energy, 2));
// double x = K_mass/K_energy;
// double K_beta_z = 1 + pow(x, 2)/2 - pow(x, 4)/8 + pow(x, 6)/16;
TVector3 K_beta = TVector3(0, 0, K_beta_z);
TLorentzVector Pi_pos_4v = TLorentzVector( Pi_momentum_cm, Pi_energy_cm);
TLorentzVector Pi_neg_4v = TLorentzVector(-Pi_momentum_cm, Pi_energy_cm); // Momentum cons. in cm
Pi_pos_4v.Boost(K_beta);
Pi_neg_4v.Boost(K_beta);
TVector3 Pi_pos = Pi_pos_4v.Vect();
TVector3 Pi_neg = Pi_neg_4v.Vect();
histo_Pi_pos->Fill(Pi_pos.Px(), Pi_pos.Py(), Pi_pos.Pz());
// Calculate hit points in first two chambers
TVector2 hit_p1=chamber_hit(Pi_pos, z1, path);
TVector2 hit_n1=chamber_hit(Pi_neg, z1, path);
TVector2 hit_p2=chamber_hit(Pi_pos, z2, path);
TVector2 hit_n2=chamber_hit(Pi_neg, z2, path);
histo_hit_p1->Fill(hit_p1.X(), hit_p1.Y());
// Apply chamber smearing
TVector2 hit_p1_smeared = apply_chamber_smearing(hit_p1, dx, dy);
TVector2 hit_n1_smeared = apply_chamber_smearing(hit_n1, dx, dy);
TVector2 hit_p2_smeared = apply_chamber_smearing(hit_p2, dx, dy);
TVector2 hit_n2_smeared = apply_chamber_smearing(hit_n2, dx, dy);
histo_hit_p1_smeared->Fill(hit_p1_smeared.X(), hit_p1_smeared.Y());
// The magnetic field is schematized as a kick of magnitude p_kick
// applied at the center of the magnetic field region (z_kick)
// Find position at kick
TVector2 Pi_pos_position_kick = chamber_hit(Pi_pos, z_kick, path);
TVector2 Pi_neg_position_kick = chamber_hit(Pi_neg, z_kick, path);
TVector3 p_kick_vec = TVector3(p_kick, 0, 0);
// Find hits in last two chambers - p_kick is opposite due to charge
TVector2 hit_p3=chamber_hit(Pi_pos + p_kick_vec, z3, z_kick, Pi_pos_position_kick.X(), Pi_pos_position_kick.Y());
TVector2 hit_n3=chamber_hit(Pi_neg - p_kick_vec, z3, z_kick, Pi_neg_position_kick.X(), Pi_neg_position_kick.Y());
TVector2 hit_p4=chamber_hit(Pi_pos + p_kick_vec, z4, z_kick, Pi_pos_position_kick.X(), Pi_pos_position_kick.Y());
TVector2 hit_n4=chamber_hit(Pi_neg - p_kick_vec, z4, z_kick, Pi_neg_position_kick.X(), Pi_neg_position_kick.Y());
histo_hit_p3->Fill(hit_p3.X(), hit_p3.Y());
// Apply chamber smearing
TVector2 hit_p3_smeared = apply_chamber_smearing(hit_p3, dx, dy);
TVector2 hit_n3_smeared = apply_chamber_smearing(hit_n3, dx, dy);
TVector2 hit_p4_smeared = apply_chamber_smearing(hit_p4, dx, dy);
TVector2 hit_n4_smeared = apply_chamber_smearing(hit_n4, dx, dy);
// Write to file
outfile << hit_p1_smeared << " ";
outfile << hit_n1_smeared << " ";
outfile << hit_p2_smeared << " ";
outfile << hit_n2_smeared << " ";
outfile << hit_p3_smeared << " ";
outfile << hit_n3_smeared << " ";
outfile << hit_p4_smeared << " ";
outfile << hit_n4_smeared << " ";
outfile << "-" << " ";
outfile << K_energy << " ";
outfile << path << " ";
outfile << Pi_pos << " ";
outfile << Pi_neg <<endl;
}
// Histogram drawing
canv_K_energy->cd();
histo_K_energy->Draw();
canv_K_path->cd();
canv_K_path->SetLogy();
histo_K_path->Draw();
canv_Pi_momentum_cm->cd();
histo_Pi_momentum_cm->Draw();
canv_Pi_pos->cd();
histo_Pi_pos->Draw();
canv_hit_p1->cd();
histo_hit_p1->Draw();
canv_hit_p1_smeared->cd();
histo_hit_p1_smeared->Draw();
canv_hit_p3->cd();
histo_hit_p3->Draw();
return 0;
}
int main(int, char**)
{
return experiment();
}
<commit_msg>Changed out text file format<commit_after>#include <iostream>
#include <fstream>
#include <cmath>
#include "TH1.h"
#include "TH2.h"
#include "TH3.h"
#include "TCanvas.h"
#include "TRandom3.h"
#include "TVector2.h"
#include "TVector3.h"
#include "TLorentzVector.h"
/* Simulated experiment is a K_L->PiPi decay (CP violating)*/
const double K_energy_average /*GeV*/ = 2; // Around the value of Cronin-Fitch experiment
const double K_energy_sigma /*GeV*/ = 0.5;
const double K_path_average /* m */ = 15.34;
const double K_mass /*GeV*/ = 0.497611;
const double Pi_mass /*GeV*/ = 0.139570; // charged pi
const double Pi_energy_cm = K_mass/2;
const double Pi_momentum_mod_cm = sqrt(Pi_energy_cm*Pi_energy_cm - Pi_mass*Pi_mass);
/* Detector coordinates */
const double z1 /* m */ = 200;
const double z2 /* m */ = 201;
const double z3 /* m */ = 250;
const double z4 /* m */ = 251;
/* Detector smearing */
const double dx /* m */ = 0.01;
const double dy /* m */ = 0.01;
/* dp kick - applied at the center of the field region */
const double z_drift /* m */ = z3-z2;
const double z_kick /* m */ = (z2+z3)/2;
const double p_kick /* GeV */ = 1e-5*z_drift;
/* Plots constants */
const double hits_bound /* m */ = 100;
const int N_events = 1e5;
TRandom rng;
using namespace std;
ostream& operator<<(ostream& ost, TVector2& vec)
{
return ost << vec.X() << " " << vec.Y();
}
ostream& operator<<(ostream& ost, TVector3& vec)
{
return ost << vec.X() << " " << vec.Y() << " " << vec.Z();
}
inline double generate_K_energy()
{
return max(K_mass, rng.Gaus(K_energy_average, K_energy_sigma));
}
inline double generate_K_path()
{
return rng.Exp(K_path_average);
}
inline double gamma_from_K_energy(double K_energy)
{
return K_energy/K_mass;
}
inline TVector3 generate_Pi_momentum_cm()
{
double x,y,z;
rng.Sphere(x, y, z, Pi_momentum_mod_cm);
return TVector3(x, y, z);
}
inline TVector2 chamber_hit(TVector3 Pi_momentum, double z_chamber, double z_start, double x_start=0, double y_start=0)
{
double z_travelled = z_chamber - z_start;
double scale = z_travelled/Pi_momentum.Pz();
return TVector2(Pi_momentum.Px()*scale + x_start, Pi_momentum.Py()*scale + y_start);
}
inline TVector2 apply_chamber_smearing(TVector2 hit, double dx, double dy)
{
double x = rng.Gaus(hit.X(), dx);
double y = rng.Gaus(hit.Y(), dy);
return TVector2(x, y);
}
int experiment()
{
rng = TRandom3(12345); /* Fixed init */
// Histograms declaration
TCanvas* canv_K_energy = new TCanvas("canv_K_energy", "K energy distribution", 1000, 600);
TH1D* histo_K_energy = new TH1D("histo_K_energy", "K energy distribution; E (GeV); N",
180, K_energy_average - 3* K_energy_sigma, K_energy_average + 3* K_energy_sigma);
TCanvas* canv_K_path = new TCanvas("canv_K_path", "K path distribution", 1000, 600);
TH1D* histo_K_path = new TH1D("histo_K_path", "K path distribution; Path (m); N",
180, 0, 10*gamma_from_K_energy(K_energy_average)*K_path_average);
TCanvas* canv_Pi_momentum_cm = new TCanvas("canv_Pi_momentum_cm", "Pi momentum cm", 1000, 600);
TH3D* histo_Pi_momentum_cm = new TH3D("histo_Pi_momentum_cm", "Pi momentum cm; Px (GeV); Py (GeV); Pz (GeV)",
100, -Pi_momentum_mod_cm, +Pi_momentum_mod_cm,
100, -Pi_momentum_mod_cm, +Pi_momentum_mod_cm,
100, -Pi_momentum_mod_cm, +Pi_momentum_mod_cm);
TCanvas* canv_Pi_pos = new TCanvas("canv_Pi_pos", "Pi pos", 1000, 600);
TH3D* histo_Pi_pos = new TH3D("histo_Pi_pos", "Pi pos; Px (GeV); Py (GeV); Pz (GeV)",
100, -Pi_momentum_mod_cm, +Pi_momentum_mod_cm,
100, -Pi_momentum_mod_cm, +Pi_momentum_mod_cm,
100, 0, +2*K_energy_average);
TCanvas* canv_hit_p1 = new TCanvas("canv_hit_p1", "Hit pos ch1", 1000, 600);
TH2D* histo_hit_p1 = new TH2D("histo_hit_p1", "Hit pos ch1; x (m); y (m); N",
200, -hits_bound, +hits_bound, 200, -hits_bound, +hits_bound);
TCanvas* canv_hit_p1_smeared = new TCanvas("canv_hit_p1_smeared", "Hit pos ch1 smeared", 1000, 600);
TH2D* histo_hit_p1_smeared = new TH2D("histo_hit_p1_smeared", "Hit pos ch1 smeared; x (m); y (m); N",
200, -hits_bound, +hits_bound, 200, -hits_bound, +hits_bound);
TCanvas* canv_hit_p3 = new TCanvas("canv_hit_p13", "Hit pos ch3", 1000, 600);
TH2D* histo_hit_p3 = new TH2D("histo_hit_p3", "Hit pos ch3; x (m); y (m); N",
200, -hits_bound, +hits_bound, 200, -hits_bound, +hits_bound);
// Out file
ofstream outfile;
outfile.open("experiment.txt");
// Main loop
for (int nev=0; nev<N_events; ++nev) {
// Generate K energy
double K_energy = generate_K_energy();
histo_K_energy->Fill(K_energy);
// Generate K path
double path_cm = generate_K_path();
double path = gamma_from_K_energy(K_energy)*path_cm;
histo_K_path->Fill(path);
// Discard K that have not decayed before the first chamber
if (path > z1) continue;
// Generate cm dynamic
TVector3 Pi_momentum_cm = generate_Pi_momentum_cm();
histo_Pi_momentum_cm->Fill(Pi_momentum_cm.Px(), Pi_momentum_cm.Py(), Pi_momentum_cm.Pz());
// Boost to lab frame
double K_beta_z = sqrt(1 - pow(K_mass/K_energy, 2));
// double x = K_mass/K_energy;
// double K_beta_z = 1 + pow(x, 2)/2 - pow(x, 4)/8 + pow(x, 6)/16;
TVector3 K_beta = TVector3(0, 0, K_beta_z);
TLorentzVector Pi_pos_4v = TLorentzVector( Pi_momentum_cm, Pi_energy_cm);
TLorentzVector Pi_neg_4v = TLorentzVector(-Pi_momentum_cm, Pi_energy_cm); // Momentum cons. in cm
Pi_pos_4v.Boost(K_beta);
Pi_neg_4v.Boost(K_beta);
TVector3 Pi_pos = Pi_pos_4v.Vect();
TVector3 Pi_neg = Pi_neg_4v.Vect();
histo_Pi_pos->Fill(Pi_pos.Px(), Pi_pos.Py(), Pi_pos.Pz());
// Calculate hit points in first two chambers
TVector2 hit_p1=chamber_hit(Pi_pos, z1, path);
TVector2 hit_n1=chamber_hit(Pi_neg, z1, path);
TVector2 hit_p2=chamber_hit(Pi_pos, z2, path);
TVector2 hit_n2=chamber_hit(Pi_neg, z2, path);
histo_hit_p1->Fill(hit_p1.X(), hit_p1.Y());
// Apply chamber smearing
TVector2 hit_p1_smeared = apply_chamber_smearing(hit_p1, dx, dy);
TVector2 hit_n1_smeared = apply_chamber_smearing(hit_n1, dx, dy);
TVector2 hit_p2_smeared = apply_chamber_smearing(hit_p2, dx, dy);
TVector2 hit_n2_smeared = apply_chamber_smearing(hit_n2, dx, dy);
histo_hit_p1_smeared->Fill(hit_p1_smeared.X(), hit_p1_smeared.Y());
// The magnetic field is schematized as a kick of magnitude p_kick
// applied at the center of the magnetic field region (z_kick)
// Find position at kick
TVector2 Pi_pos_position_kick = chamber_hit(Pi_pos, z_kick, path);
TVector2 Pi_neg_position_kick = chamber_hit(Pi_neg, z_kick, path);
TVector3 p_kick_vec = TVector3(p_kick, 0, 0);
// Find hits in last two chambers - p_kick is opposite due to charge
TVector2 hit_p3=chamber_hit(Pi_pos + p_kick_vec, z3, z_kick, Pi_pos_position_kick.X(), Pi_pos_position_kick.Y());
TVector2 hit_n3=chamber_hit(Pi_neg - p_kick_vec, z3, z_kick, Pi_neg_position_kick.X(), Pi_neg_position_kick.Y());
TVector2 hit_p4=chamber_hit(Pi_pos + p_kick_vec, z4, z_kick, Pi_pos_position_kick.X(), Pi_pos_position_kick.Y());
TVector2 hit_n4=chamber_hit(Pi_neg - p_kick_vec, z4, z_kick, Pi_neg_position_kick.X(), Pi_neg_position_kick.Y());
histo_hit_p3->Fill(hit_p3.X(), hit_p3.Y());
// Apply chamber smearing
TVector2 hit_p3_smeared = apply_chamber_smearing(hit_p3, dx, dy);
TVector2 hit_n3_smeared = apply_chamber_smearing(hit_n3, dx, dy);
TVector2 hit_p4_smeared = apply_chamber_smearing(hit_p4, dx, dy);
TVector2 hit_n4_smeared = apply_chamber_smearing(hit_n4, dx, dy);
// Write to file
outfile << nev << " ";
outfile << hit_p1_smeared << " ";
outfile << hit_n1_smeared << " ";
outfile << hit_p2_smeared << " ";
outfile << hit_n2_smeared << " ";
outfile << hit_p3_smeared << " ";
outfile << hit_n3_smeared << " ";
outfile << hit_p4_smeared << " ";
outfile << hit_n4_smeared << " ";
outfile << K_energy << " ";
outfile << path << " ";
outfile << Pi_pos << " ";
outfile << Pi_neg <<endl;
}
// Histogram drawing
canv_K_energy->cd();
histo_K_energy->Draw();
canv_K_path->cd();
canv_K_path->SetLogy();
histo_K_path->Draw();
canv_Pi_momentum_cm->cd();
histo_Pi_momentum_cm->Draw();
canv_Pi_pos->cd();
histo_Pi_pos->Draw();
canv_hit_p1->cd();
histo_hit_p1->Draw();
canv_hit_p1_smeared->cd();
histo_hit_p1_smeared->Draw();
canv_hit_p3->cd();
histo_hit_p3->Draw();
return 0;
}
int main(int, char**)
{
return experiment();
}
<|endoftext|>
|
<commit_before>#include "stan/math/functions/log_sum_exp.hpp"
#include <gtest/gtest.h>
void test_log_sum_exp(double a, double b) {
using std::log;
using std::exp;
using stan::math::log_sum_exp;
EXPECT_FLOAT_EQ(log(exp(a) + exp(b)),
log_sum_exp(a,b));
}
void test_log_sum_exp(const std::vector<double>& as) {
using std::log;
using std::exp;
using stan::math::log_sum_exp;
double sum_exp = 0.0;
for (size_t n = 0; n < as.size(); ++n)
sum_exp += exp(as[n]);
EXPECT_FLOAT_EQ(log(sum_exp),
log_sum_exp(as));
}
TEST(MathFunctions, log_sum_exp) {
using stan::math::log_sum_exp;
std::vector<double> as;
test_log_sum_exp(as);
as.push_back(0.0);
test_log_sum_exp(as);
as.push_back(1.0);
test_log_sum_exp(as);
as.push_back(-1.0);
test_log_sum_exp(as);
as.push_back(-10000.0);
test_log_sum_exp(as);
as.push_back(10000.0);
EXPECT_FLOAT_EQ(10000.0, log_sum_exp(as));
}
TEST(MathFunctions, log_sum_exp_2) {
using stan::math::log_sum_exp;
test_log_sum_exp(1.0,2.0);
test_log_sum_exp(1.0,1.0);
test_log_sum_exp(3.0,2.0);
test_log_sum_exp(-20.0,12);
test_log_sum_exp(-20.0,12);
// exp(10000.0) overflows
EXPECT_FLOAT_EQ(10000.0,log_sum_exp(10000.0,0.0));
EXPECT_FLOAT_EQ(0.0,log_sum_exp(-10000.0,0.0));
}
<commit_msg>added NaN test for log_sum_exp<commit_after>#include <stan/math/functions/log_sum_exp.hpp>
#include <boost/math/special_functions/fpclassify.hpp>
#include <gtest/gtest.h>
void test_log_sum_exp(double a, double b) {
using std::log;
using std::exp;
using stan::math::log_sum_exp;
EXPECT_FLOAT_EQ(log(exp(a) + exp(b)),
log_sum_exp(a,b));
}
void test_log_sum_exp(const std::vector<double>& as) {
using std::log;
using std::exp;
using stan::math::log_sum_exp;
double sum_exp = 0.0;
for (size_t n = 0; n < as.size(); ++n)
sum_exp += exp(as[n]);
EXPECT_FLOAT_EQ(log(sum_exp),
log_sum_exp(as));
}
TEST(MathFunctions, log_sum_exp) {
using stan::math::log_sum_exp;
std::vector<double> as;
test_log_sum_exp(as);
as.push_back(0.0);
test_log_sum_exp(as);
as.push_back(1.0);
test_log_sum_exp(as);
as.push_back(-1.0);
test_log_sum_exp(as);
as.push_back(-10000.0);
test_log_sum_exp(as);
as.push_back(10000.0);
EXPECT_FLOAT_EQ(10000.0, log_sum_exp(as));
}
TEST(MathFunctions, log_sum_exp_2) {
using stan::math::log_sum_exp;
test_log_sum_exp(1.0,2.0);
test_log_sum_exp(1.0,1.0);
test_log_sum_exp(3.0,2.0);
test_log_sum_exp(-20.0,12);
test_log_sum_exp(-20.0,12);
// exp(10000.0) overflows
EXPECT_FLOAT_EQ(10000.0,log_sum_exp(10000.0,0.0));
EXPECT_FLOAT_EQ(0.0,log_sum_exp(-10000.0,0.0));
}
TEST(MathFunctions, log_sum_exp_nan) {
double nan = std::numeric_limits<double>::quiet_NaN();
EXPECT_PRED1(boost::math::isnan<double>,
stan::math::log_sum_exp(1.0, nan));
EXPECT_PRED1(boost::math::isnan<double>,
stan::math::log_sum_exp(nan, 1.0));
EXPECT_PRED1(boost::math::isnan<double>,
stan::math::log_sum_exp(nan, nan));
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2015 Fondazione Istituto Italiano di Tecnologia
* Authors: Silvio Traversaro
* CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT
*
*/
#include <iDynTree/Core/TestUtils.h>
#include <iDynTree/Model/Model.h>
#include <iDynTree/Model/Traversal.h>
#include <iDynTree/ModelIO/URDFModelImport.h>
#include <iDynTree/Model/ForwardKinematics.h>
#include <iDynTree/Model/Dynamics.h>
#include <iDynTree/Model/JointState.h>
#include <iDynTree/Model/LinkState.h>
#include <iDynTree/Model/FreeFloatingState.h>
#include <iDynTree/Model/FreeFloatingMassMatrix.h>
#include "testModels.h"
#include <cassert>
#include <cstdio>
#include <cstdlib>
using namespace iDynTree;
void checkInverseAndForwardDynamicsAreIdempotent(const Model & model,
const Traversal & traversal)
{
// Allocate input for both algorithms : robot position, velocity
// and link external wrenches
LinkExternalWrenches linkExtWrenches(model);
FreeFloatingPos robotPos(model);
FreeFloatingVel robotVel(model);
// Input for direct dynamics algorithms
// and output for inverse dynamics : joint torques
JointDoubleArray ABA_jntTorques(model);
// Fill the input to forward dynamics with random data
robotPos.worldBasePos() = getRandomTransform();
robotVel.baseVel() = getRandomTwist();
getRandomVector(robotPos.jointPos());
getRandomVector(robotVel.jointVel());
for(unsigned int link=0; link < model.getNrOfLinks(); link++ )
{
linkExtWrenches(link) = getRandomWrench();
}
getRandomVector(ABA_jntTorques);
// Output for direct dynamics algorithms
// and input for inverse dynamics : robot acceleration
FreeFloatingAcc ABA_robotAcc(model);
// Allocate temporary data structures for ABA
iDynTree::DOFSpatialMotionArray ABA_S(model);
iDynTree::DOFSpatialForceArray ABA_U(model);
iDynTree::JointDoubleArray ABA_D(model);
JointDoubleArray ABA_u(model);
iDynTree::LinkVelArray ABA_linksVel(model);
iDynTree::LinkAccArray ABA_linksBiasAcceleration(model);
ASSERT_EQUAL_DOUBLE(ABA_linksBiasAcceleration.getNrOfLinks(),model.getNrOfLinks());
LinkAccArray ABA_linksAcceleration(model);
ASSERT_EQUAL_DOUBLE(ABA_linksBiasAcceleration.getNrOfLinks(),model.getNrOfLinks());
LinkArticulatedBodyInertias linkABIs(model);
LinkWrenches linksBiasWrench(model);
// Run ABA
ArticulatedBodyAlgorithm(model,
traversal,
robotPos,
robotVel,
linkExtWrenches,
ABA_jntTorques,
ABA_S,
ABA_U,
ABA_D,
ABA_u,
ABA_linksVel,
ABA_linksBiasAcceleration,
ABA_linksAcceleration,
linkABIs,
linksBiasWrench,
ABA_robotAcc);
// Allocate temporary data structure for RNEA
LinkVelArray RNEA_linksVel(model);
LinkAccArray RNEA_linksAcc(model);
LinkInternalWrenches RNEA_linkIntWrenches(model);
FreeFloatingGeneralizedTorques RNEA_baseForceAndJointTorques(model);
// Run RNEA
ForwardVelAccKinematics(model,
traversal,
robotPos,
robotVel,
ABA_robotAcc,
RNEA_linksVel,
RNEA_linksAcc);
RNEADynamicPhase(model,
traversal,
robotPos,
RNEA_linksVel,
RNEA_linksAcc,
linkExtWrenches,
RNEA_linkIntWrenches,
RNEA_baseForceAndJointTorques);
// Check output of RNEA : given that accelerations
// and external forces are consistent, the resulting
// base wrench should be zero, while the joint torque
// should be equal to the one given in input to the ABA
Vector6 zeroVec; zeroVec.zero();
std::cout << "Check base wrench" << std::endl;
ASSERT_EQUAL_VECTOR_TOL(RNEA_baseForceAndJointTorques.baseWrench().asVector(),
zeroVec,1e-7);
std::cout << "Check joint torques" << std::endl;
ASSERT_EQUAL_VECTOR_TOL(RNEA_baseForceAndJointTorques.jointTorques(),ABA_jntTorques,1e-9);
}
int main()
{
for(unsigned int mdl = 0; mdl < IDYNTREE_TESTS_URDFS_NR; mdl++ )
{
std::string urdfFileName = getAbsModelPath(std::string(IDYNTREE_TESTS_URDFS[mdl]));
std::cout << "Checking dynamics test on " << urdfFileName << std::endl;
Model model;
bool ok = modelFromURDF(urdfFileName,model);
assert(ok);
Traversal traversal;
ok = model.computeFullTreeTraversal(traversal);
assert(ok);
checkInverseAndForwardDynamicsAreIdempotent(model,traversal);
}
}
<commit_msg>[test] Increase tolerance on DynamicsIntegration<commit_after>/*
* Copyright (C) 2015 Fondazione Istituto Italiano di Tecnologia
* Authors: Silvio Traversaro
* CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT
*
*/
#include <iDynTree/Core/TestUtils.h>
#include <iDynTree/Model/Model.h>
#include <iDynTree/Model/Traversal.h>
#include <iDynTree/ModelIO/URDFModelImport.h>
#include <iDynTree/Model/ForwardKinematics.h>
#include <iDynTree/Model/Dynamics.h>
#include <iDynTree/Model/JointState.h>
#include <iDynTree/Model/LinkState.h>
#include <iDynTree/Model/FreeFloatingState.h>
#include <iDynTree/Model/FreeFloatingMassMatrix.h>
#include "testModels.h"
#include <cassert>
#include <cstdio>
#include <cstdlib>
using namespace iDynTree;
void checkInverseAndForwardDynamicsAreIdempotent(const Model & model,
const Traversal & traversal)
{
// Allocate input for both algorithms : robot position, velocity
// and link external wrenches
LinkExternalWrenches linkExtWrenches(model);
FreeFloatingPos robotPos(model);
FreeFloatingVel robotVel(model);
// Input for direct dynamics algorithms
// and output for inverse dynamics : joint torques
JointDoubleArray ABA_jntTorques(model);
// Fill the input to forward dynamics with random data
robotPos.worldBasePos() = getRandomTransform();
robotVel.baseVel() = getRandomTwist();
getRandomVector(robotPos.jointPos());
getRandomVector(robotVel.jointVel());
for(unsigned int link=0; link < model.getNrOfLinks(); link++ )
{
linkExtWrenches(link) = getRandomWrench();
}
getRandomVector(ABA_jntTorques);
// Output for direct dynamics algorithms
// and input for inverse dynamics : robot acceleration
FreeFloatingAcc ABA_robotAcc(model);
// Allocate temporary data structures for ABA
iDynTree::DOFSpatialMotionArray ABA_S(model);
iDynTree::DOFSpatialForceArray ABA_U(model);
iDynTree::JointDoubleArray ABA_D(model);
JointDoubleArray ABA_u(model);
iDynTree::LinkVelArray ABA_linksVel(model);
iDynTree::LinkAccArray ABA_linksBiasAcceleration(model);
ASSERT_EQUAL_DOUBLE(ABA_linksBiasAcceleration.getNrOfLinks(),model.getNrOfLinks());
LinkAccArray ABA_linksAcceleration(model);
ASSERT_EQUAL_DOUBLE(ABA_linksBiasAcceleration.getNrOfLinks(),model.getNrOfLinks());
LinkArticulatedBodyInertias linkABIs(model);
LinkWrenches linksBiasWrench(model);
// Run ABA
ArticulatedBodyAlgorithm(model,
traversal,
robotPos,
robotVel,
linkExtWrenches,
ABA_jntTorques,
ABA_S,
ABA_U,
ABA_D,
ABA_u,
ABA_linksVel,
ABA_linksBiasAcceleration,
ABA_linksAcceleration,
linkABIs,
linksBiasWrench,
ABA_robotAcc);
// Allocate temporary data structure for RNEA
LinkVelArray RNEA_linksVel(model);
LinkAccArray RNEA_linksAcc(model);
LinkInternalWrenches RNEA_linkIntWrenches(model);
FreeFloatingGeneralizedTorques RNEA_baseForceAndJointTorques(model);
// Run RNEA
ForwardVelAccKinematics(model,
traversal,
robotPos,
robotVel,
ABA_robotAcc,
RNEA_linksVel,
RNEA_linksAcc);
RNEADynamicPhase(model,
traversal,
robotPos,
RNEA_linksVel,
RNEA_linksAcc,
linkExtWrenches,
RNEA_linkIntWrenches,
RNEA_baseForceAndJointTorques);
// Check output of RNEA : given that accelerations
// and external forces are consistent, the resulting
// base wrench should be zero, while the joint torque
// should be equal to the one given in input to the ABA
Vector6 zeroVec; zeroVec.zero();
std::cout << "Check base wrench" << std::endl;
ASSERT_EQUAL_VECTOR_TOL(RNEA_baseForceAndJointTorques.baseWrench().asVector(),
zeroVec,1e-6);
std::cout << "Check joint torques" << std::endl;
ASSERT_EQUAL_VECTOR_TOL(RNEA_baseForceAndJointTorques.jointTorques(),ABA_jntTorques,1e-07);
}
int main()
{
for(unsigned int mdl = 0; mdl < IDYNTREE_TESTS_URDFS_NR; mdl++ )
{
std::string urdfFileName = getAbsModelPath(std::string(IDYNTREE_TESTS_URDFS[mdl]));
std::cout << "Checking dynamics test on " << urdfFileName << std::endl;
Model model;
bool ok = modelFromURDF(urdfFileName,model);
assert(ok);
Traversal traversal;
ok = model.computeFullTreeTraversal(traversal);
assert(ok);
checkInverseAndForwardDynamicsAreIdempotent(model,traversal);
}
}
<|endoftext|>
|
<commit_before><commit_msg>get rid of unecessary loop and change comment<commit_after><|endoftext|>
|
<commit_before>/***********************************************************************
created: Sun Mar 13 2005
author: Paul D Turner
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
***************************************************************************/
#include "CEGUI/XMLParserModules/TinyXML/XMLParser.h"
#include "CEGUI/ResourceProvider.h"
#include "CEGUI/System.h"
#include "CEGUI/XMLHandler.h"
#include "CEGUI/XMLAttributes.h"
#include "CEGUI/Logger.h"
#include "CEGUI/Exceptions.h"
#include <tinyxml.h>
//---------------------------------------------------------------------------//
// These are to support the <=2.5 and >=2.6 API versions
#ifdef CEGUI_TINYXML_HAS_2_6_API
# define CEGUI_TINYXML_ELEMENT TINYXML_ELEMENT
# define CEGUI_TINYXML_TEXT TINYXML_TEXT
#else
# define CEGUI_TINYXML_ELEMENT ELEMENT
# define CEGUI_TINYXML_TEXT TEXT
#endif
// Start of CEGUI namespace section
namespace CEGUI
{
class TinyXMLDocument : public TiXmlDocument
{
public:
TinyXMLDocument(XMLHandler& handler, const RawDataContainer& source, const String& schemaName);
~TinyXMLDocument()
{}
protected:
void processElement(const TiXmlElement* element);
private:
XMLHandler* d_handler;
};
TinyXMLDocument::TinyXMLDocument(XMLHandler& handler, const RawDataContainer& source, const String& /*schemaName*/)
{
d_handler = &handler;
// Create a buffer with extra bytes for a newline and a terminating null
size_t size = source.getSize();
char* buf = new char[size + 2];
memcpy(buf, source.getDataPtr(), size);
// PDT: The addition of the newline is a kludge to resolve an issue
// whereby parse returns 0 if the xml file has no newline at the end but
// is otherwise well formed.
buf[size] = '\n';
buf[size+1] = 0;
// Parse the document
TiXmlDocument doc;
if (!doc.Parse(static_cast<const char*>(buf)))
{
// error detected, cleanup out buffers
delete[] buf;
// throw exception
CEGUI_THROW(FileIOException("an error occurred while "
"parsing the XML document - check it for potential errors!."));
}
const TiXmlElement* currElement = doc.RootElement();
if (currElement)
{
CEGUI_TRY
{
// function called recursively to parse xml data
processElement(currElement);
}
CEGUI_CATCH(...)
{
delete [] buf;
CEGUI_RETHROW;
}
} // if (currElement)
// Free memory
delete [] buf;
}
void TinyXMLDocument::processElement(const TiXmlElement* element)
{
// build attributes block for the element
XMLAttributes attrs;
const TiXmlAttribute *currAttr = element->FirstAttribute();
while (currAttr)
{
attrs.add(reinterpret_cast<const encoded_char*>(currAttr->Name()), reinterpret_cast<const encoded_char*>(currAttr->Value()));
currAttr = currAttr->Next();
}
// start element
d_handler->elementStart(reinterpret_cast<const encoded_char*>(element->Value()), attrs);
// do children
const TiXmlNode* childNode = element->FirstChild();
while (childNode)
{
switch(childNode->Type())
{
case TiXmlNode::CEGUI_TINYXML_ELEMENT:
processElement(childNode->ToElement());
break;
case TiXmlNode::CEGUI_TINYXML_TEXT:
if (childNode->ToText()->Value() != '\0')
d_handler->text(reinterpret_cast<const encoded_char*>(childNode->ToText()->Value()));
break;
// Silently ignore unhandled node type
};
childNode = childNode->NextSibling();
}
// end element
d_handler->elementEnd(reinterpret_cast<const encoded_char*>(element->Value()));
}
TinyXMLParser::TinyXMLParser(void)
{
// set ID string
d_identifierString = "CEGUI::TinyXMLParser - Official tinyXML based parser module for CEGUI";
}
TinyXMLParser::~TinyXMLParser(void)
{}
void TinyXMLParser::parseXML(XMLHandler& handler, const RawDataContainer& source, const String& schemaName)
{
TinyXMLDocument doc(handler, source, schemaName);
}
bool TinyXMLParser::initialiseImpl(void)
{
// This used to prevent deletion of line ending in the middle of a text.
// WhiteSpace cleaning will be available throught the use of String methods directly
//TiXmlDocument::SetCondenseWhiteSpace(false);
return true;
}
void TinyXMLParser::cleanupImpl(void)
{}
} // End of CEGUI namespace section
<commit_msg>Fixed compile error in TinyXML based parser<commit_after>/***********************************************************************
created: Sun Mar 13 2005
author: Paul D Turner
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
***************************************************************************/
#include "CEGUI/XMLParserModules/TinyXML/XMLParser.h"
#include "CEGUI/ResourceProvider.h"
#include "CEGUI/System.h"
#include "CEGUI/XMLHandler.h"
#include "CEGUI/XMLAttributes.h"
#include "CEGUI/Logger.h"
#include "CEGUI/Exceptions.h"
#include <tinyxml.h>
//---------------------------------------------------------------------------//
// These are to support the <=2.5 and >=2.6 API versions
#ifdef CEGUI_TINYXML_HAS_2_6_API
# define CEGUI_TINYXML_ELEMENT TINYXML_ELEMENT
# define CEGUI_TINYXML_TEXT TINYXML_TEXT
#else
# define CEGUI_TINYXML_ELEMENT ELEMENT
# define CEGUI_TINYXML_TEXT TEXT
#endif
// Start of CEGUI namespace section
namespace CEGUI
{
class TinyXMLDocument : public TiXmlDocument
{
public:
TinyXMLDocument(XMLHandler& handler, const RawDataContainer& source, const String& schemaName);
~TinyXMLDocument()
{}
protected:
void processElement(const TiXmlElement* element);
private:
XMLHandler* d_handler;
};
TinyXMLDocument::TinyXMLDocument(XMLHandler& handler, const RawDataContainer& source, const String& /*schemaName*/)
{
d_handler = &handler;
// Create a buffer with extra bytes for a newline and a terminating null
size_t size = source.getSize();
char* buf = new char[size + 2];
memcpy(buf, source.getDataPtr(), size);
// PDT: The addition of the newline is a kludge to resolve an issue
// whereby parse returns 0 if the xml file has no newline at the end but
// is otherwise well formed.
buf[size] = '\n';
buf[size+1] = 0;
// Parse the document
TiXmlDocument doc;
if (!doc.Parse(static_cast<const char*>(buf)))
{
// error detected, cleanup out buffers
delete[] buf;
// throw exception
CEGUI_THROW(FileIOException("an error occurred while "
"parsing the XML document - check it for potential errors!."));
}
const TiXmlElement* currElement = doc.RootElement();
if (currElement)
{
CEGUI_TRY
{
// function called recursively to parse xml data
processElement(currElement);
}
CEGUI_CATCH(...)
{
delete [] buf;
CEGUI_RETHROW;
}
} // if (currElement)
// Free memory
delete [] buf;
}
void TinyXMLDocument::processElement(const TiXmlElement* element)
{
// build attributes block for the element
XMLAttributes attrs;
const TiXmlAttribute *currAttr = element->FirstAttribute();
while (currAttr)
{
attrs.add(reinterpret_cast<const encoded_char*>(currAttr->Name()), reinterpret_cast<const encoded_char*>(currAttr->Value()));
currAttr = currAttr->Next();
}
// start element
d_handler->elementStart(reinterpret_cast<const encoded_char*>(element->Value()), attrs);
// do children
const TiXmlNode* childNode = element->FirstChild();
while (childNode)
{
switch(childNode->Type())
{
case TiXmlNode::CEGUI_TINYXML_ELEMENT:
processElement(childNode->ToElement());
break;
case TiXmlNode::CEGUI_TINYXML_TEXT:
if (childNode->ToText()->Value() != nullptr)
d_handler->text(reinterpret_cast<const encoded_char*>(childNode->ToText()->Value()));
break;
// Silently ignore unhandled node type
};
childNode = childNode->NextSibling();
}
// end element
d_handler->elementEnd(reinterpret_cast<const encoded_char*>(element->Value()));
}
TinyXMLParser::TinyXMLParser(void)
{
// set ID string
d_identifierString = "CEGUI::TinyXMLParser - Official tinyXML based parser module for CEGUI";
}
TinyXMLParser::~TinyXMLParser(void)
{}
void TinyXMLParser::parseXML(XMLHandler& handler, const RawDataContainer& source, const String& schemaName)
{
TinyXMLDocument doc(handler, source, schemaName);
}
bool TinyXMLParser::initialiseImpl(void)
{
// This used to prevent deletion of line ending in the middle of a text.
// WhiteSpace cleaning will be available throught the use of String methods directly
//TiXmlDocument::SetCondenseWhiteSpace(false);
return true;
}
void TinyXMLParser::cleanupImpl(void)
{}
} // End of CEGUI namespace section
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: FilteredContainer.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: rt $ $Date: 2005-09-08 09:57:48 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef DBACCESS_CORE_FILTERED_CONTAINER_HXX
#include "FilteredContainer.hxx"
#endif
#ifndef DBA_CORE_REFRESHLISTENER_HXX
#include "RefreshListener.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBC_XROW_HPP_
#include <com/sun/star/sdbc/XRow.hpp>
#endif
#ifndef _CONNECTIVITY_DBTOOLS_HXX_
#include <connectivity/dbtools.hxx>
#endif
#ifndef _WLDCRD_HXX
#include <tools/wldcrd.hxx>
#endif
namespace dbaccess
{
using namespace dbtools;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::sdb;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::util;
using namespace ::com::sun::star::container;
using namespace ::osl;
using namespace ::comphelper;
using namespace ::cppu;
using namespace ::connectivity::sdbcx;
//------------------------------------------------------------------------------
/** compare two strings
*/
extern int
#if defined( WNT )
__cdecl
#endif
#if defined( ICC ) && defined( OS2 )
_Optlink
#endif
NameCompare( const void* pFirst, const void* pSecond)
{
return reinterpret_cast< const ::rtl::OUString* >(pFirst)->compareTo(*reinterpret_cast< const ::rtl::OUString* >(pSecond));
}
//------------------------------------------------------------------------------
/** creates a vector of WildCards and reduce the _rTableFilter of the length of WildsCards
*/
sal_Int32 createWildCardVector(Sequence< ::rtl::OUString >& _rTableFilter, ::std::vector< WildCard >& _rOut)
{
// for wildcard search : remove all table filters which are a wildcard expression and build a WilCard
// for them
::rtl::OUString* pTableFilters = _rTableFilter.getArray();
::rtl::OUString* pEnd = pTableFilters + _rTableFilter.getLength();
sal_Int32 nShiftPos = 0;
for (sal_Int32 i=0; pEnd != pTableFilters; ++pTableFilters,++i)
{
if (pTableFilters->indexOf('%') != -1)
{
_rOut.push_back(WildCard(pTableFilters->replace('%', '*')));
}
else
{
if (nShiftPos != i)
{
_rTableFilter.getArray()[nShiftPos] = _rTableFilter.getArray()[i];
}
++nShiftPos;
}
}
// now aTableFilter contains nShiftPos non-wc-strings and aWCSearch all wc-strings
_rTableFilter.realloc(nShiftPos);
return nShiftPos;
}
//==========================================================================
//= OViewContainer
//==========================================================================
OFilteredContainer::OFilteredContainer(::cppu::OWeakObject& _rParent,
::osl::Mutex& _rMutex,
const Reference< XConnection >& _xCon,
sal_Bool _bCase,
IRefreshListener* _pRefreshListener,
IWarningsContainer* _pWarningsContainer)
:OCollection(_rParent,_bCase,_rMutex,::std::vector< ::rtl::OUString>())
,m_bConstructed(sal_False)
,m_xConnection(_xCon)
,m_pWarningsContainer(_pWarningsContainer)
,m_pRefreshListener(_pRefreshListener)
{
}
// -------------------------------------------------------------------------
void OFilteredContainer::construct(const Reference< XNameAccess >& _rxMasterContainer,
const Sequence< ::rtl::OUString >& _rTableFilter,
const Sequence< ::rtl::OUString >& _rTableTypeFilter)
{
try
{
Reference<XConnection> xCon = m_xConnection;
if ( xCon.is() )
m_xMetaData = xCon->getMetaData();
}
catch(SQLException&)
{
}
m_xMasterContainer = _rxMasterContainer;
if(m_xMasterContainer.is())
{
addMasterContainerListener();
sal_Int32 nTableFilterLen = _rTableFilter.getLength();
connectivity::TStringVector aTableNames;
sal_Bool bNoTableFilters = ((nTableFilterLen == 1) && _rTableFilter[0].equalsAsciiL("%", 1));
if(!bNoTableFilters)
{
Sequence< ::rtl::OUString > aTableFilter = _rTableFilter;
Sequence< ::rtl::OUString > aTableTypeFilter = _rTableTypeFilter;
// build sorted versions of the filter sequences, so the visibility decision is faster
qsort(aTableFilter.getArray(), nTableFilterLen, sizeof(::rtl::OUString), NameCompare);
// as we want to modify nTableFilterLen, remember this
// for wildcard search : remove all table filters which are a wildcard expression and build a WilCard
// for them
::std::vector< WildCard > aWCSearch; // contains the wildcards for the table filter
nTableFilterLen = createWildCardVector(aTableFilter,aWCSearch);
aTableNames.reserve(nTableFilterLen + (aWCSearch.size() * 10));
Sequence< ::rtl::OUString> aNames = m_xMasterContainer->getElementNames();
const ::rtl::OUString* pBegin = aNames.getConstArray();
const ::rtl::OUString* pEnd = pBegin + aNames.getLength();
for(;pBegin != pEnd;++pBegin)
{
if(isNameValid(*pBegin,aTableFilter,aTableTypeFilter,aWCSearch))
aTableNames.push_back(*pBegin);
}
}
else
{
// no filter so insert all names
Sequence< ::rtl::OUString> aNames = m_xMasterContainer->getElementNames();
const ::rtl::OUString* pBegin = aNames.getConstArray();
const ::rtl::OUString* pEnd = pBegin + aNames.getLength();
aTableNames = connectivity::TStringVector(pBegin,pEnd);
}
reFill(aTableNames);
m_bConstructed = sal_True;
}
else
{
construct(_rTableFilter,_rTableTypeFilter);
}
}
//------------------------------------------------------------------------------
void OFilteredContainer::construct(const Sequence< ::rtl::OUString >& _rTableFilter, const Sequence< ::rtl::OUString >& _rTableTypeFilter)
{
try
{
Reference<XConnection> xCon = m_xConnection;
if ( xCon.is() )
m_xMetaData = xCon->getMetaData();
}
catch(SQLException&)
{
}
// build sorted versions of the filter sequences, so the visibility decision is faster
Sequence< ::rtl::OUString > aTableFilter(_rTableFilter);
sal_Int32 nTableFilterLen = aTableFilter.getLength();
if (nTableFilterLen)
qsort(aTableFilter.getArray(), nTableFilterLen, sizeof(::rtl::OUString), NameCompare);
sal_Bool bNoTableFilters = ((nTableFilterLen == 1) && _rTableFilter[0].equalsAsciiL("%", 1));
// as we want to modify nTableFilterLen, remember this
// for wildcard search : remove all table filters which are a wildcard expression and build a WilCard
// for them
::std::vector< WildCard > aWCSearch;
nTableFilterLen = createWildCardVector(aTableFilter,aWCSearch);
try
{
if (m_xMetaData.is())
{
static const ::rtl::OUString sAll = ::rtl::OUString::createFromAscii("%");
Sequence< ::rtl::OUString > sTableTypes = getTableTypeFilter(_rTableTypeFilter);
if ( m_bConstructed && sTableTypes.getLength() == 0 )
return;
Reference< XResultSet > xTables = m_xMetaData->getTables(Any(), sAll, sAll, sTableTypes);
Reference< XRow > xCurrentRow(xTables, UNO_QUERY);
if (xCurrentRow.is())
{
// after creation the set is positioned before the first record, per definitionem
::rtl::OUString sCatalog, sSchema, sName, sType;
::rtl::OUString sComposedName;
// we first collect the names and construct the OTable objects later, as the ctor of the table may need
// another result set from the connection, and some drivers support only one statement per connection
sal_Bool bFilterMatch;
while (xTables->next())
{
sCatalog = xCurrentRow->getString(1);
sSchema = xCurrentRow->getString(2);
sName = xCurrentRow->getString(3);
#if OSL_DEBUG_LEVEL > 0
::rtl::OUString sTableType = xCurrentRow->getString(4);
#endif
// we're not interested in the "wasNull", as the getStrings would return an empty string in
// that case, which is sufficient here
composeTableName(m_xMetaData, sCatalog, sSchema, sName, sComposedName, sal_False,::dbtools::eInDataManipulation);
bFilterMatch = bNoTableFilters
|| ((nTableFilterLen != 0) && (NULL != bsearch(&sComposedName, aTableFilter.getConstArray(), nTableFilterLen, sizeof(::rtl::OUString), NameCompare)));
// the table is allowed to "pass" if we had no filters at all or any of the non-wildcard filters matches
if (!bFilterMatch && aWCSearch.size())
{ // or if one of the wildcrad expression matches
for ( ::std::vector< WildCard >::const_iterator aLoop = aWCSearch.begin();
aLoop != aWCSearch.end() && !bFilterMatch;
++aLoop
)
bFilterMatch = aLoop->Matches(sComposedName);
}
if (bFilterMatch)
{ // the table name is allowed (not filtered out)
insertElement(sComposedName,NULL);
}
}
// dispose the tables result set, in case the connection can handle only one concurrent statement
// (the table object creation will need it's own statements)
disposeComponent(xTables);
}
else
OSL_ENSURE(0,"OFilteredContainer::construct : did not get a XRow from the tables result set !");
}
else
OSL_ENSURE(0,"OFilteredContainer::construct : no connection meta data !");
}
catch (SQLException&)
{
OSL_ENSURE(0,"OFilteredContainer::construct: caught an SQL-Exception !");
disposing();
return;
}
m_bConstructed = sal_True;
}
//------------------------------------------------------------------------------
void OFilteredContainer::disposing()
{
OCollection::disposing();
removeMasterContainerListener();
m_xMasterContainer = NULL;
m_xMetaData = NULL;
m_pWarningsContainer = NULL;
m_pRefreshListener = NULL;
m_bConstructed = sal_False;
}
// -------------------------------------------------------------------------
void OFilteredContainer::impl_refresh() throw(RuntimeException)
{
if ( m_pRefreshListener )
{
m_bConstructed = sal_False;
Reference<XRefreshable> xRefresh(m_xMasterContainer,UNO_QUERY);
if ( xRefresh.is() )
xRefresh->refresh();
m_pRefreshListener->refresh(this);
}
}
// -------------------------------------------------------------------------
sal_Bool OFilteredContainer::isNameValid( const ::rtl::OUString& _rName,
const Sequence< ::rtl::OUString >& _rTableFilter,
const Sequence< ::rtl::OUString >& _rTableTypeFilter,
const ::std::vector< WildCard >& _rWCSearch) const
{
sal_Int32 nTableFilterLen = _rTableFilter.getLength();
sal_Bool bFilterMatch = (NULL != bsearch(&_rName, _rTableFilter.getConstArray(), nTableFilterLen, sizeof(::rtl::OUString), NameCompare));
// the table is allowed to "pass" if we had no filters at all or any of the non-wildcard filters matches
if (!bFilterMatch && !_rWCSearch.empty())
{ // or if one of the wildcrad expression matches
String sWCCompare = (const sal_Unicode*)_rName;
for ( ::std::vector< WildCard >::const_iterator aLoop = _rWCSearch.begin();
aLoop != _rWCSearch.end() && !bFilterMatch;
++aLoop
)
bFilterMatch = aLoop->Matches(sWCCompare);
}
return bFilterMatch;
}
// -----------------------------------------------------------------------------
::rtl::OUString OFilteredContainer::getNameForObject(const ObjectType& _xObject)
{
OSL_ENSURE(_xObject.is(),"OTables::getNameForObject: Object is NULL!");
return ::dbtools::composeTableName(m_xMetaData,_xObject,sal_False,::dbtools::eInDataManipulation);
}
// ..............................................................................
} // namespace
// ..............................................................................
<commit_msg>INTEGRATION: CWS warnings01 (1.6.48); FILE MERGED 2006/03/24 15:35:45 fs 1.6.48.1: #i57457# warning-free code (unxlngi6/.pro + unxsoli4.pro)<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: FilteredContainer.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: hr $ $Date: 2006-06-20 02: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 DBACCESS_CORE_FILTERED_CONTAINER_HXX
#include "FilteredContainer.hxx"
#endif
#ifndef DBA_CORE_REFRESHLISTENER_HXX
#include "RefreshListener.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBC_XROW_HPP_
#include <com/sun/star/sdbc/XRow.hpp>
#endif
#ifndef _CONNECTIVITY_DBTOOLS_HXX_
#include <connectivity/dbtools.hxx>
#endif
#ifndef _WLDCRD_HXX
#include <tools/wldcrd.hxx>
#endif
namespace dbaccess
{
using namespace dbtools;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::sdb;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::util;
using namespace ::com::sun::star::container;
using namespace ::osl;
using namespace ::comphelper;
using namespace ::cppu;
using namespace ::connectivity::sdbcx;
//------------------------------------------------------------------------------
/** creates a vector of WildCards and reduce the _rTableFilter of the length of WildsCards
*/
sal_Int32 createWildCardVector(Sequence< ::rtl::OUString >& _rTableFilter, ::std::vector< WildCard >& _rOut)
{
// for wildcard search : remove all table filters which are a wildcard expression and build a WilCard
// for them
::rtl::OUString* pTableFilters = _rTableFilter.getArray();
::rtl::OUString* pEnd = pTableFilters + _rTableFilter.getLength();
sal_Int32 nShiftPos = 0;
for (sal_Int32 i=0; pEnd != pTableFilters; ++pTableFilters,++i)
{
if (pTableFilters->indexOf('%') != -1)
{
_rOut.push_back(WildCard(pTableFilters->replace('%', '*')));
}
else
{
if (nShiftPos != i)
{
_rTableFilter.getArray()[nShiftPos] = _rTableFilter.getArray()[i];
}
++nShiftPos;
}
}
// now aTableFilter contains nShiftPos non-wc-strings and aWCSearch all wc-strings
_rTableFilter.realloc(nShiftPos);
return nShiftPos;
}
//==========================================================================
//= OViewContainer
//==========================================================================
OFilteredContainer::OFilteredContainer(::cppu::OWeakObject& _rParent,
::osl::Mutex& _rMutex,
const Reference< XConnection >& _xCon,
sal_Bool _bCase,
IRefreshListener* _pRefreshListener,
IWarningsContainer* _pWarningsContainer)
:OCollection(_rParent,_bCase,_rMutex,::std::vector< ::rtl::OUString>())
,m_pWarningsContainer(_pWarningsContainer)
,m_pRefreshListener(_pRefreshListener)
,m_xConnection(_xCon)
,m_bConstructed(sal_False)
{
}
// -------------------------------------------------------------------------
void OFilteredContainer::construct(const Reference< XNameAccess >& _rxMasterContainer,
const Sequence< ::rtl::OUString >& _rTableFilter,
const Sequence< ::rtl::OUString >& _rTableTypeFilter)
{
try
{
Reference<XConnection> xCon = m_xConnection;
if ( xCon.is() )
m_xMetaData = xCon->getMetaData();
}
catch(SQLException&)
{
}
m_xMasterContainer = _rxMasterContainer;
if(m_xMasterContainer.is())
{
addMasterContainerListener();
sal_Int32 nTableFilterLen = _rTableFilter.getLength();
connectivity::TStringVector aTableNames;
sal_Bool bNoTableFilters = ((nTableFilterLen == 1) && _rTableFilter[0].equalsAsciiL("%", 1));
if(!bNoTableFilters)
{
Sequence< ::rtl::OUString > aTableFilter = _rTableFilter;
Sequence< ::rtl::OUString > aTableTypeFilter = _rTableTypeFilter;
// build sorted versions of the filter sequences, so the visibility decision is faster
::std::sort( aTableFilter.getArray(), aTableFilter.getArray() + nTableFilterLen );
// as we want to modify nTableFilterLen, remember this
// for wildcard search : remove all table filters which are a wildcard expression and build a WilCard
// for them
::std::vector< WildCard > aWCSearch; // contains the wildcards for the table filter
nTableFilterLen = createWildCardVector(aTableFilter,aWCSearch);
aTableNames.reserve(nTableFilterLen + (aWCSearch.size() * 10));
Sequence< ::rtl::OUString> aNames = m_xMasterContainer->getElementNames();
const ::rtl::OUString* pBegin = aNames.getConstArray();
const ::rtl::OUString* pEnd = pBegin + aNames.getLength();
for(;pBegin != pEnd;++pBegin)
{
if(isNameValid(*pBegin,aTableFilter,aTableTypeFilter,aWCSearch))
aTableNames.push_back(*pBegin);
}
}
else
{
// no filter so insert all names
Sequence< ::rtl::OUString> aNames = m_xMasterContainer->getElementNames();
const ::rtl::OUString* pBegin = aNames.getConstArray();
const ::rtl::OUString* pEnd = pBegin + aNames.getLength();
aTableNames = connectivity::TStringVector(pBegin,pEnd);
}
reFill(aTableNames);
m_bConstructed = sal_True;
}
else
{
construct(_rTableFilter,_rTableTypeFilter);
}
}
//------------------------------------------------------------------------------
void OFilteredContainer::construct(const Sequence< ::rtl::OUString >& _rTableFilter, const Sequence< ::rtl::OUString >& _rTableTypeFilter)
{
try
{
Reference<XConnection> xCon = m_xConnection;
if ( xCon.is() )
m_xMetaData = xCon->getMetaData();
}
catch(SQLException&)
{
}
// build sorted versions of the filter sequences, so the visibility decision is faster
Sequence< ::rtl::OUString > aTableFilter(_rTableFilter);
sal_Int32 nTableFilterLen = aTableFilter.getLength();
if (nTableFilterLen)
::std::sort( aTableFilter.getArray(), aTableFilter.getArray() + nTableFilterLen );
sal_Bool bNoTableFilters = ((nTableFilterLen == 1) && _rTableFilter[0].equalsAsciiL("%", 1));
// as we want to modify nTableFilterLen, remember this
// for wildcard search : remove all table filters which are a wildcard expression and build a WilCard
// for them
::std::vector< WildCard > aWCSearch;
nTableFilterLen = createWildCardVector(aTableFilter,aWCSearch);
try
{
if (m_xMetaData.is())
{
static const ::rtl::OUString sAll = ::rtl::OUString::createFromAscii("%");
Sequence< ::rtl::OUString > sTableTypes = getTableTypeFilter(_rTableTypeFilter);
if ( m_bConstructed && sTableTypes.getLength() == 0 )
return;
Reference< XResultSet > xTables = m_xMetaData->getTables(Any(), sAll, sAll, sTableTypes);
Reference< XRow > xCurrentRow(xTables, UNO_QUERY);
if (xCurrentRow.is())
{
// after creation the set is positioned before the first record, per definitionem
::rtl::OUString sCatalog, sSchema, sName, sType;
::rtl::OUString sComposedName;
// we first collect the names and construct the OTable objects later, as the ctor of the table may need
// another result set from the connection, and some drivers support only one statement per connection
sal_Bool bFilterMatch;
while (xTables->next())
{
sCatalog = xCurrentRow->getString(1);
sSchema = xCurrentRow->getString(2);
sName = xCurrentRow->getString(3);
#if OSL_DEBUG_LEVEL > 0
::rtl::OUString sTableType = xCurrentRow->getString(4);
#endif
// we're not interested in the "wasNull", as the getStrings would return an empty string in
// that case, which is sufficient here
composeTableName(m_xMetaData, sCatalog, sSchema, sName, sComposedName, sal_False,::dbtools::eInDataManipulation);
const ::rtl::OUString* tableFilter = aTableFilter.getConstArray();
const ::rtl::OUString* tableFilterEnd = aTableFilter.getConstArray() + nTableFilterLen;
bool composedNameInFilter = ::std::find( tableFilter, tableFilterEnd, sComposedName ) != tableFilterEnd;
bFilterMatch = bNoTableFilters
|| ( ( nTableFilterLen != 0 )
&& composedNameInFilter
);
// the table is allowed to "pass" if we had no filters at all or any of the non-wildcard filters matches
if (!bFilterMatch && aWCSearch.size())
{ // or if one of the wildcrad expression matches
for ( ::std::vector< WildCard >::const_iterator aLoop = aWCSearch.begin();
aLoop != aWCSearch.end() && !bFilterMatch;
++aLoop
)
bFilterMatch = aLoop->Matches(sComposedName);
}
if (bFilterMatch)
{ // the table name is allowed (not filtered out)
insertElement(sComposedName,NULL);
}
}
// dispose the tables result set, in case the connection can handle only one concurrent statement
// (the table object creation will need it's own statements)
disposeComponent(xTables);
}
else
OSL_ENSURE(0,"OFilteredContainer::construct : did not get a XRow from the tables result set !");
}
else
OSL_ENSURE(0,"OFilteredContainer::construct : no connection meta data !");
}
catch (SQLException&)
{
OSL_ENSURE(0,"OFilteredContainer::construct: caught an SQL-Exception !");
disposing();
return;
}
m_bConstructed = sal_True;
}
//------------------------------------------------------------------------------
void OFilteredContainer::disposing()
{
OCollection::disposing();
removeMasterContainerListener();
m_xMasterContainer = NULL;
m_xMetaData = NULL;
m_pWarningsContainer = NULL;
m_pRefreshListener = NULL;
m_bConstructed = sal_False;
}
// -------------------------------------------------------------------------
void OFilteredContainer::impl_refresh() throw(RuntimeException)
{
if ( m_pRefreshListener )
{
m_bConstructed = sal_False;
Reference<XRefreshable> xRefresh(m_xMasterContainer,UNO_QUERY);
if ( xRefresh.is() )
xRefresh->refresh();
m_pRefreshListener->refresh(this);
}
}
// -------------------------------------------------------------------------
sal_Bool OFilteredContainer::isNameValid( const ::rtl::OUString& _rName,
const Sequence< ::rtl::OUString >& _rTableFilter,
const Sequence< ::rtl::OUString >& /*_rTableTypeFilter*/,
const ::std::vector< WildCard >& _rWCSearch) const
{
sal_Int32 nTableFilterLen = _rTableFilter.getLength();
const ::rtl::OUString* tableFilter = _rTableFilter.getConstArray();
const ::rtl::OUString* tableFilterEnd = _rTableFilter.getConstArray() + nTableFilterLen;
bool bFilterMatch = ::std::find( tableFilter, tableFilterEnd, _rName ) != tableFilterEnd;
// the table is allowed to "pass" if we had no filters at all or any of the non-wildcard filters matches
if (!bFilterMatch && !_rWCSearch.empty())
{ // or if one of the wildcrad expression matches
String sWCCompare = (const sal_Unicode*)_rName;
for ( ::std::vector< WildCard >::const_iterator aLoop = _rWCSearch.begin();
aLoop != _rWCSearch.end() && !bFilterMatch;
++aLoop
)
bFilterMatch = aLoop->Matches(sWCCompare);
}
return bFilterMatch;
}
// -----------------------------------------------------------------------------
::rtl::OUString OFilteredContainer::getNameForObject(const ObjectType& _xObject)
{
OSL_ENSURE(_xObject.is(),"OTables::getNameForObject: Object is NULL!");
return ::dbtools::composeTableName(m_xMetaData,_xObject,sal_False,::dbtools::eInDataManipulation);
}
// ..............................................................................
} // namespace
// ..............................................................................
<|endoftext|>
|
<commit_before>#include "jni_helper.hpp"
#include "logging.hpp"
#include "../../../../../base/assert.hpp"
static JavaVM * g_jvm = 0;
// @TODO remove after refactoring. Needed for NVidia code
void InitNVEvent(JavaVM * jvm);
extern "C"
{
JNIEXPORT jint JNICALL
JNI_OnLoad(JavaVM * jvm, void *)
{
g_jvm = jvm;
jni::InitSystemLog();
jni::InitAssertLog();
// @TODO remove line below after refactoring
InitNVEvent(jvm);
return JNI_VERSION_1_6;
}
JNIEXPORT void JNICALL
JNI_OnUnload(JavaVM *, void *)
{
g_jvm = 0;
}
} // extern "C"
namespace jni
{
jmethodID GetJavaMethodID(JNIEnv * env, jobject obj, char const * fn, char const * sig)
{
ASSERT(env, ("JNIEnv can't be 0"));
ASSERT(obj, ("jobject can't be 0"));
jclass cls = env->GetObjectClass(obj);
ASSERT(cls, ("Can't get class: ", DescribeException()));
jmethodID mid = env->GetMethodID(cls, fn, sig);
ASSERT(mid, ("Can't get methodID", fn, sig, DescribeException()));
return mid;
}
/*
jobject CreateJavaObject(JNIEnv * env, char const * klassName, char const * sig, ...)
{
jclass klass = env->FindClass(klassName);
ASSERT(klass, ("Can't find java class", klassName));
jmethodID methodId = env->GetMethodID(klass, "<init>", sig);
ASSERT(methodId, ("Can't find java constructor", sig));
va_list args;
va_start(args, sig);
jobject res = env->NewObject(klass, methodId, args);
ASSERT(res, ());
va_end(args);
return res;
}
*/
string ToNativeString(JNIEnv * env, jstring str)
{
string result;
char const * utfBuffer = env->GetStringUTFChars(str, 0);
if (utfBuffer)
{
result = utfBuffer;
env->ReleaseStringUTFChars(str, utfBuffer);
}
return result;
}
jstring ToJavaString(JNIEnv * env, char const * s)
{
return env->NewStringUTF(s);
}
JNIEnv * GetEnv()
{
JNIEnv * env;
if (JNI_OK != g_jvm->GetEnv((void **)&env, JNI_VERSION_1_6))
{
ASSERT(false, ("Can't get JNIEnv. Was thread attached to JVM?"));
return 0;
}
return env;
}
JavaVM * GetJVM()
{
ASSERT(g_jvm, ("JVM is not initialized"));
return g_jvm;
}
struct global_ref_deleter
{
void operator()(jobject * ref)
{
jni::GetEnv()->DeleteGlobalRef(*ref);
delete ref;
}
};
shared_ptr<jobject> make_global_ref(jobject obj)
{
jobject * ref = new jobject;
*ref = jni::GetEnv()->NewGlobalRef(obj);
return shared_ptr<jobject>(ref, global_ref_deleter());
}
string DescribeException()
{
JNIEnv * env = jni::GetEnv();
if (env->ExceptionCheck())
{
jthrowable e = env->ExceptionOccurred();
// have to clear the exception before JNI will work again.
env->ExceptionClear();
jclass eclass = env->GetObjectClass(e);
jmethodID mid = env->GetMethodID(eclass, "toString", "()Ljava/lang/String;");
jstring jErrorMsg = (jstring) env->CallObjectMethod(e, mid);
return ToNativeString(env, jErrorMsg);
}
return "";
}
} // namespace jni
<commit_msg>[android] fixed exception unwinding issue on android 2.1<commit_after>#include "jni_helper.hpp"
#include "logging.hpp"
#include "../../../../../base/assert.hpp"
static JavaVM * g_jvm = 0;
// @TODO remove after refactoring. Needed for NVidia code
void InitNVEvent(JavaVM * jvm);
extern "C"
{
/// fix for stack unwinding problem during exception handling on Android 2.1
/// http://code.google.com/p/android/issues/detail?id=20176
#ifndef _MIPSEL
typedef long unsigned int *_Unwind_Ptr;
/* Stubbed out in libdl and defined in the dynamic linker.
* Same semantics as __gnu_Unwind_Find_exidx().
*/
_Unwind_Ptr dl_unwind_find_exidx(_Unwind_Ptr pc, int *pcount);
_Unwind_Ptr __gnu_Unwind_Find_exidx(_Unwind_Ptr pc, int *pcount)
{
return dl_unwind_find_exidx(pc, pcount);
}
static void* g_func_ptr;
#endif
JNIEXPORT jint JNICALL
JNI_OnLoad(JavaVM * jvm, void *)
{
/// fix for stack unwinding problem during exception handling on Android 2.1
/// http://code.google.com/p/android/issues/detail?id=20176
#ifndef _MIPSEL
// when i throw exception, linker maybe can't find __gnu_Unwind_Find_exidx(lazy binding issue??)
// so I force to bind this symbol at shared object load time
g_func_ptr = (void*)__gnu_Unwind_Find_exidx;
#endif
g_jvm = jvm;
jni::InitSystemLog();
jni::InitAssertLog();
// @TODO remove line below after refactoring
InitNVEvent(jvm);
return JNI_VERSION_1_6;
}
JNIEXPORT void JNICALL
JNI_OnUnload(JavaVM *, void *)
{
g_jvm = 0;
}
} // extern "C"
namespace jni
{
jmethodID GetJavaMethodID(JNIEnv * env, jobject obj, char const * fn, char const * sig)
{
ASSERT(env, ("JNIEnv can't be 0"));
ASSERT(obj, ("jobject can't be 0"));
jclass cls = env->GetObjectClass(obj);
ASSERT(cls, ("Can't get class: ", DescribeException()));
jmethodID mid = env->GetMethodID(cls, fn, sig);
ASSERT(mid, ("Can't get methodID", fn, sig, DescribeException()));
return mid;
}
/*
jobject CreateJavaObject(JNIEnv * env, char const * klassName, char const * sig, ...)
{
jclass klass = env->FindClass(klassName);
ASSERT(klass, ("Can't find java class", klassName));
jmethodID methodId = env->GetMethodID(klass, "<init>", sig);
ASSERT(methodId, ("Can't find java constructor", sig));
va_list args;
va_start(args, sig);
jobject res = env->NewObject(klass, methodId, args);
ASSERT(res, ());
va_end(args);
return res;
}
*/
string ToNativeString(JNIEnv * env, jstring str)
{
string result;
char const * utfBuffer = env->GetStringUTFChars(str, 0);
if (utfBuffer)
{
result = utfBuffer;
env->ReleaseStringUTFChars(str, utfBuffer);
}
return result;
}
jstring ToJavaString(JNIEnv * env, char const * s)
{
return env->NewStringUTF(s);
}
JNIEnv * GetEnv()
{
JNIEnv * env;
if (JNI_OK != g_jvm->GetEnv((void **)&env, JNI_VERSION_1_6))
{
ASSERT(false, ("Can't get JNIEnv. Was thread attached to JVM?"));
return 0;
}
return env;
}
JavaVM * GetJVM()
{
ASSERT(g_jvm, ("JVM is not initialized"));
return g_jvm;
}
struct global_ref_deleter
{
void operator()(jobject * ref)
{
jni::GetEnv()->DeleteGlobalRef(*ref);
delete ref;
}
};
shared_ptr<jobject> make_global_ref(jobject obj)
{
jobject * ref = new jobject;
*ref = jni::GetEnv()->NewGlobalRef(obj);
return shared_ptr<jobject>(ref, global_ref_deleter());
}
string DescribeException()
{
JNIEnv * env = jni::GetEnv();
if (env->ExceptionCheck())
{
jthrowable e = env->ExceptionOccurred();
// have to clear the exception before JNI will work again.
env->ExceptionClear();
jclass eclass = env->GetObjectClass(e);
jmethodID mid = env->GetMethodID(eclass, "toString", "()Ljava/lang/String;");
jstring jErrorMsg = (jstring) env->CallObjectMethod(e, mid);
return ToNativeString(env, jErrorMsg);
}
return "";
}
} // namespace jni
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2010-2011 Sune Vuorela <sune@vuorela.dk>
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
#include "barcodewidget.h"
#include "abstractbarcode.h"
#include <QResizeEvent>
#include <QPainter>
using namespace prison;
/**
* @cond PRIVATE
*/
class BarcodeWidget::Private {
public:
AbstractBarcode* m_barcode;
BarcodeWidget* q;
Private(AbstractBarcode* barcode,BarcodeWidget* parent) : m_barcode(barcode), q(parent) {
}
};
/**
* @endcond
*/
BarcodeWidget::BarcodeWidget(QWidget* parent): QWidget(parent), d(new BarcodeWidget::Private(0,this)) {
}
BarcodeWidget::BarcodeWidget(AbstractBarcode* barcode, QWidget* parent) : QWidget(parent), d(new BarcodeWidget::Private(barcode,this)) {
}
void BarcodeWidget::setData(QString data) {
if(d->m_barcode)
d->m_barcode->setData(data);
updateGeometry();
repaint();
}
void BarcodeWidget::paintEvent(QPaintEvent* event) {
QPainter painter(this);
if(d->m_barcode) {
d->m_barcode->paint(&painter,QRectF(QPointF(0,0),size()));
} else {
painter.fillRect(QRectF(QPointF(0,0),size()),Qt::black);
}
QWidget::paintEvent(event);
}
void BarcodeWidget::resizeEvent(QResizeEvent* event) {
if(d->m_barcode) {
updateGeometry();
repaint();
}
QWidget::resizeEvent(event);
}
void BarcodeWidget::mousePressEvent(QMouseEvent* event) {
if(event->buttons() & Qt::LeftButton) {
QMimeData* data = new QMimeData();
data->setImageData(d->m_barcode->toImage(size()));
QDrag* drag = new QDrag(this);
drag->setMimeData(data);
drag->exec();
}
QWidget::mousePressEvent(event);
}
QSize BarcodeWidget::minimumSizeHint() const
{
if(d->m_barcode) {
return d->m_barcode->minimumSize().toSize();
} else {
return QWidget::minimumSizeHint();
}
}
prison::BarcodeWidget::~BarcodeWidget() {
delete d->m_barcode;
delete d;
}
void BarcodeWidget::setBarcode(AbstractBarcode* barcode) {
delete d->m_barcode;
d->m_barcode=barcode;
}
<commit_msg>call updateGeometry a extra time<commit_after>/*
Copyright (c) 2010-2011 Sune Vuorela <sune@vuorela.dk>
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
#include "barcodewidget.h"
#include "abstractbarcode.h"
#include <QResizeEvent>
#include <QPainter>
using namespace prison;
/**
* @cond PRIVATE
*/
class BarcodeWidget::Private {
public:
AbstractBarcode* m_barcode;
BarcodeWidget* q;
Private(AbstractBarcode* barcode,BarcodeWidget* parent) : m_barcode(barcode), q(parent) {
}
};
/**
* @endcond
*/
BarcodeWidget::BarcodeWidget(QWidget* parent): QWidget(parent), d(new BarcodeWidget::Private(0,this)) {
}
BarcodeWidget::BarcodeWidget(AbstractBarcode* barcode, QWidget* parent) : QWidget(parent), d(new BarcodeWidget::Private(barcode,this)) {
}
void BarcodeWidget::setData(QString data) {
if(d->m_barcode)
d->m_barcode->setData(data);
updateGeometry();
repaint();
}
void BarcodeWidget::paintEvent(QPaintEvent* event) {
QPainter painter(this);
if(d->m_barcode) {
d->m_barcode->paint(&painter,QRectF(QPointF(0,0),size()));
updateGeometry();
} else {
painter.fillRect(QRectF(QPointF(0,0),size()),Qt::black);
}
QWidget::paintEvent(event);
}
void BarcodeWidget::resizeEvent(QResizeEvent* event) {
if(d->m_barcode) {
updateGeometry();
repaint();
}
QWidget::resizeEvent(event);
}
void BarcodeWidget::mousePressEvent(QMouseEvent* event) {
if(event->buttons() & Qt::LeftButton) {
QMimeData* data = new QMimeData();
data->setImageData(d->m_barcode->toImage(size()));
QDrag* drag = new QDrag(this);
drag->setMimeData(data);
drag->exec();
}
QWidget::mousePressEvent(event);
}
QSize BarcodeWidget::minimumSizeHint() const
{
if(d->m_barcode) {
return d->m_barcode->minimumSize().toSize();
} else {
return QWidget::minimumSizeHint();
}
}
prison::BarcodeWidget::~BarcodeWidget() {
delete d->m_barcode;
delete d;
}
void BarcodeWidget::setBarcode(AbstractBarcode* barcode) {
delete d->m_barcode;
d->m_barcode=barcode;
}
<|endoftext|>
|
<commit_before>#include "ebc/BitcodeRetriever.h"
#include "ebc/BitcodeArchive.h"
#include "ebc/BitcodeContainer.h"
#include "ebc/BitcodeMetadata.h"
#include "ebc/EbcError.h"
#include "ebc/util/Xar.h"
#include "llvm/ADT/Triple.h"
#include "llvm/Object/ELFObjectFile.h"
#include "llvm/Object/MachO.h"
#include "llvm/Object/MachOUniversal.h"
#include "llvm/Support/Error.h"
#include "llvm/Support/ErrorHandling.h"
#include <algorithm>
#include <iostream>
#include <memory>
#include <string>
using namespace llvm;
using namespace llvm::object;
namespace ebc {
/// Strip path from file name.
static std::string GetFileName(std::string fileName) {
auto pos = fileName.rfind('/');
return pos == std::string::npos ? fileName : fileName.substr(pos + 1);
}
/// Internal EBC error that extends LLVM's ErrorInfo class. We use this to have
/// the implementation return llvm::Expected<> objects.
class InternalEbcError : public llvm::ErrorInfo<InternalEbcError> {
public:
static char ID;
InternalEbcError(std::string msg) : _msg(std::move(msg)) {}
~InternalEbcError(){};
const std::string &getMessage() const {
return _msg;
}
std::error_code convertToErrorCode() const override {
llvm_unreachable("Not implemented");
}
void log(llvm::raw_ostream &OS) const override {
OS << _msg;
}
private:
std::string _msg;
};
char InternalEbcError::ID = 0;
/// Convert an LLVM error object to an EbcError. This works both for LLVM's
/// internal errors as well as for our custom InternalEbcError.
static EbcError ToEbcError(llvm::Error &&e) {
std::string msg;
handleAllErrors(std::move(e), [&msg](llvm::ErrorInfoBase &eib) { msg = eib.message(); });
return EbcError(msg);
}
class BitcodeRetriever::Impl {
public:
typedef std::vector<std::unique_ptr<BitcodeContainer>> BitcodeContainers;
Impl(std::string objectPath) : _objectPath(std::move(objectPath)) {}
/// Set the architecture for which to retrieve bitcode. This is relevant to
/// 'fat' object files containing multiple architectures. If no architecture
/// is set, bitcode is retrieved for all present architectures.
void SetArch(std::string arch) {
_arch = std::move(arch);
}
/// Perform the actual bitcode retrieval. Depending on the type of the object
/// file the resulting list contains plain bitcode containers or bitcode
/// archives.
///
/// @return A list of bitcode containers.
BitcodeContainers GetBitcodeContainers() {
auto binaryOrErr = createBinary(_objectPath);
if (!binaryOrErr) {
if (util::xar::IsXarFile(_objectPath)) {
llvm::consumeError(binaryOrErr.takeError());
auto bitcodeContainers = GetBitcodeContainersFromXar(_objectPath);
if (!bitcodeContainers) {
throw ToEbcError(bitcodeContainers.takeError());
}
return std::move(*bitcodeContainers);
} else {
throw ToEbcError(binaryOrErr.takeError());
}
}
auto bitcodeContainers = GetBitcodeContainers(*binaryOrErr->getBinary());
if (!bitcodeContainers) {
throw ToEbcError(bitcodeContainers.takeError());
}
return std::move(*bitcodeContainers);
}
private:
/// Helper method for determining whether the given architecture should be
/// handled.
///
/// @param arch The architecture.
///
/// @return True if the architecture matches the set architure or when no
/// architecture is set. False otherwise.
bool processArch(const std::string &arch) const {
return _arch.empty() ? true : (_arch == arch);
}
llvm::Expected<BitcodeContainers> GetBitcodeContainersFromXar(const std::string &xar) {
auto bitcodeArchive = BitcodeArchive::BitcodeArchiveFromFile(xar);
if (bitcodeArchive) {
bitcodeArchive->GetBinaryMetadata().SetFileName(GetFileName(xar));
auto bitcodeContainers = std::vector<std::unique_ptr<BitcodeContainer>>();
bitcodeContainers.push_back(std::move(bitcodeArchive));
return std::move(bitcodeContainers);
}
return llvm::make_error<InternalEbcError>("Could not create bitcode archive form Xar.");
}
/// Obtains all bitcode from an object. The method basically determines the
/// kind of object and dispatches the actual work to the specialized method.
///
/// @param binary The binary object.
///
/// @return A list of bitcode containers.
llvm::Expected<BitcodeContainers> GetBitcodeContainers(const llvm::object::Binary &binary) const {
auto bitcodeContainers = std::vector<std::unique_ptr<BitcodeContainer>>();
if (const auto *universalBinary = dyn_cast<MachOUniversalBinary>(&binary)) {
// Iterate over all objects (i.e. architectures):
for (auto object : universalBinary->objects()) {
Expected<std::unique_ptr<MachOObjectFile>> machOObject = object.getAsObjectFile();
if (machOObject) {
auto container = GetBitcodeContainerFromMachO(machOObject->get());
if (!container) {
return container.takeError();
}
// Check for nullptr for when we only consider one architecture.
if (container.get()) {
bitcodeContainers.push_back(std::move(*container));
}
continue;
} else {
llvm::consumeError(machOObject.takeError());
}
Expected<std::unique_ptr<Archive>> archive = object.getAsArchive();
if (archive) {
auto containers = GetBitcodeContainersFromArchive(*archive->get());
if (!containers) {
return containers.takeError();
}
// We have to move all valid containers so we can move on to the next
// architecture.
bitcodeContainers.reserve(bitcodeContainers.size() + containers->size());
std::copy_if(std::make_move_iterator(containers->begin()), std::make_move_iterator(containers->end()),
std::back_inserter(bitcodeContainers),
[](const auto &uniquePtr) { return uniquePtr != nullptr; });
continue;
} else {
llvm::consumeError(archive.takeError());
}
}
} else if (const auto machOObjectFile = dyn_cast<MachOObjectFile>(&binary)) {
auto container = GetBitcodeContainerFromMachO(machOObjectFile);
if (!container) {
return container.takeError();
}
// Check for nullptr for when we only consider one architecture.
if (container.get()) {
bitcodeContainers.push_back(std::move(*container));
}
} else if (const auto object = dyn_cast<ObjectFile>(&binary)) {
auto container = GetBitcodeContainerFromObject(object);
if (!container) {
return container.takeError();
}
// Check for nullptr for when we only consider one architecture.
if (container.get()) {
bitcodeContainers.push_back(std::move(*container));
}
} else if (const auto archive = dyn_cast<Archive>(&binary)) {
// We can return early to prevent moving all containers in the vector.
return GetBitcodeContainersFromArchive(*archive);
} else {
return llvm::make_error<InternalEbcError>("Unsupported binary");
}
return std::move(bitcodeContainers);
}
/// Obtains all bitcode from an object archive.
///
/// @param archive The object archive.
///
/// @return A list of bitcode containers.
llvm::Expected<BitcodeContainers> GetBitcodeContainersFromArchive(const llvm::object::Archive &archive) const {
Error err = Error::success();
auto bitcodeContainers = std::vector<std::unique_ptr<BitcodeContainer>>();
for (const auto &child : archive.children(err)) {
auto childOrErr = child.getAsBinary();
if (!childOrErr) {
return childOrErr.takeError();
}
auto containers = GetBitcodeContainers(*(*childOrErr));
if (!containers) {
return containers.takeError();
}
bitcodeContainers.reserve(bitcodeContainers.size() + containers->size());
std::move(containers->begin(), containers->end(), std::back_inserter(bitcodeContainers));
}
if (err) {
return std::move(err);
}
return std::move(bitcodeContainers);
}
/// Reads bitcode from a Mach O object file.
///
/// @param objectFile The Mach O object file.
///
/// @return The bitcode container.
llvm::Expected<std::unique_ptr<BitcodeContainer>> GetBitcodeContainerFromMachO(
const llvm::object::MachOObjectFile *objectFile) const {
// For MachO return the correct arch tripple.
const std::string arch = objectFile->getArchTriple(nullptr).getArchName();
if (!processArch(arch)) {
return nullptr;
}
BitcodeContainer *bitcodeContainer = nullptr;
const std::string name = objectFile->getFileFormatName().str();
std::vector<std::string> commands;
for (const SectionRef §ion : objectFile->sections()) {
// Get section name
DataRefImpl dataRef = section.getRawDataRefImpl();
StringRef segName = objectFile->getSectionFinalSegmentName(dataRef);
if (segName == "__LLVM") {
StringRef sectName;
section.getName(sectName);
if (sectName == "__bundle") {
// Embedded bitcode in universal binary.
auto data = GetSectionData(section);
bitcodeContainer = new BitcodeArchive(data.first, data.second);
} else if (sectName == "__bitcode") {
// Embedded bitcode in single MachO object.
auto data = GetSectionData(section);
bitcodeContainer = new BitcodeContainer(data.first, data.second);
} else if (sectName == "__cmd" || sectName == "__cmdline") {
commands = GetCommands(section);
}
}
}
if (bitcodeContainer == nullptr) {
return llvm::make_error<InternalEbcError>("No bitcode section in " + objectFile->getFileName().str());
}
// Set commands
bitcodeContainer->SetCommands(commands);
// Set binary metadata
bitcodeContainer->GetBinaryMetadata().SetFileName(GetFileName(objectFile->getFileName()));
bitcodeContainer->GetBinaryMetadata().SetFileFormatName(objectFile->getFileFormatName());
bitcodeContainer->GetBinaryMetadata().SetArch(arch);
bitcodeContainer->GetBinaryMetadata().SetUuid(objectFile->getUuid().data());
return std::unique_ptr<BitcodeContainer>(bitcodeContainer);
}
/// Reads bitcode from a plain object file.
///
/// @param objectFile The Mach O object file.
///
/// @return The bitcode container.
llvm::Expected<std::unique_ptr<BitcodeContainer>> GetBitcodeContainerFromObject(
const llvm::object::ObjectFile *objectFile) const {
const auto arch = llvm::Triple::getArchTypeName(static_cast<Triple::ArchType>(objectFile->getArch()));
if (!processArch(arch)) {
return nullptr;
}
BitcodeContainer *bitcodeContainer = nullptr;
std::vector<std::string> commands;
for (const SectionRef §ion : objectFile->sections()) {
StringRef sectName;
section.getName(sectName);
if (sectName == ".llvmbc") {
auto data = GetSectionData(section);
bitcodeContainer = new BitcodeContainer(data.first, data.second);
} else if (sectName == ".llvmcmd") {
commands = GetCommands(section);
}
}
if (bitcodeContainer == nullptr) {
return llvm::make_error<InternalEbcError>("No bitcode section in " + objectFile->getFileName().str());
}
// Set commands
bitcodeContainer->SetCommands(commands);
// Set binary metadata
bitcodeContainer->GetBinaryMetadata().SetFileName(GetFileName(objectFile->getFileName()));
bitcodeContainer->GetBinaryMetadata().SetFileFormatName(objectFile->getFileFormatName());
bitcodeContainer->GetBinaryMetadata().SetArch(arch);
return std::unique_ptr<BitcodeContainer>(bitcodeContainer);
}
/// Obtains data from a section.
///
/// @param section The section from which the data should be obtained.
///
/// @return A pair with the data and the size of the data.
static std::pair<const char *, std::uint32_t> GetSectionData(const llvm::object::SectionRef §ion) {
StringRef bytesStr;
section.getContents(bytesStr);
const char *sect = reinterpret_cast<const char *>(bytesStr.data());
uint32_t sect_size = bytesStr.size();
return std::make_pair(sect, sect_size);
}
/// Obtains compiler commands from a section. It automatically parses the
/// data into a vector.
///
/// @param section The sectio from which to read the compiler commands.
///
/// @return A vector of compiler commands.
static std::vector<std::string> GetCommands(const llvm::object::SectionRef §ion) {
auto data = GetSectionData(section);
const char *p = data.first;
const char *end = data.first + data.second;
// Create list of strings from commands separated by null bytes.
std::vector<std::string> cmds;
do {
// Creating a string from p consumes data until next null byte.
cmds.push_back(std::string(p));
// Continue after the null byte.
p += cmds.back().size() + 1;
} while (p < end);
return cmds;
}
std::string _objectPath;
std::string _arch;
};
BitcodeRetriever::BitcodeRetriever(std::string objectPath) : _impl(std::make_unique<Impl>(std::move(objectPath))) {}
BitcodeRetriever::~BitcodeRetriever() = default;
void BitcodeRetriever::SetArch(std::string arch) {
_impl->SetArch(std::move(arch));
}
std::vector<std::unique_ptr<BitcodeContainer>> BitcodeRetriever::GetBitcodeContainers() {
return _impl->GetBitcodeContainers();
}
} // namespace ebc
<commit_msg>Fix unchecked LLVM expected<commit_after>#include "ebc/BitcodeRetriever.h"
#include "ebc/BitcodeArchive.h"
#include "ebc/BitcodeContainer.h"
#include "ebc/BitcodeMetadata.h"
#include "ebc/EbcError.h"
#include "ebc/util/Xar.h"
#include "llvm/ADT/Triple.h"
#include "llvm/Object/ELFObjectFile.h"
#include "llvm/Object/MachO.h"
#include "llvm/Object/MachOUniversal.h"
#include "llvm/Support/Error.h"
#include "llvm/Support/ErrorHandling.h"
#include <algorithm>
#include <iostream>
#include <memory>
#include <string>
using namespace llvm;
using namespace llvm::object;
namespace ebc {
/// Strip path from file name.
static std::string GetFileName(std::string fileName) {
auto pos = fileName.rfind('/');
return pos == std::string::npos ? fileName : fileName.substr(pos + 1);
}
/// Internal EBC error that extends LLVM's ErrorInfo class. We use this to have
/// the implementation return llvm::Expected<> objects.
class InternalEbcError : public llvm::ErrorInfo<InternalEbcError> {
public:
static char ID;
InternalEbcError(std::string msg) : _msg(std::move(msg)) {}
~InternalEbcError(){};
const std::string &getMessage() const {
return _msg;
}
std::error_code convertToErrorCode() const override {
llvm_unreachable("Not implemented");
}
void log(llvm::raw_ostream &OS) const override {
OS << _msg;
}
private:
std::string _msg;
};
char InternalEbcError::ID = 0;
/// Convert an LLVM error object to an EbcError. This works both for LLVM's
/// internal errors as well as for our custom InternalEbcError.
static EbcError ToEbcError(llvm::Error &&e) {
std::string msg;
handleAllErrors(std::move(e), [&msg](llvm::ErrorInfoBase &eib) { msg = eib.message(); });
return EbcError(msg);
}
class BitcodeRetriever::Impl {
public:
typedef std::vector<std::unique_ptr<BitcodeContainer>> BitcodeContainers;
Impl(std::string objectPath) : _objectPath(std::move(objectPath)) {}
/// Set the architecture for which to retrieve bitcode. This is relevant to
/// 'fat' object files containing multiple architectures. If no architecture
/// is set, bitcode is retrieved for all present architectures.
void SetArch(std::string arch) {
_arch = std::move(arch);
}
/// Perform the actual bitcode retrieval. Depending on the type of the object
/// file the resulting list contains plain bitcode containers or bitcode
/// archives.
///
/// @return A list of bitcode containers.
BitcodeContainers GetBitcodeContainers() {
auto binaryOrErr = createBinary(_objectPath);
if (!binaryOrErr) {
if (util::xar::IsXarFile(_objectPath)) {
llvm::consumeError(binaryOrErr.takeError());
auto bitcodeContainers = GetBitcodeContainersFromXar(_objectPath);
if (!bitcodeContainers) {
throw ToEbcError(bitcodeContainers.takeError());
}
return std::move(*bitcodeContainers);
} else {
throw ToEbcError(binaryOrErr.takeError());
}
}
auto bitcodeContainers = GetBitcodeContainers(*binaryOrErr->getBinary());
if (!bitcodeContainers) {
throw ToEbcError(bitcodeContainers.takeError());
}
return std::move(*bitcodeContainers);
}
private:
/// Helper method for determining whether the given architecture should be
/// handled.
///
/// @param arch The architecture.
///
/// @return True if the architecture matches the set architure or when no
/// architecture is set. False otherwise.
bool processArch(const std::string &arch) const {
return _arch.empty() ? true : (_arch == arch);
}
llvm::Expected<BitcodeContainers> GetBitcodeContainersFromXar(const std::string &xar) {
auto bitcodeArchive = BitcodeArchive::BitcodeArchiveFromFile(xar);
if (bitcodeArchive) {
bitcodeArchive->GetBinaryMetadata().SetFileName(GetFileName(xar));
auto bitcodeContainers = std::vector<std::unique_ptr<BitcodeContainer>>();
bitcodeContainers.push_back(std::move(bitcodeArchive));
return std::move(bitcodeContainers);
}
return llvm::make_error<InternalEbcError>("Could not create bitcode archive form Xar.");
}
/// Obtains all bitcode from an object. The method basically determines the
/// kind of object and dispatches the actual work to the specialized method.
///
/// @param binary The binary object.
///
/// @return A list of bitcode containers.
llvm::Expected<BitcodeContainers> GetBitcodeContainers(const llvm::object::Binary &binary) const {
auto bitcodeContainers = std::vector<std::unique_ptr<BitcodeContainer>>();
if (const auto *universalBinary = dyn_cast<MachOUniversalBinary>(&binary)) {
// Iterate over all objects (i.e. architectures):
for (auto object : universalBinary->objects()) {
Expected<std::unique_ptr<MachOObjectFile>> machOObject = object.getAsObjectFile();
if (machOObject) {
auto container = GetBitcodeContainerFromMachO(machOObject->get());
if (!container) {
return container.takeError();
}
// Check for nullptr for when we only consider one architecture.
if (container.get()) {
bitcodeContainers.push_back(std::move(*container));
}
continue;
} else {
llvm::consumeError(machOObject.takeError());
}
Expected<std::unique_ptr<Archive>> archive = object.getAsArchive();
if (archive) {
auto containers = GetBitcodeContainersFromArchive(*archive->get());
if (!containers) {
return containers.takeError();
}
// We have to move all valid containers so we can move on to the next
// architecture.
bitcodeContainers.reserve(bitcodeContainers.size() + containers->size());
std::copy_if(std::make_move_iterator(containers->begin()), std::make_move_iterator(containers->end()),
std::back_inserter(bitcodeContainers),
[](const auto &uniquePtr) { return uniquePtr != nullptr; });
continue;
} else {
llvm::consumeError(archive.takeError());
}
}
} else if (const auto machOObjectFile = dyn_cast<MachOObjectFile>(&binary)) {
auto container = GetBitcodeContainerFromMachO(machOObjectFile);
if (!container) {
return container.takeError();
}
// Check for nullptr for when we only consider one architecture.
if (container.get()) {
bitcodeContainers.push_back(std::move(*container));
}
} else if (const auto object = dyn_cast<ObjectFile>(&binary)) {
auto container = GetBitcodeContainerFromObject(object);
if (!container) {
return container.takeError();
}
// Check for nullptr for when we only consider one architecture.
if (container.get()) {
bitcodeContainers.push_back(std::move(*container));
}
} else if (const auto archive = dyn_cast<Archive>(&binary)) {
// We can return early to prevent moving all containers in the vector.
return GetBitcodeContainersFromArchive(*archive);
} else {
return llvm::make_error<InternalEbcError>("Unsupported binary");
}
return std::move(bitcodeContainers);
}
/// Obtains all bitcode from an object archive.
///
/// @param archive The object archive.
///
/// @return A list of bitcode containers.
llvm::Expected<BitcodeContainers> GetBitcodeContainersFromArchive(const llvm::object::Archive &archive) const {
Error err = Error::success();
auto bitcodeContainers = std::vector<std::unique_ptr<BitcodeContainer>>();
for (const auto &child : archive.children(err)) {
if (err) {
return std::move(err);
}
auto childOrErr = child.getAsBinary();
if (!childOrErr) {
return childOrErr.takeError();
}
auto containers = GetBitcodeContainers(*(*childOrErr));
if (!containers) {
return containers.takeError();
}
bitcodeContainers.reserve(bitcodeContainers.size() + containers->size());
std::move(containers->begin(), containers->end(), std::back_inserter(bitcodeContainers));
}
return std::move(bitcodeContainers);
}
/// Reads bitcode from a Mach O object file.
///
/// @param objectFile The Mach O object file.
///
/// @return The bitcode container.
llvm::Expected<std::unique_ptr<BitcodeContainer>> GetBitcodeContainerFromMachO(
const llvm::object::MachOObjectFile *objectFile) const {
// For MachO return the correct arch tripple.
const std::string arch = objectFile->getArchTriple(nullptr).getArchName();
if (!processArch(arch)) {
return nullptr;
}
BitcodeContainer *bitcodeContainer = nullptr;
const std::string name = objectFile->getFileFormatName().str();
std::vector<std::string> commands;
for (const SectionRef §ion : objectFile->sections()) {
// Get section name
DataRefImpl dataRef = section.getRawDataRefImpl();
StringRef segName = objectFile->getSectionFinalSegmentName(dataRef);
if (segName == "__LLVM") {
StringRef sectName;
section.getName(sectName);
if (sectName == "__bundle") {
// Embedded bitcode in universal binary.
auto data = GetSectionData(section);
bitcodeContainer = new BitcodeArchive(data.first, data.second);
} else if (sectName == "__bitcode") {
// Embedded bitcode in single MachO object.
auto data = GetSectionData(section);
bitcodeContainer = new BitcodeContainer(data.first, data.second);
} else if (sectName == "__cmd" || sectName == "__cmdline") {
commands = GetCommands(section);
}
}
}
if (bitcodeContainer == nullptr) {
return llvm::make_error<InternalEbcError>("No bitcode section in " + objectFile->getFileName().str());
}
// Set commands
bitcodeContainer->SetCommands(commands);
// Set binary metadata
bitcodeContainer->GetBinaryMetadata().SetFileName(GetFileName(objectFile->getFileName()));
bitcodeContainer->GetBinaryMetadata().SetFileFormatName(objectFile->getFileFormatName());
bitcodeContainer->GetBinaryMetadata().SetArch(arch);
bitcodeContainer->GetBinaryMetadata().SetUuid(objectFile->getUuid().data());
return std::unique_ptr<BitcodeContainer>(bitcodeContainer);
}
/// Reads bitcode from a plain object file.
///
/// @param objectFile The Mach O object file.
///
/// @return The bitcode container.
llvm::Expected<std::unique_ptr<BitcodeContainer>> GetBitcodeContainerFromObject(
const llvm::object::ObjectFile *objectFile) const {
const auto arch = llvm::Triple::getArchTypeName(static_cast<Triple::ArchType>(objectFile->getArch()));
if (!processArch(arch)) {
return nullptr;
}
BitcodeContainer *bitcodeContainer = nullptr;
std::vector<std::string> commands;
for (const SectionRef §ion : objectFile->sections()) {
StringRef sectName;
section.getName(sectName);
if (sectName == ".llvmbc") {
auto data = GetSectionData(section);
bitcodeContainer = new BitcodeContainer(data.first, data.second);
} else if (sectName == ".llvmcmd") {
commands = GetCommands(section);
}
}
if (bitcodeContainer == nullptr) {
return llvm::make_error<InternalEbcError>("No bitcode section in " + objectFile->getFileName().str());
}
// Set commands
bitcodeContainer->SetCommands(commands);
// Set binary metadata
bitcodeContainer->GetBinaryMetadata().SetFileName(GetFileName(objectFile->getFileName()));
bitcodeContainer->GetBinaryMetadata().SetFileFormatName(objectFile->getFileFormatName());
bitcodeContainer->GetBinaryMetadata().SetArch(arch);
return std::unique_ptr<BitcodeContainer>(bitcodeContainer);
}
/// Obtains data from a section.
///
/// @param section The section from which the data should be obtained.
///
/// @return A pair with the data and the size of the data.
static std::pair<const char *, std::uint32_t> GetSectionData(const llvm::object::SectionRef §ion) {
StringRef bytesStr;
section.getContents(bytesStr);
const char *sect = reinterpret_cast<const char *>(bytesStr.data());
uint32_t sect_size = bytesStr.size();
return std::make_pair(sect, sect_size);
}
/// Obtains compiler commands from a section. It automatically parses the
/// data into a vector.
///
/// @param section The sectio from which to read the compiler commands.
///
/// @return A vector of compiler commands.
static std::vector<std::string> GetCommands(const llvm::object::SectionRef §ion) {
auto data = GetSectionData(section);
const char *p = data.first;
const char *end = data.first + data.second;
// Create list of strings from commands separated by null bytes.
std::vector<std::string> cmds;
do {
// Creating a string from p consumes data until next null byte.
cmds.push_back(std::string(p));
// Continue after the null byte.
p += cmds.back().size() + 1;
} while (p < end);
return cmds;
}
std::string _objectPath;
std::string _arch;
};
BitcodeRetriever::BitcodeRetriever(std::string objectPath) : _impl(std::make_unique<Impl>(std::move(objectPath))) {}
BitcodeRetriever::~BitcodeRetriever() = default;
void BitcodeRetriever::SetArch(std::string arch) {
_impl->SetArch(std::move(arch));
}
std::vector<std::unique_ptr<BitcodeContainer>> BitcodeRetriever::GetBitcodeContainers() {
return _impl->GetBitcodeContainers();
}
} // namespace ebc
<|endoftext|>
|
<commit_before>/**
* @file
*/
#pragma once
#include "libbirch/Any.hpp"
#include "libbirch/Atomic.hpp"
#include "libbirch/type.hpp"
#include "libbirch/memory.hpp"
namespace libbirch {
/**
* Shared object.
*
* @ingroup libbirch
*
* @tparam T Type, must derive from Any.
*
* Supports reference counted garbage collection. Cycles are collected by
* periodically calling collect(); currently this must be done manually at
* opportune times.
*
* @attention While Shared maintains a pointer to a referent object, it likes
* to pretend it's not a pointer. This behavior differs from
* [`std::shared_ptr`](https://en.cppreference.com/w/cpp/memory/shared_ptr).
* In particular, its default constructor does not initialize the pointer to
* `nullptr`, but rather default-constructs an object of type `T` and sets the
* pointer to that. Consider using a [`std::optional`](https://en.cppreference.com/w/cpp/utility/optional/optional)
* with a Shared value instead of `nullptr`.
*/
template<class T>
class Shared {
template<class U> friend class Shared;
friend class Marker;
friend class Scanner;
friend class Reacher;
friend class Collector;
friend class Spanner;
friend class Bridger;
friend class Copier;
friend class BiconnectedCopier;
public:
using value_type = T;
/**
* Default constructor. Constructs a new referent using the default
* constructor.
*/
Shared() :
Shared(new T(), false) {
//
}
/**
* Constructor. Constructs a new referent with the given arguments. The
* first is a placeholder (pass [`std::in_place`](https://en.cppreference.com/w/cpp/utility/in_place))
* to distinguish this constructor from copy and move constructors.
*
* @note [`std::optional`](https://en.cppreference.com/w/cpp/utility/optional/)
* behaves similarly with regard to [`std::in_place`](https://en.cppreference.com/w/cpp/utility/in_place).
*/
template<class... Args>
Shared(std::in_place_t, Args&&... args) :
Shared(new T(std::forward<Args>(args)...), false) {
//
}
/**
* Constructor.
*
* @param ptr Raw pointer.
* @param b Is this a bridge?
*/
Shared(T* ptr, const bool b = false) :
ptr(ptr),
b(b) {
if (ptr) {
ptr->incShared();
}
}
/**
* Copy constructor.
*/
Shared(const Shared& o) : ptr(nullptr), b(false) {
if (o.b) {
if (biconnected_copy()) {
replace(o.load());
b = true;
} else {
replace(o.get());
b = false;
}
} else {
replace(o.load());
}
}
/**
* Generic copy constructor.
*/
template<class U, std::enable_if_t<std::is_base_of<T,U>::value,int> = 0>
Shared(const Shared<U>& o) :
Shared(o.get(), false) {
//
}
/**
* Move constructor.
*/
Shared(Shared&& o) :
ptr(o.ptr.exchange(nullptr)), b(o.b) {
o.b = false;
}
/**
* Generic move constructor.
*/
template<class U, std::enable_if_t<std::is_base_of<T,U>::value,int> = 0>
Shared(Shared<U>&& o) :
ptr(o.ptr.exchange(nullptr)), b(o.b) {
o.b = false;
}
/**
* Destructor.
*/
~Shared() {
release();
}
/**
* Copy assignment.
*/
Shared& operator=(const Shared& o) {
replace(o.get());
b = false;
return *this;
}
/**
* Generic copy assignment.
*/
template<class U, std::enable_if_t<std::is_base_of<T,U>::value,int> = 0>
Shared& operator=(const Shared<U>& o) {
replace(o.get());
b = false;
return *this;
}
/**
* Move assignment.
*/
Shared& operator=(Shared&& o) {
auto ptr = o.ptr.exchange(nullptr);
auto old = this->ptr.exchange(ptr);
if (old) {
if (ptr == old) {
old->decSharedReachable();
} else {
old->decShared();
}
}
std::swap(b, o.b);
return *this;
}
/**
* Generic move assignment.
*/
template<class U, std::enable_if_t<std::is_base_of<T,U>::value,int> = 0>
Shared& operator=(Shared<U>&& o) {
auto ptr = o.ptr.exchange(nullptr);
auto old = this->ptr.exchange(ptr);
if (old) {
if (ptr == old) {
old->decSharedReachable();
} else {
old->decShared();
}
}
std::swap(b, o.b);
return *this;
}
/**
* Value assignment.
*/
template<class U, std::enable_if_t<is_value<U>::value,int> = 0>
Shared<T>& operator=(const U& o) {
*get() = o;
return *this;
}
/**
* Value assignment.
*/
template<class U, std::enable_if_t<is_value<U>::value,int> = 0>
const Shared<T>& operator=(const U& o) const {
*get() = o;
return *this;
}
/**
* Is the pointer not null?
*
* This is used instead of an `operator bool()` so as not to conflict with
* conversion operators in the referent type.
*/
bool query() const {
return load() != nullptr;
}
/**
* Get the raw pointer.
*/
T* get();
/**
* Get the raw pointer.
*/
T* get() const {
return const_cast<Shared<T>*>(this)->get();
}
/**
* Get the raw pointer as const.
*/
const T* read() const {
return get();
}
/**
* Deep copy. Finds bridges in the reachable graph then immediately copies
* the subgraph up to the nearest reachable bridges, the remainder deferred
* until needed.
*/
Shared<T> copy();
/**
* Deep copy.
*/
Shared<T> copy() const {
return const_cast<Shared<T>*>(this)->copy();
}
/**
* Deep copy. Copies the subgraph up to the nearest reachable bridges, the
* remainder deferred until needed. Unlike #copy(), does not attempt to find
* new bridges, but does use existing bridges. This is suitable if eager
* copying, rather than lazy copying, is preferred, or for the second and
* subsequent copies when replicating a graph multiple times, when the
* bridge finding has already been completed by the first copy (using
* #copy()).
*/
Shared<T> copy2();
/**
* Deep copy.
*/
Shared<T> copy2() const {
return const_cast<Shared<T>*>(this)->copy2();
}
/**
* Replace. Sets the raw pointer to a new value and returns the previous
* value.
*/
T* replace(T* ptr) {
if (ptr) {
ptr->incShared();
}
auto old = this->ptr.exchange(ptr);
if (old) {
if (ptr == old) {
old->decSharedReachable();
} else {
old->decShared();
}
}
b = false;
return old;
}
/**
* Release. Sets the raw pointer to null and returns the previous value.
*/
T* release() {
auto old = ptr.exchange(nullptr);
if (old) {
old->decShared();
}
b = false;
return old;
}
/**
* Dereference.
*/
T& operator*() const {
return *get();
}
/**
* Member access.
*/
T* operator->() const {
return get();
}
/**
* Call on referent.
*/
template<class... Args>
auto& operator()(Args&&... args) {
return (*get())(std::forward<Args>(args)...);
}
private:
/**
* Load the raw pointer as-is. Does not trigger copy-on-write.
*/
T* load() const {
return ptr.load();
}
/**
* Store the raw pointer as-is. Does not update reference counts.
*/
void store(T* o) {
ptr.store(o);
}
/**
* Raw pointer.
*/
Atomic<T*> ptr;
/**
* Is this a bridge?
*/
bool b;
};
template<class T>
struct is_value<Shared<T>> {
static const bool value = false;
};
template<class T>
struct is_pointer<Shared<T>> {
static const bool value = true;
};
}
#include "libbirch/Spanner.hpp"
#include "libbirch/Bridger.hpp"
#include "libbirch/Copier.hpp"
#include "libbirch/BiconnectedCopier.hpp"
template<class T>
T* libbirch::Shared<T>::get() {
T* v = load();
if (b) {
b = false;
if (v->numShared() > 1) { // no need to copy for last reference
/* the copy is of a biconnected component here, used the optimized
* BiconnectedCopier for this */
v = static_cast<T*>(BiconnectedCopier(v).visit(static_cast<Any*>(v)));
replace(v);
}
}
return v;
}
template<class T>
libbirch::Shared<T> libbirch::Shared<T>::copy() {
/* find bridges */
Spanner().visit(0, 1, *this);
Bridger().visit(1, 0, *this);
/* copy */
return copy2();
}
template<class T>
libbirch::Shared<T> libbirch::Shared<T>::copy2() {
Any* u = load();
if (b) {
return Shared<T>(static_cast<T*>(u), true);
} else {
/* the copy is *not* of a biconnected component here, use the
* general-purpose Copier for this */
return Shared<T>(static_cast<T*>(Copier().visit(u)), false);
}
}
<commit_msg>Removed use of atomic to store raw pointer value in Shared.<commit_after>/**
* @file
*/
#pragma once
#include "libbirch/Any.hpp"
#include "libbirch/Atomic.hpp"
#include "libbirch/type.hpp"
#include "libbirch/memory.hpp"
namespace libbirch {
/**
* Shared object.
*
* @ingroup libbirch
*
* @tparam T Type, must derive from Any.
*
* Supports reference counted garbage collection. Cycles are collected by
* periodically calling collect(); currently this must be done manually at
* opportune times.
*
* @attention While Shared maintains a pointer to a referent object, it likes
* to pretend it's not a pointer. This behavior differs from
* [`std::shared_ptr`](https://en.cppreference.com/w/cpp/memory/shared_ptr).
* In particular, its default constructor does not initialize the pointer to
* `nullptr`, but rather default-constructs an object of type `T` and sets the
* pointer to that. Consider using a [`std::optional`](https://en.cppreference.com/w/cpp/utility/optional/optional)
* with a Shared value instead of `nullptr`.
*/
template<class T>
class Shared {
template<class U> friend class Shared;
friend class Marker;
friend class Scanner;
friend class Reacher;
friend class Collector;
friend class Spanner;
friend class Bridger;
friend class Copier;
friend class BiconnectedCopier;
public:
using value_type = T;
/**
* Default constructor. Constructs a new referent using the default
* constructor.
*/
Shared() :
Shared(new T(), false) {
//
}
/**
* Constructor. Constructs a new referent with the given arguments. The
* first is a placeholder (pass [`std::in_place`](https://en.cppreference.com/w/cpp/utility/in_place))
* to distinguish this constructor from copy and move constructors.
*
* @note [`std::optional`](https://en.cppreference.com/w/cpp/utility/optional/)
* behaves similarly with regard to [`std::in_place`](https://en.cppreference.com/w/cpp/utility/in_place).
*/
template<class... Args>
Shared(std::in_place_t, Args&&... args) :
Shared(new T(std::forward<Args>(args)...), false) {
//
}
/**
* Constructor.
*
* @param ptr Raw pointer.
* @param b Is this a bridge?
*/
Shared(T* ptr, const bool b = false) :
ptr(ptr),
b(b) {
if (ptr) {
ptr->incShared();
}
}
/**
* Copy constructor.
*/
Shared(const Shared& o) : ptr(nullptr), b(false) {
if (o.b) {
if (biconnected_copy()) {
replace(o.load());
b = true;
} else {
replace(o.get());
b = false;
}
} else {
replace(o.load());
}
}
/**
* Generic copy constructor.
*/
template<class U, std::enable_if_t<std::is_base_of<T,U>::value,int> = 0>
Shared(const Shared<U>& o) :
Shared(o.get(), false) {
//
}
/**
* Move constructor.
*/
Shared(Shared&& o) :
ptr(o.ptr), b(o.b) {
o.ptr = nullptr;
o.b = false;
}
/**
* Generic move constructor.
*/
template<class U, std::enable_if_t<std::is_base_of<T,U>::value,int> = 0>
Shared(Shared<U>&& o) :
ptr(o.ptr), b(o.b) {
o.ptr = nullptr;
o.b = false;
}
/**
* Destructor.
*/
~Shared() {
release();
}
/**
* Copy assignment.
*/
Shared& operator=(const Shared& o) {
replace(o.get());
b = false;
return *this;
}
/**
* Generic copy assignment.
*/
template<class U, std::enable_if_t<std::is_base_of<T,U>::value,int> = 0>
Shared& operator=(const Shared<U>& o) {
replace(o.get());
b = false;
return *this;
}
/**
* Move assignment.
*/
Shared& operator=(Shared&& o) {
auto old = ptr;
ptr = o.ptr;
b = o.b;
o.ptr = nullptr;
o.b = false;
if (old) {
if (ptr == old) {
old->decSharedReachable();
} else {
old->decShared();
}
}
return *this;
}
/**
* Generic move assignment.
*/
template<class U, std::enable_if_t<std::is_base_of<T,U>::value,int> = 0>
Shared& operator=(Shared<U>&& o) {
auto old = ptr;
ptr = o.ptr;
b = o.b;
o.ptr = nullptr;
o.b = false;
if (old) {
if (ptr == old) {
old->decSharedReachable();
} else {
old->decShared();
}
}
return *this;
}
/**
* Value assignment.
*/
template<class U, std::enable_if_t<is_value<U>::value,int> = 0>
Shared<T>& operator=(const U& o) {
*get() = o;
return *this;
}
/**
* Value assignment.
*/
template<class U, std::enable_if_t<is_value<U>::value,int> = 0>
const Shared<T>& operator=(const U& o) const {
*get() = o;
return *this;
}
/**
* Is the pointer not null?
*
* This is used instead of an `operator bool()` so as not to conflict with
* conversion operators in the referent type.
*/
bool query() const {
return load() != nullptr;
}
/**
* Get the raw pointer.
*/
T* get();
/**
* Get the raw pointer.
*/
T* get() const {
return const_cast<Shared<T>*>(this)->get();
}
/**
* Get the raw pointer as const.
*/
const T* read() const {
return get();
}
/**
* Deep copy. Finds bridges in the reachable graph then immediately copies
* the subgraph up to the nearest reachable bridges, the remainder deferred
* until needed.
*/
Shared<T> copy();
/**
* Deep copy.
*/
Shared<T> copy() const {
return const_cast<Shared<T>*>(this)->copy();
}
/**
* Deep copy. Copies the subgraph up to the nearest reachable bridges, the
* remainder deferred until needed. Unlike #copy(), does not attempt to find
* new bridges, but does use existing bridges. This is suitable if eager
* copying, rather than lazy copying, is preferred, or for the second and
* subsequent copies when replicating a graph multiple times, when the
* bridge finding has already been completed by the first copy (using
* #copy()).
*/
Shared<T> copy2();
/**
* Deep copy.
*/
Shared<T> copy2() const {
return const_cast<Shared<T>*>(this)->copy2();
}
/**
* Replace. Sets the raw pointer to a new value and returns the previous
* value.
*/
T* replace(T* ptr) {
if (ptr) {
ptr->incShared();
}
auto old = this->ptr;
this->ptr = ptr;
this->b = false;
if (old) {
if (ptr == old) {
old->decSharedReachable();
} else {
old->decShared();
}
}
return old;
}
/**
* Release. Sets the raw pointer to null and returns the previous value.
*/
T* release() {
auto old = ptr;
ptr = nullptr;
b = false;
if (old) {
old->decShared();
}
return old;
}
/**
* Dereference.
*/
T& operator*() const {
return *get();
}
/**
* Member access.
*/
T* operator->() const {
return get();
}
/**
* Call on referent.
*/
template<class... Args>
auto& operator()(Args&&... args) {
return (*get())(std::forward<Args>(args)...);
}
private:
/**
* Load the raw pointer as-is. Does not trigger copy-on-write.
*/
T* load() const {
return ptr;
}
/**
* Store the raw pointer as-is. Does not update reference counts.
*/
void store(T* o) {
ptr = o;
}
/**
* Raw pointer.
*/
T* ptr;
/**
* Is this a bridge?
*/
bool b;
};
template<class T>
struct is_value<Shared<T>> {
static const bool value = false;
};
template<class T>
struct is_pointer<Shared<T>> {
static const bool value = true;
};
}
#include "libbirch/Spanner.hpp"
#include "libbirch/Bridger.hpp"
#include "libbirch/Copier.hpp"
#include "libbirch/BiconnectedCopier.hpp"
template<class T>
T* libbirch::Shared<T>::get() {
T* v = load();
if (b) {
b = false;
if (v->numShared() > 1) { // no need to copy for last reference
/* the copy is of a biconnected component here, used the optimized
* BiconnectedCopier for this */
v = static_cast<T*>(BiconnectedCopier(v).visit(static_cast<Any*>(v)));
replace(v);
}
}
return v;
}
template<class T>
libbirch::Shared<T> libbirch::Shared<T>::copy() {
/* find bridges */
Spanner().visit(0, 1, *this);
Bridger().visit(1, 0, *this);
/* copy */
return copy2();
}
template<class T>
libbirch::Shared<T> libbirch::Shared<T>::copy2() {
Any* u = load();
if (b) {
return Shared<T>(static_cast<T*>(u), true);
} else {
/* the copy is *not* of a biconnected component here, use the
* general-purpose Copier for this */
return Shared<T>(static_cast<T*>(Copier().visit(u)), false);
}
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/login/user_image_view.h"
#include <algorithm>
#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "base/callback.h"
#include "chrome/browser/chromeos/login/rounded_rect_painter.h"
#include "gfx/canvas.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "skia/ext/image_operations.h"
#include "views/controls/button/image_button.h"
#include "views/controls/button/native_button.h"
#include "views/controls/image_view.h"
#include "views/controls/label.h"
namespace {
// Margin in pixels from the left and right borders of screen's contents.
const int kHorizontalMargin = 10;
// Margin in pixels from the top and bottom borders of screen's contents.
const int kVerticalMargin = 10;
// Padding between horizontally neighboring elements.
const int kHorizontalPadding = 10;
// Padding between vertically neighboring elements.
const int kVerticalPadding = 10;
// Size of each image in images list.
const int kImageSize = 160;
// Size of selected image preview.
const int kSelectedImageSize = 260;
} // namespace
namespace chromeos {
UserImageView::UserImageView(Delegate* delegate)
: title_label_(NULL),
ok_button_(NULL),
cancel_button_(NULL),
video_button_(NULL),
selected_image_(NULL),
delegate_(delegate),
image_selected_(false) {
}
UserImageView::~UserImageView() {
}
void UserImageView::Init() {
// Use rounded rect background.
set_border(CreateWizardBorder(&BorderDefinition::kScreenBorder));
views::Painter* painter = CreateWizardPainter(
&BorderDefinition::kScreenBorder);
set_background(views::Background::CreateBackgroundPainter(true, painter));
// Set up fonts.
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
gfx::Font title_font = rb.GetFont(ResourceBundle::MediumBoldFont);
title_label_ = new views::Label();
title_label_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
title_label_->SetFont(title_font);
title_label_->SetMultiLine(true);
AddChildView(title_label_);
SkBitmap video_button_image(
skia::ImageOperations::Resize(
*ResourceBundle::GetSharedInstance().GetBitmapNamed(
IDR_USER_IMAGE_NO_VIDEO),
skia::ImageOperations::RESIZE_LANCZOS3,
kImageSize,
kImageSize));
video_button_ = new views::ImageButton(this);
video_button_->SetImage(views::CustomButton::BS_NORMAL, &video_button_image);
AddChildView(video_button_);
selected_image_ = new views::ImageView();
selected_image_->SetImageSize(
gfx::Size(kSelectedImageSize, kSelectedImageSize));
selected_image_->SetImage(
*ResourceBundle::GetSharedInstance().GetBitmapNamed(
IDR_LOGIN_OTHER_USER));
AddChildView(selected_image_);
UpdateLocalizedStrings();
}
void UserImageView::RecreateNativeControls() {
// There is no way to get native button preferred size after the button was
// sized so delete and recreate the button on text update.
delete ok_button_;
ok_button_ = new views::NativeButton(this, std::wstring());
AddChildView(ok_button_);
ok_button_->SetEnabled(image_selected_);
delete cancel_button_;
cancel_button_ = new views::NativeButton(this, std::wstring());
AddChildView(cancel_button_);
cancel_button_->SetEnabled(true);
}
void UserImageView::UpdateLocalizedStrings() {
RecreateNativeControls();
title_label_->SetText(l10n_util::GetString(IDS_USER_IMAGE_SCREEN_TITLE));
ok_button_->SetLabel(l10n_util::GetString(IDS_OK));
cancel_button_->SetLabel(l10n_util::GetString(IDS_CANCEL));
selected_image_->SetTooltipText(
l10n_util::GetString(IDS_USER_IMAGE_SELECTED_TOOLTIP));
}
void UserImageView::UpdateVideoFrame(const SkBitmap& frame) {
last_frame_.reset(new SkBitmap(frame));
SkBitmap video_button_image(
skia::ImageOperations::Resize(
frame,
skia::ImageOperations::RESIZE_LANCZOS3,
kImageSize,
kImageSize));
video_button_->SetImage(views::CustomButton::BS_NORMAL, &video_button_image);
video_button_->SchedulePaint();
}
void UserImageView::OnVideoImageClicked() {
// TODO(avayvod): Snapshot sound.
if (!last_frame_.get())
return;
selected_image_->SetImage(*last_frame_);
image_selected_ = true;
ok_button_->SetEnabled(true);
}
void UserImageView::LocaleChanged() {
UpdateLocalizedStrings();
Layout();
}
void UserImageView::Layout() {
gfx::Insets insets = GetInsets();
// Place title at the top.
int title_x = insets.left() + kHorizontalMargin;
int title_y = insets.top() + kVerticalMargin;
int max_width = width() - insets.width() - kHorizontalMargin * 2;
title_label_->SizeToFit(max_width);
gfx::Size title_size = title_label_->GetPreferredSize();
title_label_->SetBounds(title_x,
title_y,
std::min(max_width, title_size.width()),
title_size.height());
// Put OK button at the right bottom corner.
gfx::Size ok_size = ok_button_->GetPreferredSize();
int ok_x = width() - insets.right() - kHorizontalMargin - ok_size.width();
int ok_y = height() - insets.bottom() - kVerticalMargin - ok_size.height();
ok_button_->SetBounds(ok_x, ok_y, ok_size.width(), ok_size.height());
// Put Cancel button to the left from OK.
gfx::Size cancel_size = cancel_button_->GetPreferredSize();
int cancel_x = ok_x - kHorizontalPadding - cancel_size.width();
int cancel_y = ok_y; // Height should be the same for both buttons.
cancel_button_->SetBounds(cancel_x,
cancel_y,
cancel_size.width(),
cancel_size.height());
// The area between buttons and title is for images.
int title_bottom = title_label_->y() + title_label_->height();
gfx::Rect images_area(insets.left() + kHorizontalMargin,
title_bottom + kVerticalPadding,
max_width,
ok_button_->y() - title_bottom -
2 * kVerticalPadding);
// Video capture image is in the top left corner of the area.
int video_button_x = images_area.x();
int video_button_y = images_area.y();
gfx::Size video_button_size = video_button_->GetPreferredSize();
video_button_->SetBounds(video_button_x,
video_button_y,
video_button_size.width(),
video_button_size.height());
// Selected image is floating in the middle between top and height, near
// the right border.
gfx::Size selected_image_size = selected_image_->GetPreferredSize();
int selected_image_x = images_area.right() - selected_image_size.width();
int selected_image_y = images_area.y() +
(images_area.height() - selected_image_size.height()) / 2;
selected_image_->SetBounds(selected_image_x,
selected_image_y,
selected_image_size.width(),
selected_image_size.height());
SchedulePaint();
}
gfx::Size UserImageView::GetPreferredSize() {
return gfx::Size(width(), height());
}
void UserImageView::ButtonPressed(
views::Button* sender, const views::Event& event) {
DCHECK(delegate_);
if (sender == video_button_) {
OnVideoImageClicked();
return;
}
if (sender == ok_button_)
delegate_->OnOK(*last_frame_);
else if (sender == cancel_button_)
delegate_->OnCancel();
else
NOTREACHED();
}
} // namespace chromeos
<commit_msg>Set selected user image instead of the last captured by camera.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/login/user_image_view.h"
#include <algorithm>
#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "base/callback.h"
#include "chrome/browser/chromeos/login/rounded_rect_painter.h"
#include "gfx/canvas.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "skia/ext/image_operations.h"
#include "views/controls/button/image_button.h"
#include "views/controls/button/native_button.h"
#include "views/controls/image_view.h"
#include "views/controls/label.h"
namespace {
// Margin in pixels from the left and right borders of screen's contents.
const int kHorizontalMargin = 10;
// Margin in pixels from the top and bottom borders of screen's contents.
const int kVerticalMargin = 10;
// Padding between horizontally neighboring elements.
const int kHorizontalPadding = 10;
// Padding between vertically neighboring elements.
const int kVerticalPadding = 10;
// Size of each image in images list.
const int kImageSize = 160;
// Size of selected image preview.
const int kSelectedImageSize = 260;
} // namespace
namespace chromeos {
UserImageView::UserImageView(Delegate* delegate)
: title_label_(NULL),
ok_button_(NULL),
cancel_button_(NULL),
video_button_(NULL),
selected_image_(NULL),
delegate_(delegate),
image_selected_(false) {
}
UserImageView::~UserImageView() {
}
void UserImageView::Init() {
// Use rounded rect background.
set_border(CreateWizardBorder(&BorderDefinition::kScreenBorder));
views::Painter* painter = CreateWizardPainter(
&BorderDefinition::kScreenBorder);
set_background(views::Background::CreateBackgroundPainter(true, painter));
// Set up fonts.
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
gfx::Font title_font = rb.GetFont(ResourceBundle::MediumBoldFont);
title_label_ = new views::Label();
title_label_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
title_label_->SetFont(title_font);
title_label_->SetMultiLine(true);
AddChildView(title_label_);
SkBitmap video_button_image(
skia::ImageOperations::Resize(
*ResourceBundle::GetSharedInstance().GetBitmapNamed(
IDR_USER_IMAGE_NO_VIDEO),
skia::ImageOperations::RESIZE_LANCZOS3,
kImageSize,
kImageSize));
video_button_ = new views::ImageButton(this);
video_button_->SetImage(views::CustomButton::BS_NORMAL, &video_button_image);
AddChildView(video_button_);
selected_image_ = new views::ImageView();
selected_image_->SetImageSize(
gfx::Size(kSelectedImageSize, kSelectedImageSize));
selected_image_->SetImage(
*ResourceBundle::GetSharedInstance().GetBitmapNamed(
IDR_LOGIN_OTHER_USER));
AddChildView(selected_image_);
UpdateLocalizedStrings();
}
void UserImageView::RecreateNativeControls() {
// There is no way to get native button preferred size after the button was
// sized so delete and recreate the button on text update.
delete ok_button_;
ok_button_ = new views::NativeButton(this, std::wstring());
AddChildView(ok_button_);
ok_button_->SetEnabled(image_selected_);
delete cancel_button_;
cancel_button_ = new views::NativeButton(this, std::wstring());
AddChildView(cancel_button_);
cancel_button_->SetEnabled(true);
}
void UserImageView::UpdateLocalizedStrings() {
RecreateNativeControls();
title_label_->SetText(l10n_util::GetString(IDS_USER_IMAGE_SCREEN_TITLE));
ok_button_->SetLabel(l10n_util::GetString(IDS_OK));
cancel_button_->SetLabel(l10n_util::GetString(IDS_CANCEL));
selected_image_->SetTooltipText(
l10n_util::GetString(IDS_USER_IMAGE_SELECTED_TOOLTIP));
}
void UserImageView::UpdateVideoFrame(const SkBitmap& frame) {
last_frame_.reset(new SkBitmap(frame));
SkBitmap video_button_image(
skia::ImageOperations::Resize(
frame,
skia::ImageOperations::RESIZE_LANCZOS3,
kImageSize,
kImageSize));
video_button_->SetImage(views::CustomButton::BS_NORMAL, &video_button_image);
video_button_->SchedulePaint();
}
void UserImageView::OnVideoImageClicked() {
// TODO(avayvod): Snapshot sound.
if (!last_frame_.get())
return;
selected_image_->SetImage(*last_frame_);
image_selected_ = true;
ok_button_->SetEnabled(true);
}
void UserImageView::LocaleChanged() {
UpdateLocalizedStrings();
Layout();
}
void UserImageView::Layout() {
gfx::Insets insets = GetInsets();
// Place title at the top.
int title_x = insets.left() + kHorizontalMargin;
int title_y = insets.top() + kVerticalMargin;
int max_width = width() - insets.width() - kHorizontalMargin * 2;
title_label_->SizeToFit(max_width);
gfx::Size title_size = title_label_->GetPreferredSize();
title_label_->SetBounds(title_x,
title_y,
std::min(max_width, title_size.width()),
title_size.height());
// Put OK button at the right bottom corner.
gfx::Size ok_size = ok_button_->GetPreferredSize();
int ok_x = width() - insets.right() - kHorizontalMargin - ok_size.width();
int ok_y = height() - insets.bottom() - kVerticalMargin - ok_size.height();
ok_button_->SetBounds(ok_x, ok_y, ok_size.width(), ok_size.height());
// Put Cancel button to the left from OK.
gfx::Size cancel_size = cancel_button_->GetPreferredSize();
int cancel_x = ok_x - kHorizontalPadding - cancel_size.width();
int cancel_y = ok_y; // Height should be the same for both buttons.
cancel_button_->SetBounds(cancel_x,
cancel_y,
cancel_size.width(),
cancel_size.height());
// The area between buttons and title is for images.
int title_bottom = title_label_->y() + title_label_->height();
gfx::Rect images_area(insets.left() + kHorizontalMargin,
title_bottom + kVerticalPadding,
max_width,
ok_button_->y() - title_bottom -
2 * kVerticalPadding);
// Video capture image is in the top left corner of the area.
int video_button_x = images_area.x();
int video_button_y = images_area.y();
gfx::Size video_button_size = video_button_->GetPreferredSize();
video_button_->SetBounds(video_button_x,
video_button_y,
video_button_size.width(),
video_button_size.height());
// Selected image is floating in the middle between top and height, near
// the right border.
gfx::Size selected_image_size = selected_image_->GetPreferredSize();
int selected_image_x = images_area.right() - selected_image_size.width();
int selected_image_y = images_area.y() +
(images_area.height() - selected_image_size.height()) / 2;
selected_image_->SetBounds(selected_image_x,
selected_image_y,
selected_image_size.width(),
selected_image_size.height());
SchedulePaint();
}
gfx::Size UserImageView::GetPreferredSize() {
return gfx::Size(width(), height());
}
void UserImageView::ButtonPressed(
views::Button* sender, const views::Event& event) {
DCHECK(delegate_);
if (sender == video_button_) {
OnVideoImageClicked();
return;
}
if (sender == ok_button_)
delegate_->OnOK(selected_image_->GetImage());
else if (sender == cancel_button_)
delegate_->OnCancel();
else
NOTREACHED();
}
} // namespace chromeos
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.