text
stringlengths 54
60.6k
|
---|
<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 "views/widget/native_widget_view.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/compositor/layer.h"
namespace views {
namespace internal {
////////////////////////////////////////////////////////////////////////////////
// NativeWidgetView, public:
// static
const char NativeWidgetView::kViewClassName[] = "views/NativeWidgetView";
NativeWidgetView::NativeWidgetView(NativeWidgetViews* native_widget)
: native_widget_(native_widget),
sent_create_(false),
delete_native_widget_(true),
cursor_(NULL) {
}
NativeWidgetView::~NativeWidgetView() {
// Don't let NativeWidgetViews delete this again. This must be outside
// the |delete_native_widget_| clause so it gets invoked for
// WIDGET_OWNS_NATIVE_WIDGET. It is safe because |native_widget_| will
// still exist in both ways NativeWidgetView can be destroyed: by view
// hierarchy teardown and from the NativeWidgetViews destructor.
native_widget_->set_delete_native_view(false);
if (delete_native_widget_)
delete native_widget_;
}
Widget* NativeWidgetView::GetAssociatedWidget() {
return native_widget_->delegate()->AsWidget();
}
////////////////////////////////////////////////////////////////////////////////
// NativeWidgetView, View overrides:
void NativeWidgetView::CalculateOffsetToAncestorWithLayer(
gfx::Point* offset,
ui::Layer** layer_parent) {
View::CalculateOffsetToAncestorWithLayer(offset, layer_parent);
}
#if !defined(NDEBUG)
std::string NativeWidgetView::PrintViewGraph(bool first) {
return DoPrintViewGraph(first, GetAssociatedWidget()->GetRootView());
}
#endif
void NativeWidgetView::ViewHierarchyChanged(bool is_add,
View* parent,
View* child) {
if (is_add && child == this) {
GetAssociatedWidget()->GetRootView()->UpdateParentLayers();
if (!sent_create_) {
sent_create_ = true;
delegate()->OnNativeWidgetCreated();
}
}
}
void NativeWidgetView::OnBoundsChanged(const gfx::Rect& previous_bounds) {
native_widget_->OnBoundsChanged(bounds(), previous_bounds);
}
void NativeWidgetView::OnPaint(gfx::Canvas* canvas) {
delegate()->OnNativeWidgetPaint(canvas);
}
gfx::NativeCursor NativeWidgetView::GetCursor(const MouseEvent& event) {
return cursor_;
}
bool NativeWidgetView::OnMousePressed(const MouseEvent& event) {
return native_widget_->OnMouseEvent(event);
}
bool NativeWidgetView::OnMouseDragged(const MouseEvent& event) {
return native_widget_->OnMouseEvent(event);
}
void NativeWidgetView::OnMouseReleased(const MouseEvent& event) {
native_widget_->OnMouseEvent(event);
}
void NativeWidgetView::OnMouseCaptureLost() {
delegate()->OnMouseCaptureLost();
}
void NativeWidgetView::OnMouseMoved(const MouseEvent& event) {
native_widget_->OnMouseEvent(event);
}
void NativeWidgetView::OnMouseEntered(const MouseEvent& event) {
native_widget_->OnMouseEvent(event);
}
void NativeWidgetView::OnMouseExited(const MouseEvent& event) {
native_widget_->OnMouseEvent(event);
}
ui::TouchStatus NativeWidgetView::OnTouchEvent(const TouchEvent& event) {
return delegate()->OnTouchEvent(event);
}
bool NativeWidgetView::OnKeyPressed(const KeyEvent& event) {
return delegate()->OnKeyEvent(event);
}
bool NativeWidgetView::OnKeyReleased(const KeyEvent& event) {
return delegate()->OnKeyEvent(event);
}
bool NativeWidgetView::OnMouseWheel(const MouseWheelEvent& event) {
return native_widget_->OnMouseEvent(event);
}
void NativeWidgetView::VisibilityChanged(View* starting_from,
bool visible) {
delegate()->OnNativeWidgetVisibilityChanged(visible);
}
void NativeWidgetView::OnFocus() {
// TODO(beng): check if we have to do this.
//delegate()->OnNativeFocus(NULL);
}
void NativeWidgetView::OnBlur() {
// TODO(beng): check if we have to do this.
//delegate()->OnNativeBlur(NULL);
}
std::string NativeWidgetView::GetClassName() const {
return kViewClassName;
}
void NativeWidgetView::MoveLayerToParent(ui::Layer* parent_layer,
const gfx::Point& point) {
View::MoveLayerToParent(parent_layer, point);
if (!layer() || parent_layer == layer()) {
gfx::Point new_offset(point);
if (layer() != parent_layer)
new_offset.Offset(x(), y());
GetAssociatedWidget()->GetRootView()->MoveLayerToParent(
parent_layer, new_offset);
}
}
void NativeWidgetView::UpdateChildLayerBounds(const gfx::Point& offset) {
gfx::Point new_offset(offset.x() + x(), offset.y() + y());
View::UpdateChildLayerBounds(new_offset);
if (!layer())
GetAssociatedWidget()->GetRootView()->UpdateChildLayerBounds(new_offset);
}
} // namespace internal
} // namespace views
<commit_msg>Don't reapply offset in NativeWidgetView::UpdateChildLayerBounds.<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 "views/widget/native_widget_view.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/compositor/layer.h"
namespace views {
namespace internal {
////////////////////////////////////////////////////////////////////////////////
// NativeWidgetView, public:
// static
const char NativeWidgetView::kViewClassName[] = "views/NativeWidgetView";
NativeWidgetView::NativeWidgetView(NativeWidgetViews* native_widget)
: native_widget_(native_widget),
sent_create_(false),
delete_native_widget_(true),
cursor_(NULL) {
}
NativeWidgetView::~NativeWidgetView() {
// Don't let NativeWidgetViews delete this again. This must be outside
// the |delete_native_widget_| clause so it gets invoked for
// WIDGET_OWNS_NATIVE_WIDGET. It is safe because |native_widget_| will
// still exist in both ways NativeWidgetView can be destroyed: by view
// hierarchy teardown and from the NativeWidgetViews destructor.
native_widget_->set_delete_native_view(false);
if (delete_native_widget_)
delete native_widget_;
}
Widget* NativeWidgetView::GetAssociatedWidget() {
return native_widget_->delegate()->AsWidget();
}
////////////////////////////////////////////////////////////////////////////////
// NativeWidgetView, View overrides:
void NativeWidgetView::CalculateOffsetToAncestorWithLayer(
gfx::Point* offset,
ui::Layer** layer_parent) {
View::CalculateOffsetToAncestorWithLayer(offset, layer_parent);
}
#if !defined(NDEBUG)
std::string NativeWidgetView::PrintViewGraph(bool first) {
return DoPrintViewGraph(first, GetAssociatedWidget()->GetRootView());
}
#endif
void NativeWidgetView::ViewHierarchyChanged(bool is_add,
View* parent,
View* child) {
if (is_add && child == this) {
GetAssociatedWidget()->GetRootView()->UpdateParentLayers();
if (!sent_create_) {
sent_create_ = true;
delegate()->OnNativeWidgetCreated();
}
}
}
void NativeWidgetView::OnBoundsChanged(const gfx::Rect& previous_bounds) {
native_widget_->OnBoundsChanged(bounds(), previous_bounds);
}
void NativeWidgetView::OnPaint(gfx::Canvas* canvas) {
delegate()->OnNativeWidgetPaint(canvas);
}
gfx::NativeCursor NativeWidgetView::GetCursor(const MouseEvent& event) {
return cursor_;
}
bool NativeWidgetView::OnMousePressed(const MouseEvent& event) {
return native_widget_->OnMouseEvent(event);
}
bool NativeWidgetView::OnMouseDragged(const MouseEvent& event) {
return native_widget_->OnMouseEvent(event);
}
void NativeWidgetView::OnMouseReleased(const MouseEvent& event) {
native_widget_->OnMouseEvent(event);
}
void NativeWidgetView::OnMouseCaptureLost() {
delegate()->OnMouseCaptureLost();
}
void NativeWidgetView::OnMouseMoved(const MouseEvent& event) {
native_widget_->OnMouseEvent(event);
}
void NativeWidgetView::OnMouseEntered(const MouseEvent& event) {
native_widget_->OnMouseEvent(event);
}
void NativeWidgetView::OnMouseExited(const MouseEvent& event) {
native_widget_->OnMouseEvent(event);
}
ui::TouchStatus NativeWidgetView::OnTouchEvent(const TouchEvent& event) {
return delegate()->OnTouchEvent(event);
}
bool NativeWidgetView::OnKeyPressed(const KeyEvent& event) {
return delegate()->OnKeyEvent(event);
}
bool NativeWidgetView::OnKeyReleased(const KeyEvent& event) {
return delegate()->OnKeyEvent(event);
}
bool NativeWidgetView::OnMouseWheel(const MouseWheelEvent& event) {
return native_widget_->OnMouseEvent(event);
}
void NativeWidgetView::VisibilityChanged(View* starting_from,
bool visible) {
delegate()->OnNativeWidgetVisibilityChanged(visible);
}
void NativeWidgetView::OnFocus() {
// TODO(beng): check if we have to do this.
//delegate()->OnNativeFocus(NULL);
}
void NativeWidgetView::OnBlur() {
// TODO(beng): check if we have to do this.
//delegate()->OnNativeBlur(NULL);
}
std::string NativeWidgetView::GetClassName() const {
return kViewClassName;
}
void NativeWidgetView::MoveLayerToParent(ui::Layer* parent_layer,
const gfx::Point& point) {
View::MoveLayerToParent(parent_layer, point);
if (!layer() || parent_layer == layer()) {
gfx::Point new_offset(point);
if (layer() != parent_layer)
new_offset.Offset(x(), y());
GetAssociatedWidget()->GetRootView()->MoveLayerToParent(
parent_layer, new_offset);
}
}
void NativeWidgetView::UpdateChildLayerBounds(const gfx::Point& offset) {
View::UpdateChildLayerBounds(offset);
if (!layer()) {
const gfx::Rect& bounds = GetAssociatedWidget()->GetRootView()->bounds();
gfx::Point new_offset(offset.x() + bounds.x(), offset.y() + bounds.y());
GetAssociatedWidget()->GetRootView()->UpdateChildLayerBounds(new_offset);
}
}
} // namespace internal
} // namespace views
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: jscriptclasses.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: jl $ $Date: 2001-12-06 08:12:40 $
*
* 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): _______________________________________
*
*
************************************************************************/
#include "jscriptclasses.hxx"
//========================================================================
// JScriptValue
//========================================================================
JScriptValue::JScriptValue(): m_bOutParam(0), m_bInOutParam(0)
{
}
JScriptValue::~JScriptValue()
{
}
// JScriptValue, IDispatch --------------------------------------------
STDMETHODIMP JScriptValue::GetTypeInfoCount(UINT *pctinfo)
{
return E_NOTIMPL;
}
// JScriptValue, IDispatch --------------------------------------------
STDMETHODIMP JScriptValue::GetTypeInfo( UINT iTInfo,
LCID lcid,
ITypeInfo **ppTInfo)
{
return E_NOTIMPL;
}
// JScriptValue, IDispatch --------------------------------------------
STDMETHODIMP JScriptValue::GetIDsOfNames( REFIID riid,
LPOLESTR *rgszNames,
UINT cNames,
LCID lcid,
DISPID *rgDispId)
{
if( !rgDispId)
return E_POINTER;
HRESULT ret= S_OK;
CComBSTR name(*rgszNames);
name.ToLower();
if( name == CComBSTR( L"set") )
*rgDispId= 1;
else if( name == CComBSTR( L"get") )
*rgDispId= 2;
else if( name == CComBSTR( L"initoutparam") )
*rgDispId= 3;
else if( name == CComBSTR( L"initinoutparam") )
*rgDispId= 4;
else
ret= DISP_E_UNKNOWNNAME;
return ret;
}
// JScriptValue, IDispatch --------------------------------------------
STDMETHODIMP JScriptValue::Invoke( DISPID dispIdMember,
REFIID riid,
LCID lcid,
WORD wFlags,
DISPPARAMS *pDispParams,
VARIANT *pVarResult,
EXCEPINFO *pExcepInfo,
UINT *puArgErr)
{
if( pDispParams->cNamedArgs)
return DISP_E_NONAMEDARGS;
HRESULT ret= S_OK;
switch( dispIdMember)
{
case 0: // DISPID_VALUE
if( wFlags & DISPATCH_PROPERTYGET && pVarResult)
{
if( FAILED( VariantCopy( pVarResult, &m_varValue)))
ret= E_FAIL;
}
else
ret= E_POINTER;
break;
case 1:
if( wFlags & DISPATCH_METHOD)
ret= Set( pDispParams->rgvarg[1], pDispParams->rgvarg[0]);
if( FAILED( ret))
ret= DISP_E_EXCEPTION;
break;
case 2:
if( wFlags & DISPATCH_METHOD)
ret= Get( pVarResult);
if( FAILED( ret))
ret= DISP_E_EXCEPTION;
break;
case 3:
if( wFlags & DISPATCH_METHOD)
ret= InitOutParam();
if( FAILED( ret))
ret= DISP_E_EXCEPTION;
break;
case 4:
if( wFlags & DISPATCH_METHOD)
ret= InitInOutParam( pDispParams->rgvarg[1], pDispParams->rgvarg[0]);
if( FAILED( ret))
ret= DISP_E_EXCEPTION;
break;
default:
ret= DISP_E_MEMBERNOTFOUND;
break;
}
return ret;
}
// JScriptValue, IScriptOutParam-----------------------
STDMETHODIMP JScriptValue::Set( VARIANT type, VARIANT value)
{
Lock();
HRESULT hr= S_OK;
m_varValue.Clear();
hr= VariantCopyInd( &m_varValue, &value);
VARIANT var;
VariantInit( &var);
if( SUCCEEDED( hr= VariantChangeType( &var, &type, 0, VT_BSTR)))
m_bstrType= var.bstrVal;
Unlock();
return hr;
}
// JScriptValue, IScriptOutParam-----------------------
STDMETHODIMP JScriptValue::Get( VARIANT *val)
{
Lock();
if( !val)
return E_POINTER;
HRESULT hr= VariantCopy( val, &m_varValue);
Unlock();
return hr;
}
STDMETHODIMP JScriptValue::InitOutParam()
{
Lock();
m_varValue.Clear();
m_bOutParam= true;
m_bInOutParam= false;
Unlock();
return S_OK;
}
STDMETHODIMP JScriptValue::InitInOutParam( VARIANT type, VARIANT value)
{
Lock();
m_bInOutParam= true;
m_bOutParam= false;
Unlock();
return Set( type, value);
}
STDMETHODIMP JScriptValue::IsOutParam( VARIANT_BOOL * flag)
{
Lock();
if( !flag)
return E_POINTER;
*flag= m_bOutParam ? VARIANT_TRUE : VARIANT_FALSE;
Unlock();
return S_OK;
}
STDMETHODIMP JScriptValue::IsInOutParam( VARIANT_BOOL * flag)
{
Lock();
if( !flag)
return E_POINTER;
*flag= m_bInOutParam ? VARIANT_TRUE : VARIANT_FALSE;
Unlock();
return S_OK;
}
STDMETHODIMP JScriptValue::GetValue( BSTR* type, VARIANT *value)
{
Lock();
if( !type || !value)
return E_POINTER;
HRESULT hr;
if( SUCCEEDED( hr= m_bstrType.CopyTo( type)))
hr= VariantCopy( value, &m_varValue);
Unlock();
return hr;
}
//##########################################################################################
// JScriptOutValue
//##########################################################################################
JScriptOutParam::JScriptOutParam()
{
}
JScriptOutParam::~JScriptOutParam()
{
}
// JScriptOutParam, IDispatch --------------------------------------------
STDMETHODIMP JScriptOutParam::GetTypeInfoCount(UINT *pctinfo)
{
return E_NOTIMPL;
}
// JScriptOutParam, IDispatch --------------------------------------------
STDMETHODIMP JScriptOutParam::GetTypeInfo( UINT iTInfo,
LCID lcid,
ITypeInfo **ppTInfo)
{
return E_NOTIMPL;
}
// JScriptOutParam, IDispatch --------------------------------------------
STDMETHODIMP JScriptOutParam::GetIDsOfNames( REFIID riid,
LPOLESTR *rgszNames,
UINT cNames,
LCID lcid,
DISPID *rgDispId)
{
if( !rgDispId)
return E_POINTER;
HRESULT ret= S_OK;
CComBSTR name(*rgszNames);
name.ToLower();
if( name == CComBSTR( L"0") )
*rgDispId= 1;
else
ret= DISP_E_UNKNOWNNAME;
return ret;
}
// JScriptOutParam, IDispatch --------------------------------------------
STDMETHODIMP JScriptOutParam::Invoke( DISPID dispIdMember,
REFIID riid,
LCID lcid,
WORD wFlags,
DISPPARAMS *pDispParams,
VARIANT *pVarResult,
EXCEPINFO *pExcepInfo,
UINT *puArgErr)
{
HRESULT ret= S_OK;
switch( dispIdMember)
{
case 0: // DISPID_VALUE
if( wFlags & DISPATCH_PROPERTYGET && pVarResult)
{
if( FAILED( VariantCopy( pVarResult, &m_varValue)))
ret= E_FAIL;
}
else if( wFlags & DISPATCH_PROPERTYPUT || wFlags & DISPATCH_PROPERTYPUTREF)
{
m_varValue.Clear();
if( FAILED( VariantCopyInd( &m_varValue, &pDispParams->rgvarg[0])))
ret= E_FAIL;
}
else
ret= E_POINTER;
break;
case 1: //
if( wFlags & DISPATCH_PROPERTYGET && pVarResult)
{
if( FAILED( VariantCopy( pVarResult, &m_varValue)))
ret= E_FAIL;
}
else if( wFlags & DISPATCH_PROPERTYPUT || wFlags & DISPATCH_PROPERTYPUTREF)
{
m_varValue.Clear();
if( FAILED( VariantCopyInd( &m_varValue, &pDispParams->rgvarg[0])))
ret= E_FAIL;
}
else
ret= E_POINTER;
break;
default:
ret= DISP_E_MEMBERNOTFOUND;
break;
}
return ret;
}
<commit_msg>INTEGRATION: CWS ooo19126 (1.3.578); FILE MERGED 2005/09/05 12:59:31 rt 1.3.578.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: jscriptclasses.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2005-09-08 19:42:46 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#include "jscriptclasses.hxx"
//========================================================================
// JScriptValue
//========================================================================
JScriptValue::JScriptValue(): m_bOutParam(0), m_bInOutParam(0)
{
}
JScriptValue::~JScriptValue()
{
}
// JScriptValue, IDispatch --------------------------------------------
STDMETHODIMP JScriptValue::GetTypeInfoCount(UINT *pctinfo)
{
return E_NOTIMPL;
}
// JScriptValue, IDispatch --------------------------------------------
STDMETHODIMP JScriptValue::GetTypeInfo( UINT iTInfo,
LCID lcid,
ITypeInfo **ppTInfo)
{
return E_NOTIMPL;
}
// JScriptValue, IDispatch --------------------------------------------
STDMETHODIMP JScriptValue::GetIDsOfNames( REFIID riid,
LPOLESTR *rgszNames,
UINT cNames,
LCID lcid,
DISPID *rgDispId)
{
if( !rgDispId)
return E_POINTER;
HRESULT ret= S_OK;
CComBSTR name(*rgszNames);
name.ToLower();
if( name == CComBSTR( L"set") )
*rgDispId= 1;
else if( name == CComBSTR( L"get") )
*rgDispId= 2;
else if( name == CComBSTR( L"initoutparam") )
*rgDispId= 3;
else if( name == CComBSTR( L"initinoutparam") )
*rgDispId= 4;
else
ret= DISP_E_UNKNOWNNAME;
return ret;
}
// JScriptValue, IDispatch --------------------------------------------
STDMETHODIMP JScriptValue::Invoke( DISPID dispIdMember,
REFIID riid,
LCID lcid,
WORD wFlags,
DISPPARAMS *pDispParams,
VARIANT *pVarResult,
EXCEPINFO *pExcepInfo,
UINT *puArgErr)
{
if( pDispParams->cNamedArgs)
return DISP_E_NONAMEDARGS;
HRESULT ret= S_OK;
switch( dispIdMember)
{
case 0: // DISPID_VALUE
if( wFlags & DISPATCH_PROPERTYGET && pVarResult)
{
if( FAILED( VariantCopy( pVarResult, &m_varValue)))
ret= E_FAIL;
}
else
ret= E_POINTER;
break;
case 1:
if( wFlags & DISPATCH_METHOD)
ret= Set( pDispParams->rgvarg[1], pDispParams->rgvarg[0]);
if( FAILED( ret))
ret= DISP_E_EXCEPTION;
break;
case 2:
if( wFlags & DISPATCH_METHOD)
ret= Get( pVarResult);
if( FAILED( ret))
ret= DISP_E_EXCEPTION;
break;
case 3:
if( wFlags & DISPATCH_METHOD)
ret= InitOutParam();
if( FAILED( ret))
ret= DISP_E_EXCEPTION;
break;
case 4:
if( wFlags & DISPATCH_METHOD)
ret= InitInOutParam( pDispParams->rgvarg[1], pDispParams->rgvarg[0]);
if( FAILED( ret))
ret= DISP_E_EXCEPTION;
break;
default:
ret= DISP_E_MEMBERNOTFOUND;
break;
}
return ret;
}
// JScriptValue, IScriptOutParam-----------------------
STDMETHODIMP JScriptValue::Set( VARIANT type, VARIANT value)
{
Lock();
HRESULT hr= S_OK;
m_varValue.Clear();
hr= VariantCopyInd( &m_varValue, &value);
VARIANT var;
VariantInit( &var);
if( SUCCEEDED( hr= VariantChangeType( &var, &type, 0, VT_BSTR)))
m_bstrType= var.bstrVal;
Unlock();
return hr;
}
// JScriptValue, IScriptOutParam-----------------------
STDMETHODIMP JScriptValue::Get( VARIANT *val)
{
Lock();
if( !val)
return E_POINTER;
HRESULT hr= VariantCopy( val, &m_varValue);
Unlock();
return hr;
}
STDMETHODIMP JScriptValue::InitOutParam()
{
Lock();
m_varValue.Clear();
m_bOutParam= true;
m_bInOutParam= false;
Unlock();
return S_OK;
}
STDMETHODIMP JScriptValue::InitInOutParam( VARIANT type, VARIANT value)
{
Lock();
m_bInOutParam= true;
m_bOutParam= false;
Unlock();
return Set( type, value);
}
STDMETHODIMP JScriptValue::IsOutParam( VARIANT_BOOL * flag)
{
Lock();
if( !flag)
return E_POINTER;
*flag= m_bOutParam ? VARIANT_TRUE : VARIANT_FALSE;
Unlock();
return S_OK;
}
STDMETHODIMP JScriptValue::IsInOutParam( VARIANT_BOOL * flag)
{
Lock();
if( !flag)
return E_POINTER;
*flag= m_bInOutParam ? VARIANT_TRUE : VARIANT_FALSE;
Unlock();
return S_OK;
}
STDMETHODIMP JScriptValue::GetValue( BSTR* type, VARIANT *value)
{
Lock();
if( !type || !value)
return E_POINTER;
HRESULT hr;
if( SUCCEEDED( hr= m_bstrType.CopyTo( type)))
hr= VariantCopy( value, &m_varValue);
Unlock();
return hr;
}
//##########################################################################################
// JScriptOutValue
//##########################################################################################
JScriptOutParam::JScriptOutParam()
{
}
JScriptOutParam::~JScriptOutParam()
{
}
// JScriptOutParam, IDispatch --------------------------------------------
STDMETHODIMP JScriptOutParam::GetTypeInfoCount(UINT *pctinfo)
{
return E_NOTIMPL;
}
// JScriptOutParam, IDispatch --------------------------------------------
STDMETHODIMP JScriptOutParam::GetTypeInfo( UINT iTInfo,
LCID lcid,
ITypeInfo **ppTInfo)
{
return E_NOTIMPL;
}
// JScriptOutParam, IDispatch --------------------------------------------
STDMETHODIMP JScriptOutParam::GetIDsOfNames( REFIID riid,
LPOLESTR *rgszNames,
UINT cNames,
LCID lcid,
DISPID *rgDispId)
{
if( !rgDispId)
return E_POINTER;
HRESULT ret= S_OK;
CComBSTR name(*rgszNames);
name.ToLower();
if( name == CComBSTR( L"0") )
*rgDispId= 1;
else
ret= DISP_E_UNKNOWNNAME;
return ret;
}
// JScriptOutParam, IDispatch --------------------------------------------
STDMETHODIMP JScriptOutParam::Invoke( DISPID dispIdMember,
REFIID riid,
LCID lcid,
WORD wFlags,
DISPPARAMS *pDispParams,
VARIANT *pVarResult,
EXCEPINFO *pExcepInfo,
UINT *puArgErr)
{
HRESULT ret= S_OK;
switch( dispIdMember)
{
case 0: // DISPID_VALUE
if( wFlags & DISPATCH_PROPERTYGET && pVarResult)
{
if( FAILED( VariantCopy( pVarResult, &m_varValue)))
ret= E_FAIL;
}
else if( wFlags & DISPATCH_PROPERTYPUT || wFlags & DISPATCH_PROPERTYPUTREF)
{
m_varValue.Clear();
if( FAILED( VariantCopyInd( &m_varValue, &pDispParams->rgvarg[0])))
ret= E_FAIL;
}
else
ret= E_POINTER;
break;
case 1: //
if( wFlags & DISPATCH_PROPERTYGET && pVarResult)
{
if( FAILED( VariantCopy( pVarResult, &m_varValue)))
ret= E_FAIL;
}
else if( wFlags & DISPATCH_PROPERTYPUT || wFlags & DISPATCH_PROPERTYPUTREF)
{
m_varValue.Clear();
if( FAILED( VariantCopyInd( &m_varValue, &pDispParams->rgvarg[0])))
ret= E_FAIL;
}
else
ret= E_POINTER;
break;
default:
ret= DISP_E_MEMBERNOTFOUND;
break;
}
return ret;
}
<|endoftext|> |
<commit_before>/******************************************************************************
* SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1 *
* (c) 2006-2011 MGH, INRIA, USTL, UJF, CNRS *
* *
* 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 :: Modules *
* *
* Authors: The SOFA Team and external contributors (see Authors.txt) *
* *
* Contact information: [email protected] *
******************************************************************************/
#include <sofa/component/collision/FrictionContact.inl>
namespace sofa
{
namespace component
{
namespace collision
{
using namespace defaulttype;
using namespace sofa::helper;
using simulation::Node;
sofa::core::collision::DetectionOutput::ContactId Identifier::cpt=0;
std::list<sofa::core::collision::DetectionOutput::ContactId> Identifier::availableId;
SOFA_DECL_CLASS(FrictionContact)
Creator<Contact::Factory, FrictionContact<PointModel, PointModel> > PointPointFrictionContactClass("FrictionContact",true);
Creator<Contact::Factory, FrictionContact<LineModel, SphereModel> > LineSphereFrictionContactClass("FrictionContact",true);
Creator<Contact::Factory, FrictionContact<LineModel, PointModel> > LinePointFrictionContactClass("FrictionContact",true);
Creator<Contact::Factory, FrictionContact<LineModel, LineModel> > LineLineFrictionContactClass("FrictionContact",true);
Creator<Contact::Factory, FrictionContact<TriangleModel, SphereModel> > TriangleSphereFrictionContactClass("FrictionContact",true);
Creator<Contact::Factory, FrictionContact<TriangleModel, PointModel> > TrianglePointFrictionContactClass("FrictionContact",true);
Creator<Contact::Factory, FrictionContact<TriangleModel, LineModel> > TriangleLineFrictionContactClass("FrictionContact",true);
Creator<Contact::Factory, FrictionContact<TriangleModel, TriangleModel> > TriangleTriangleFrictionContactClass("FrictionContact",true);
Creator<Contact::Factory, FrictionContact<SphereModel, SphereModel> > SphereSphereFrictionContactClass("FrictionContact",true);
Creator<Contact::Factory, FrictionContact<SphereModel, PointModel> > SpherePointFrictionContactClass("FrictionContact",true);
Creator<Contact::Factory, FrictionContact<CapsuleModel, CapsuleModel> > CapsuleCapsuleFrictionContactClass("FrictionContact",true);
Creator<Contact::Factory, FrictionContact<CapsuleModel, TriangleModel> > CapsuleTriangleFrictionContactClass("FrictionContact",true);
Creator<Contact::Factory, FrictionContact<CapsuleModel, SphereModel> > CapsuleSphereFrictionContactClass("FrictionContact",true);
Creator<Contact::Factory, FrictionContact<OBBModel, OBBModel> > OBBOBBFrictionContactClass("FrictionContact",true);
Creator<Contact::Factory, FrictionContact<SphereModel, OBBModel> > SphereOBBFrictionContactClass("FrictionContact",true);
Creator<Contact::Factory, FrictionContact<CapsuleModel, OBBModel> > CapsuleOBBFrictionContactClass("FrictionContact",true);
Creator<Contact::Factory, FrictionContact<TriangleModel, OBBModel> > TriangleOBBFrictionContactClass("FrictionContact",true);
Creator<Contact::Factory, FrictionContact<RigidSphereModel, RigidSphereModel> > RigidSphereRigidSphereFrictionContactClass("FrictionContact",true);
Creator<Contact::Factory, FrictionContact<SphereModel, RigidSphereModel> > SphereRigidSphereFrictionContactClass("FrictionContact",true);
Creator<Contact::Factory, FrictionContact<LineModel, RigidSphereModel> > LineRigidSphereFrictionContactClass("FrictionContact",true);
Creator<Contact::Factory, FrictionContact<TriangleModel, RigidSphereModel> > TriangleRigidSphereFrictionContactClass("FrictionContact",true);
Creator<Contact::Factory, FrictionContact<RigidSphereModel, PointModel> > RigidSpherePointFrictionContactClass("FrictionContact",true);
Creator<Contact::Factory, FrictionContact<CapsuleModel, RigidSphereModel> > CapsuleRigidSphereFrictionContactClass("FrictionContact",true);
Creator<Contact::Factory, FrictionContact<RigidSphereModel, OBBModel> > RigidSphereOBBFrictionContactClass("FrictionContact",true);
Creator<Contact::Factory, FrictionContact<RigidCapsuleModel, RigidCapsuleModel> > RigidCapsuleRigidCapsuleFrictionContactClass("FrictionContact",true);
Creator<Contact::Factory, FrictionContact<CapsuleModel, RigidCapsuleModel> > CapsuleRigidCapsuleFrictionContactClass("FrictionContact",true);
Creator<Contact::Factory, FrictionContact<RigidCapsuleModel, TriangleModel> > RigidCapsuleTriangleFrictionContactClass("FrictionContact",true);
Creator<Contact::Factory, FrictionContact<RigidCapsuleModel, SphereModel> > RigidCapsuleSphereFrictionContactClass("FrictionContact",true);
Creator<Contact::Factory, FrictionContact<RigidCapsuleModel, OBBModel> > RigidCapsuleOBBFrictionContactClass("FrictionContact",true);
Creator<Contact::Factory, FrictionContact<RigidCapsuleModel, RigidSphereModel> > RigidCapsuleRigidSphereFrictionContactClass("FrictionContact",true);
} // namespace collision
} // namespace component
} // namespace sofa
<commit_msg>r10824/sofa : FIX FrictionContact link on osx/clang<commit_after>/******************************************************************************
* SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1 *
* (c) 2006-2011 MGH, INRIA, USTL, UJF, CNRS *
* *
* 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 :: Modules *
* *
* Authors: The SOFA Team and external contributors (see Authors.txt) *
* *
* Contact information: [email protected] *
******************************************************************************/
#include <sofa/component/collision/FrictionContact.inl>
#include <sofa/component/collision/RigidContactMapper.inl>
#include <sofa/component/collision/BarycentricContactMapper.inl>
namespace sofa
{
namespace component
{
namespace collision
{
using namespace defaulttype;
using namespace sofa::helper;
using simulation::Node;
sofa::core::collision::DetectionOutput::ContactId Identifier::cpt=0;
std::list<sofa::core::collision::DetectionOutput::ContactId> Identifier::availableId;
SOFA_DECL_CLASS(FrictionContact)
Creator<Contact::Factory, FrictionContact<PointModel, PointModel> > PointPointFrictionContactClass("FrictionContact",true);
Creator<Contact::Factory, FrictionContact<LineModel, SphereModel> > LineSphereFrictionContactClass("FrictionContact",true);
Creator<Contact::Factory, FrictionContact<LineModel, PointModel> > LinePointFrictionContactClass("FrictionContact",true);
Creator<Contact::Factory, FrictionContact<LineModel, LineModel> > LineLineFrictionContactClass("FrictionContact",true);
Creator<Contact::Factory, FrictionContact<TriangleModel, SphereModel> > TriangleSphereFrictionContactClass("FrictionContact",true);
Creator<Contact::Factory, FrictionContact<TriangleModel, PointModel> > TrianglePointFrictionContactClass("FrictionContact",true);
Creator<Contact::Factory, FrictionContact<TriangleModel, LineModel> > TriangleLineFrictionContactClass("FrictionContact",true);
Creator<Contact::Factory, FrictionContact<TriangleModel, TriangleModel> > TriangleTriangleFrictionContactClass("FrictionContact",true);
Creator<Contact::Factory, FrictionContact<SphereModel, SphereModel> > SphereSphereFrictionContactClass("FrictionContact",true);
Creator<Contact::Factory, FrictionContact<SphereModel, PointModel> > SpherePointFrictionContactClass("FrictionContact",true);
Creator<Contact::Factory, FrictionContact<CapsuleModel, CapsuleModel> > CapsuleCapsuleFrictionContactClass("FrictionContact",true);
Creator<Contact::Factory, FrictionContact<CapsuleModel, TriangleModel> > CapsuleTriangleFrictionContactClass("FrictionContact",true);
Creator<Contact::Factory, FrictionContact<CapsuleModel, SphereModel> > CapsuleSphereFrictionContactClass("FrictionContact",true);
Creator<Contact::Factory, FrictionContact<OBBModel, OBBModel> > OBBOBBFrictionContactClass("FrictionContact",true);
Creator<Contact::Factory, FrictionContact<SphereModel, OBBModel> > SphereOBBFrictionContactClass("FrictionContact",true);
Creator<Contact::Factory, FrictionContact<CapsuleModel, OBBModel> > CapsuleOBBFrictionContactClass("FrictionContact",true);
Creator<Contact::Factory, FrictionContact<TriangleModel, OBBModel> > TriangleOBBFrictionContactClass("FrictionContact",true);
Creator<Contact::Factory, FrictionContact<RigidSphereModel, RigidSphereModel> > RigidSphereRigidSphereFrictionContactClass("FrictionContact",true);
Creator<Contact::Factory, FrictionContact<SphereModel, RigidSphereModel> > SphereRigidSphereFrictionContactClass("FrictionContact",true);
Creator<Contact::Factory, FrictionContact<LineModel, RigidSphereModel> > LineRigidSphereFrictionContactClass("FrictionContact",true);
Creator<Contact::Factory, FrictionContact<TriangleModel, RigidSphereModel> > TriangleRigidSphereFrictionContactClass("FrictionContact",true);
Creator<Contact::Factory, FrictionContact<RigidSphereModel, PointModel> > RigidSpherePointFrictionContactClass("FrictionContact",true);
Creator<Contact::Factory, FrictionContact<CapsuleModel, RigidSphereModel> > CapsuleRigidSphereFrictionContactClass("FrictionContact",true);
Creator<Contact::Factory, FrictionContact<RigidSphereModel, OBBModel> > RigidSphereOBBFrictionContactClass("FrictionContact",true);
Creator<Contact::Factory, FrictionContact<RigidCapsuleModel, RigidCapsuleModel> > RigidCapsuleRigidCapsuleFrictionContactClass("FrictionContact",true);
Creator<Contact::Factory, FrictionContact<CapsuleModel, RigidCapsuleModel> > CapsuleRigidCapsuleFrictionContactClass("FrictionContact",true);
Creator<Contact::Factory, FrictionContact<RigidCapsuleModel, TriangleModel> > RigidCapsuleTriangleFrictionContactClass("FrictionContact",true);
Creator<Contact::Factory, FrictionContact<RigidCapsuleModel, SphereModel> > RigidCapsuleSphereFrictionContactClass("FrictionContact",true);
Creator<Contact::Factory, FrictionContact<RigidCapsuleModel, OBBModel> > RigidCapsuleOBBFrictionContactClass("FrictionContact",true);
Creator<Contact::Factory, FrictionContact<RigidCapsuleModel, RigidSphereModel> > RigidCapsuleRigidSphereFrictionContactClass("FrictionContact",true);
} // namespace collision
} // namespace component
} // namespace sofa
<|endoftext|> |
<commit_before>#include <sys/resource.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <signal.h>
#include <pthread.h>
static sigset_t DaemonSignalSet;
extern "C" {
/*
* Signal handler thread for the daemon. Waits for one of the following
* signals:
* - SIGINT
* - SIGTERM
* - SIGQUIT
* Once the signal is received, the stop method in the stop class in
* the Java code is invoked and then the thread exits.
*/
static void *
DaemonSignalHandler(void *)
{
int signo;
int stop = 0;
while (1) {
sigwait(&DaemonSignalSet, &signo);
switch (signo) {
case SIGINT:
case SIGTERM:
case SIGQUIT:
stop = 1;
break;
default:
break;
}
if (stop) {
if (StopDaemon() == JNI_OK) {
break;
}
}
}
return 0;
}
}
/*
* Checks if another instance of the daemon is already running. The running
* daemon keeps a lock on pidPath. Please note that 'fd' is not closed.
* This is intentional. Must be called after the process has daemonized
* itself.
*
* @param [out] running - set to true if another instance of the daemon
* is running, set to false otherwise.
*
* @return 0 on success, non-zero on failure.
*/
static int
DaemonAlreadyRunning(bool *running)
{
const char *caller = "DaemonAlreadyRunning";
int retval = 0;
int fd;
struct flock fl;
*running = false;
fd = open(TheDaemonArgs.pidPath.c_str(), O_CREAT | O_RDWR, 0644);
if (fd < 0) {
Log(ERR, caller, errno, "open(%s) failed",
TheDaemonArgs.pidPath.c_str());
return 1;
} else {
fl.l_type = F_WRLCK;
fl.l_whence = SEEK_SET;
fl.l_start = 0;
fl.l_len = 0;
if (fcntl(fd, F_SETLK, &fl) < 0) {
if ((errno == EACCES) || (errno == EAGAIN)) {
*running = true;
retval = 0;
} else {
Log(ERR, caller, errno, "lock(%s) failed",
TheDaemonArgs.pidPath.c_str());
retval = 1;
}
close(fd);
} else {
char buf[32];
if (ftruncate(fd, 0) < 0) {
Log(ERR, caller, errno, "ftruncate() failed");
retval = 1;
} else {
int nbytes = snprintf(buf, sizeof(buf) - 1, "%d", getpid());
buf[nbytes] = '\0';
if (write(fd, buf, nbytes) < 0) {
Log(ERR, caller, errno, "write() failed");
}
}
// keep fd open; fd leak is justified.
}
}
return retval;
}
/*
* Sends SIGTERM signal to the daemon. The process' pid is obtained from
* the pidPath.
*
* @return 0 on success, non-zero on failure.
*/
static int
DaemonStop(void)
{
const char *caller = "DaemonStop";
int retval = 0;
FILE *fp = 0;
int i, pid;
fp = fopen(TheDaemonArgs.pidPath.c_str(), "r");
if (fp) {
i = fscanf(fp, "%d", &pid);
if (i != 1) {
Log(ERR, caller, errno,
"unable to read pid from file %s",
TheDaemonArgs.pidPath.c_str());
retval = 1;
} else {
if (kill(pid, SIGTERM) < 0) {
Log(ERR, caller, errno,
"unable to kill process %d", pid);
retval = 1;
}
}
fclose(fp);
} else {
Log(ERR, caller, errno,
"unable to open file %s",
TheDaemonArgs.pidPath.c_str());
retval = 1;
}
return retval;
}
/*
* Turns the calling process into a daemon process. It does the following:
* - Sets the umask to 0.
* - Forks and let the parent exit.
* - Creates a new session (setsid).
* - Change directory to the home directory.
* - Close all the open file descriptors (0, 1, and 2 are most important).
* - Initialize the Logging.
* - Check if only a single instance of the daemon is running.
* - Blocks SIGINT, SIGTERM, SIGQUIT signal.
* - Starts another thread to handle those events.
* - Use JNI invoke APIs to load JVM.
* - Calls the start method in the start class in the Java code.
*
* @return 0 on success, non-zero on failure.
*/
static int
Daemonize(void)
{
const char *caller = "Daemonize";
int retval = 0;
bool alreadyRunning;
pid_t pid;
struct rlimit rl;
pthread_t tid;
umask(0);
pid = fork();
if (pid < 0) {
Log(ERR, caller, errno, "fork() failed");
return 1;
}
if (pid != 0)
exit(0);
if (setsid() < 0) {
Log(ERR, caller, errno, "setsid() failed");
return 1;
}
if (chdir(TheDaemonArgs.home.c_str()) < 0) {
Log(ERR, caller, errno, "chdir(%s) failed",
TheDaemonArgs.home.c_str());
return 1;
}
if (getrlimit(RLIMIT_NOFILE, &rl) < 0) {
Log(ERR, caller, errno, "getrlimit() failed");
return 1;
}
if (rl.rlim_max == RLIM_INFINITY) {
rl.rlim_max = 1024;
}
for (rlim_t r = 0; r < rl.rlim_max; ++r) {
close((int)r);
}
FileLogger *fileLogger = new FileLogger(TheDaemonArgs.logPath.c_str(), TheVerbosity);
fileLogger->makeLogPath();
TheLogger = fileLogger;
Log(INF, caller, "starting daemon");
LogDaemonArgs();
retval = DaemonAlreadyRunning(&alreadyRunning);
if (retval != 0) {
return retval;
} else if (alreadyRunning) {
Log(WRN, caller, "another instance of %s already running",
TheDaemonArgs.name.c_str());
return 1;
}
sigemptyset(&DaemonSignalSet);
sigaddset(&DaemonSignalSet, SIGINT);
sigaddset(&DaemonSignalSet, SIGTERM);
sigaddset(&DaemonSignalSet, SIGQUIT);
retval = pthread_sigmask(SIG_BLOCK, &DaemonSignalSet, NULL);
if (retval != 0) {
Log(ERR, caller, retval, "pthread_sigmask() failed");
return 1;
}
retval = pthread_create(&tid, 0, DaemonSignalHandler, 0);
if (retval != 0) {
Log(ERR, caller, retval, "pthread_create() failed");
return 1;
}
if (StartDaemon() == JNI_OK) {
Log(INF, caller, "daemon running");
} else {
Log(ERR, caller, "failed to call Java code");
kill(getpid(), SIGTERM);
}
retval = pthread_join(tid, 0);
if (retval != 0) {
Log(ERR, caller, retval, "pthread_join() failed");
return 1;
}
if (TheJVM) {
TheJVM->DestroyJavaVM();
Log(DBG, caller, "JVM destroyed");
}
Log(INF, caller, "daemon stopped");
delete TheLogger;
return 0;
}
<commit_msg>Use pthread_kill() instead of kill() when StartDedaemon() fails.<commit_after>#include <sys/resource.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <signal.h>
#include <pthread.h>
static sigset_t DaemonSignalSet;
extern "C" {
/*
* Signal handler thread for the daemon. Waits for one of the following
* signals:
* - SIGINT
* - SIGTERM
* - SIGQUIT
* Once the signal is received, the stop method in the stop class in
* the Java code is invoked and then the thread exits.
*/
static void *
DaemonSignalHandler(void *)
{
int signo;
int stop = 0;
while (1) {
sigwait(&DaemonSignalSet, &signo);
switch (signo) {
case SIGINT:
case SIGTERM:
case SIGQUIT:
stop = 1;
break;
default:
break;
}
if (stop) {
if (StopDaemon() == JNI_OK) {
break;
}
}
}
return 0;
}
}
/*
* Checks if another instance of the daemon is already running. The running
* daemon keeps a lock on pidPath. Please note that 'fd' is not closed.
* This is intentional. Must be called after the process has daemonized
* itself.
*
* @param [out] running - set to true if another instance of the daemon
* is running, set to false otherwise.
*
* @return 0 on success, non-zero on failure.
*/
static int
DaemonAlreadyRunning(bool *running)
{
const char *caller = "DaemonAlreadyRunning";
int retval = 0;
int fd;
struct flock fl;
*running = false;
fd = open(TheDaemonArgs.pidPath.c_str(), O_CREAT | O_RDWR, 0644);
if (fd < 0) {
Log(ERR, caller, errno, "open(%s) failed",
TheDaemonArgs.pidPath.c_str());
return 1;
} else {
fl.l_type = F_WRLCK;
fl.l_whence = SEEK_SET;
fl.l_start = 0;
fl.l_len = 0;
if (fcntl(fd, F_SETLK, &fl) < 0) {
if ((errno == EACCES) || (errno == EAGAIN)) {
*running = true;
retval = 0;
} else {
Log(ERR, caller, errno, "lock(%s) failed",
TheDaemonArgs.pidPath.c_str());
retval = 1;
}
close(fd);
} else {
char buf[32];
if (ftruncate(fd, 0) < 0) {
Log(ERR, caller, errno, "ftruncate() failed");
retval = 1;
} else {
int nbytes = snprintf(buf, sizeof(buf) - 1, "%d", getpid());
buf[nbytes] = '\0';
if (write(fd, buf, nbytes) < 0) {
Log(ERR, caller, errno, "write() failed");
}
}
// keep fd open; fd leak is justified.
}
}
return retval;
}
/*
* Sends SIGTERM signal to the daemon. The process' pid is obtained from
* the pidPath.
*
* @return 0 on success, non-zero on failure.
*/
static int
DaemonStop(void)
{
const char *caller = "DaemonStop";
int retval = 0;
FILE *fp = 0;
int i, pid;
fp = fopen(TheDaemonArgs.pidPath.c_str(), "r");
if (fp) {
i = fscanf(fp, "%d", &pid);
if (i != 1) {
Log(ERR, caller, errno,
"unable to read pid from file %s",
TheDaemonArgs.pidPath.c_str());
retval = 1;
} else {
if (kill(pid, SIGTERM) < 0) {
Log(ERR, caller, errno,
"unable to kill process %d", pid);
retval = 1;
}
}
fclose(fp);
} else {
Log(ERR, caller, errno,
"unable to open file %s",
TheDaemonArgs.pidPath.c_str());
retval = 1;
}
return retval;
}
/*
* Turns the calling process into a daemon process. It does the following:
* - Sets the umask to 0.
* - Forks and let the parent exit.
* - Creates a new session (setsid).
* - Change directory to the home directory.
* - Close all the open file descriptors (0, 1, and 2 are most important).
* - Initialize the Logging.
* - Check if only a single instance of the daemon is running.
* - Blocks SIGINT, SIGTERM, SIGQUIT signal.
* - Starts another thread to handle those events.
* - Use JNI invoke APIs to load JVM.
* - Calls the start method in the start class in the Java code.
*
* @return 0 on success, non-zero on failure.
*/
static int
Daemonize(void)
{
const char *caller = "Daemonize";
int retval = 0;
bool alreadyRunning;
pid_t pid;
struct rlimit rl;
pthread_t tid;
umask(0);
pid = fork();
if (pid < 0) {
Log(ERR, caller, errno, "fork() failed");
return 1;
}
if (pid != 0)
exit(0);
if (setsid() < 0) {
Log(ERR, caller, errno, "setsid() failed");
return 1;
}
if (chdir(TheDaemonArgs.home.c_str()) < 0) {
Log(ERR, caller, errno, "chdir(%s) failed",
TheDaemonArgs.home.c_str());
return 1;
}
if (getrlimit(RLIMIT_NOFILE, &rl) < 0) {
Log(ERR, caller, errno, "getrlimit() failed");
return 1;
}
if (rl.rlim_max == RLIM_INFINITY) {
rl.rlim_max = 1024;
}
for (rlim_t r = 0; r < rl.rlim_max; ++r) {
close((int)r);
}
FileLogger *fileLogger = new FileLogger(TheDaemonArgs.logPath.c_str(), TheVerbosity);
fileLogger->makeLogPath();
TheLogger = fileLogger;
Log(INF, caller, "starting daemon");
LogDaemonArgs();
retval = DaemonAlreadyRunning(&alreadyRunning);
if (retval != 0) {
return retval;
} else if (alreadyRunning) {
Log(WRN, caller, "another instance of %s already running",
TheDaemonArgs.name.c_str());
return 1;
}
sigemptyset(&DaemonSignalSet);
sigaddset(&DaemonSignalSet, SIGINT);
sigaddset(&DaemonSignalSet, SIGTERM);
sigaddset(&DaemonSignalSet, SIGQUIT);
retval = pthread_sigmask(SIG_BLOCK, &DaemonSignalSet, NULL);
if (retval != 0) {
Log(ERR, caller, retval, "pthread_sigmask() failed");
return 1;
}
retval = pthread_create(&tid, 0, DaemonSignalHandler, 0);
if (retval != 0) {
Log(ERR, caller, retval, "pthread_create() failed");
return 1;
}
if (StartDaemon() == JNI_OK) {
Log(INF, caller, "daemon running");
} else {
Log(ERR, caller, "failed to call Java code");
pthread_kill(tid, SIGTERM);
}
retval = pthread_join(tid, 0);
if (retval != 0) {
Log(ERR, caller, retval, "pthread_join() failed");
return 1;
}
if (TheJVM) {
TheJVM->DestroyJavaVM();
Log(DBG, caller, "JVM destroyed");
}
Log(INF, caller, "daemon stopped");
delete TheLogger;
return 0;
}
<|endoftext|> |
<commit_before>/**
* Software License Agreement (BSD License)
*
* Copyright (c) 2011, Willow Garage, 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 Willow Garage, Inc. 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.
*
* $Id$
*
*/
#include <pcl/visualization/cloud_viewer.h>
#include <pcl/visualization/pcl_visualizer.h>
#include <boost/thread.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/foreach.hpp>
namespace pcl
{
struct cloud_show_base
{
virtual void pop () = 0;
virtual bool popped () const = 0;
typedef boost::shared_ptr<cloud_show_base> Ptr;
};
template <typename CloudT>
struct cloud_show : cloud_show_base
{
cloud_show (const std::string &cloud_name, typename CloudT::ConstPtr cloud,
boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer) :
cloud_name (cloud_name), cloud (cloud), viewer (viewer),popped_ (false)
{}
template <typename Handler> void
pop (const Handler &handler)
{
double psize = 1.0, opacity = 1.0, linesize =1.0;
viewer->getPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_LINE_WIDTH, linesize, cloud_name);
viewer->getPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_OPACITY, opacity, cloud_name);
viewer->getPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, psize, cloud_name);
if (!viewer->updatePointCloud (cloud, handler, cloud_name))
{
viewer->addPointCloud (cloud, handler, cloud_name);
viewer->resetCameraViewpoint (cloud_name);
}
// viewer->removePointCloud (cloud_name);
viewer->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_LINE_WIDTH, linesize, cloud_name);
viewer->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_OPACITY, opacity, cloud_name);
viewer->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, psize, cloud_name);
popped_ = true;
}
virtual void pop ();
virtual bool
popped () const
{
return popped_;
}
std::string cloud_name;
typename CloudT::ConstPtr cloud;
boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer;
bool popped_;
};
typedef pcl::PointCloud<pcl::PointXYZRGB> cc;
typedef pcl::PointCloud<pcl::PointXYZI> gc;
typedef pcl::PointCloud<pcl::PointXYZ> mc;
template <> void
cloud_show<cc>::pop ()
{
pcl::visualization::PointCloudColorHandlerRGBField<pcl::PointXYZRGB> handler (cloud);
pop (handler);
}
template <> void
cloud_show<gc>::pop ()
{
pcl::visualization::PointCloudGeometryHandlerXYZ<pcl::PointXYZI> handler (cloud);
pop (handler);
}
template <> void
cloud_show<mc>::pop ()
{
pcl::visualization::PointCloudGeometryHandlerXYZ<pcl::PointXYZ> handler (cloud);
pop (handler);
}
}
struct pcl::visualization::CloudViewer::CloudViewer_impl
{
////////////////////////////////////////////////////////////////////////////////////////////
CloudViewer_impl (const std::string& window_name) :
window_name_ (window_name), has_cloud_ (false), quit_ (false)
{
viewer_thread_ = boost::thread (boost::ref (*this));
while (!viewer_)
{
boost::thread::yield ();
}
}
~CloudViewer_impl ()
{
}
////////////////////////////////////////////////////////////////////////////////////////////
template <typename T> void
block_post_cloud (const typename T::ConstPtr &cloud, const std::string &name)
{
cloud_show_base::Ptr cs (new cloud_show<T>(name,cloud,viewer_));
{
boost::mutex::scoped_lock lock (mtx_);
cloud_shows_.push_back (cs);
}
while (!cs->popped ())
{
boost::thread::yield ();
}
}
template <typename T> void
nonblock_post_cloud (const typename T::ConstPtr &cloud, const std::string &name)
{
cloud_show_base::Ptr cs (new cloud_show<T>(name,cloud,viewer_));
{
boost::mutex::scoped_lock lock (mtx_);
cloud_shows_.push_back (cs);
}
}
////////////////////////////////////////////////////////////////////////////////////////////
void
operator() ()
{
using namespace pcl::visualization;
viewer_ = boost::shared_ptr<PCLVisualizer>(new PCLVisualizer (window_name_));
viewer_->setBackgroundColor (0.1, 0.1, 0.1);
viewer_->addCoordinateSystem (0.1);
while (!quit_)
{
{
boost::mutex::scoped_lock lock (mtx_);
while (!cloud_shows_.empty ())
{
cloud_shows_.back ()->pop ();
cloud_shows_.pop_back ();
}
}
{
boost::mutex::scoped_lock lock (once_mtx);
BOOST_FOREACH (CallableList::value_type& x, callables_once)
{
(x)(*viewer_);
}
callables_once.clear ();
}
{
boost::mutex::scoped_lock lock (c_mtx);
BOOST_FOREACH (CallableMap::value_type& x, callables)
{
(x.second)(*viewer_);
}
}
if (viewer_->wasStopped ())
{
quit_ = true;
}else
{
boost::mutex::scoped_lock lock (spin_mtx_);
//TODO some smart waitkey like stuff here, so that wasStoped() can hold for a long time
//maybe a counter
viewer_->spinOnce (10); // Give the GUI millis to handle events, then return
}
}
viewer_.reset();
}
////////////////////////////////////////////////////////////////////////////////////////////
void
post (VizCallable x, const std::string &key)
{
boost::mutex::scoped_lock lock (c_mtx);
callables[key] = x;
}
void
post (VizCallable x)
{
boost::mutex::scoped_lock lock (once_mtx);
callables_once.push_back (x);
}
////////////////////////////////////////////////////////////////////////////////////////////
void
remove (const std::string &key)
{
boost::mutex::scoped_lock lock (c_mtx);
if (callables.find (key) != callables.end ())
{
callables.erase (key);
}
}
std::string window_name_;
boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer_;
boost::mutex mtx_, spin_mtx_, c_mtx, once_mtx;
boost::thread viewer_thread_;
bool has_cloud_;
bool quit_;
std::list<boost::shared_ptr<cloud_show_base> > cloud_shows_;
typedef std::map<std::string, VizCallable> CallableMap;
CallableMap callables;
typedef std::list<VizCallable> CallableList;
CallableList callables_once;
};
pcl::visualization::CloudViewer::CloudViewer (const std::string &window_name) :
impl_ (new CloudViewer_impl (window_name))
{}
pcl::visualization::CloudViewer::~CloudViewer ()
{
impl_->quit_ = true;
impl_->viewer_thread_.join();
}
void
pcl::visualization::CloudViewer::showCloud (const ColorCloud::ConstPtr &cloud,
const std::string &cloudname)
{
if (!impl_->viewer_ || impl_->viewer_->wasStopped ())
return;
impl_->block_post_cloud<ColorCloud>(cloud, cloudname);
}
void
pcl::visualization::CloudViewer::showCloud (const GrayCloud::ConstPtr &cloud,
const std::string &cloudname)
{
if (!impl_->viewer_ || impl_->viewer_->wasStopped ())
return;
impl_->block_post_cloud<GrayCloud>(cloud, cloudname);
}
void
pcl::visualization::CloudViewer::showCloud (const MonochromeCloud::ConstPtr &cloud,
const std::string &cloudname)
{
if (!impl_->viewer_ || impl_->viewer_->wasStopped ())
return;
impl_->block_post_cloud<MonochromeCloud>(cloud, cloudname);
}
void
pcl::visualization::CloudViewer::runOnVisualizationThread (VizCallable x, const std::string &key)
{
impl_->post (x, key);
}
void
pcl::visualization::CloudViewer::runOnVisualizationThreadOnce (VizCallable x)
{
impl_->post (x);
}
void
pcl::visualization::CloudViewer::removeVisualizationCallable (const std::string &key)
{
impl_->remove (key);
}
bool
pcl::visualization::CloudViewer::wasStopped (int millis)
{
boost::thread::yield (); //allow this to be called in a loop
return !impl_->viewer_;
}
<commit_msg>displaying intensity correctly now<commit_after>/**
* Software License Agreement (BSD License)
*
* Copyright (c) 2011, Willow Garage, 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 Willow Garage, Inc. 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.
*
* $Id$
*
*/
#include <pcl/visualization/cloud_viewer.h>
#include <pcl/visualization/pcl_visualizer.h>
#include <boost/thread.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/foreach.hpp>
namespace pcl
{
struct cloud_show_base
{
virtual void pop () = 0;
virtual bool popped () const = 0;
typedef boost::shared_ptr<cloud_show_base> Ptr;
};
template <typename CloudT>
struct cloud_show : cloud_show_base
{
cloud_show (const std::string &cloud_name, typename CloudT::ConstPtr cloud,
boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer) :
cloud_name (cloud_name), cloud (cloud), viewer (viewer),popped_ (false)
{}
template <typename Handler> void
pop (const Handler &handler)
{
double psize = 1.0, opacity = 1.0, linesize =1.0;
viewer->getPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_LINE_WIDTH, linesize, cloud_name);
viewer->getPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_OPACITY, opacity, cloud_name);
viewer->getPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, psize, cloud_name);
if (!viewer->updatePointCloud (cloud, handler, cloud_name))
{
viewer->addPointCloud (cloud, handler, cloud_name);
viewer->resetCameraViewpoint (cloud_name);
}
// viewer->removePointCloud (cloud_name);
viewer->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_LINE_WIDTH, linesize, cloud_name);
viewer->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_OPACITY, opacity, cloud_name);
viewer->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, psize, cloud_name);
popped_ = true;
}
virtual void pop ();
virtual bool
popped () const
{
return popped_;
}
std::string cloud_name;
typename CloudT::ConstPtr cloud;
boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer;
bool popped_;
};
typedef pcl::PointCloud<pcl::PointXYZRGB> cc;
typedef pcl::PointCloud<pcl::PointXYZI> gc;
typedef pcl::PointCloud<pcl::PointXYZ> mc;
template <> void
cloud_show<cc>::pop ()
{
pcl::visualization::PointCloudColorHandlerRGBField<pcl::PointXYZRGB> handler (cloud);
pop (handler);
}
template <> void
cloud_show<gc>::pop ()
{
pcl::visualization::PointCloudColorHandlerGenericField<pcl::PointXYZI> handler (cloud, "intensity");
pop (handler);
}
template <> void
cloud_show<mc>::pop ()
{
pcl::visualization::PointCloudGeometryHandlerXYZ<pcl::PointXYZ> handler (cloud);
pop (handler);
}
}
struct pcl::visualization::CloudViewer::CloudViewer_impl
{
////////////////////////////////////////////////////////////////////////////////////////////
CloudViewer_impl (const std::string& window_name) :
window_name_ (window_name), has_cloud_ (false), quit_ (false)
{
viewer_thread_ = boost::thread (boost::ref (*this));
while (!viewer_)
{
boost::thread::yield ();
}
}
~CloudViewer_impl ()
{
}
////////////////////////////////////////////////////////////////////////////////////////////
template <typename T> void
block_post_cloud (const typename T::ConstPtr &cloud, const std::string &name)
{
cloud_show_base::Ptr cs (new cloud_show<T>(name,cloud,viewer_));
{
boost::mutex::scoped_lock lock (mtx_);
cloud_shows_.push_back (cs);
}
while (!cs->popped ())
{
boost::thread::yield ();
}
}
template <typename T> void
nonblock_post_cloud (const typename T::ConstPtr &cloud, const std::string &name)
{
cloud_show_base::Ptr cs (new cloud_show<T>(name,cloud,viewer_));
{
boost::mutex::scoped_lock lock (mtx_);
cloud_shows_.push_back (cs);
}
}
////////////////////////////////////////////////////////////////////////////////////////////
void
operator() ()
{
using namespace pcl::visualization;
viewer_ = boost::shared_ptr<PCLVisualizer>(new PCLVisualizer (window_name_));
viewer_->setBackgroundColor (0.1, 0.1, 0.1);
viewer_->addCoordinateSystem (0.1);
while (!quit_)
{
{
boost::mutex::scoped_lock lock (mtx_);
while (!cloud_shows_.empty ())
{
cloud_shows_.back ()->pop ();
cloud_shows_.pop_back ();
}
}
{
boost::mutex::scoped_lock lock (once_mtx);
BOOST_FOREACH (CallableList::value_type& x, callables_once)
{
(x)(*viewer_);
}
callables_once.clear ();
}
{
boost::mutex::scoped_lock lock (c_mtx);
BOOST_FOREACH (CallableMap::value_type& x, callables)
{
(x.second)(*viewer_);
}
}
if (viewer_->wasStopped ())
{
quit_ = true;
}else
{
boost::mutex::scoped_lock lock (spin_mtx_);
//TODO some smart waitkey like stuff here, so that wasStoped() can hold for a long time
//maybe a counter
viewer_->spinOnce (10); // Give the GUI millis to handle events, then return
}
}
viewer_.reset();
}
////////////////////////////////////////////////////////////////////////////////////////////
void
post (VizCallable x, const std::string &key)
{
boost::mutex::scoped_lock lock (c_mtx);
callables[key] = x;
}
void
post (VizCallable x)
{
boost::mutex::scoped_lock lock (once_mtx);
callables_once.push_back (x);
}
////////////////////////////////////////////////////////////////////////////////////////////
void
remove (const std::string &key)
{
boost::mutex::scoped_lock lock (c_mtx);
if (callables.find (key) != callables.end ())
{
callables.erase (key);
}
}
std::string window_name_;
boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer_;
boost::mutex mtx_, spin_mtx_, c_mtx, once_mtx;
boost::thread viewer_thread_;
bool has_cloud_;
bool quit_;
std::list<boost::shared_ptr<cloud_show_base> > cloud_shows_;
typedef std::map<std::string, VizCallable> CallableMap;
CallableMap callables;
typedef std::list<VizCallable> CallableList;
CallableList callables_once;
};
pcl::visualization::CloudViewer::CloudViewer (const std::string &window_name) :
impl_ (new CloudViewer_impl (window_name))
{}
pcl::visualization::CloudViewer::~CloudViewer ()
{
impl_->quit_ = true;
impl_->viewer_thread_.join();
}
void
pcl::visualization::CloudViewer::showCloud (const ColorCloud::ConstPtr &cloud,
const std::string &cloudname)
{
if (!impl_->viewer_ || impl_->viewer_->wasStopped ())
return;
impl_->block_post_cloud<ColorCloud>(cloud, cloudname);
}
void
pcl::visualization::CloudViewer::showCloud (const GrayCloud::ConstPtr &cloud,
const std::string &cloudname)
{
if (!impl_->viewer_ || impl_->viewer_->wasStopped ())
return;
impl_->block_post_cloud<GrayCloud>(cloud, cloudname);
}
void
pcl::visualization::CloudViewer::showCloud (const MonochromeCloud::ConstPtr &cloud,
const std::string &cloudname)
{
if (!impl_->viewer_ || impl_->viewer_->wasStopped ())
return;
impl_->block_post_cloud<MonochromeCloud>(cloud, cloudname);
}
void
pcl::visualization::CloudViewer::runOnVisualizationThread (VizCallable x, const std::string &key)
{
impl_->post (x, key);
}
void
pcl::visualization::CloudViewer::runOnVisualizationThreadOnce (VizCallable x)
{
impl_->post (x);
}
void
pcl::visualization::CloudViewer::removeVisualizationCallable (const std::string &key)
{
impl_->remove (key);
}
bool
pcl::visualization::CloudViewer::wasStopped (int millis)
{
boost::thread::yield (); //allow this to be called in a loop
return !impl_->viewer_;
}
<|endoftext|> |
<commit_before>// Copyright (c) Facebook Inc. and Microsoft Corporation.
// Licensed under the MIT license.
#include "onnx/defs/schema.h"
using AttrType = onnx::OpSchema::AttrType;
using namespace onnx;
OPERATOR_SCHEMA(SimpleRNN)
.NumInputs(3, 6)
.NumOutputs(1, 2)
.SetDoc(R"DOC(
Computes an one-layer simple RNN. This operator is usually supported
via some custom implementation such as CuDNN.
Notations:
`X` - input tensor
`i` - input gate
`t` - time step (t-1 means previous time step)
`Wi` - W parameter weight matrix for input gate
`Ri` - R recurrence weight matrix for input gate
`Wbi` - W parameter bias vector for input gate
`Rbi` - R parameter bias vector for input gate
`WBi` - W parameter weight matrix for backward input gate
`RBi` - R recurrence weight matrix for backward input gate
`WBbi` - WR bias vectors for backward input gate
`RBbi` - RR bias vectors for backward input gate
`ReLU(X)` - max(X, 0)
`tanh(X)` - hyperbolic tangent of X
`H` - Hidden state
`num_directions` - 2 if direction == bidirectional else 1
Equations:
- Ht = Activation(Wi*Xt + Ri*Ht-1 + Wbi + Rbi)
)DOC")
.Attr("activation", "The activation function for input gate. It must be "
"one of tanh and ReLU. Default `tanh`.",
AttrType::STRING)
.Attr("hidden_size", "Number of neurons in the hidden layer", AttrType::INT)
.Attr("direction", "Specify if the RNN is forward, reverse, or bidirectional. "
"Must be one of forward (default), reverse, or bidirectional.",
AttrType::STRING)
.Attr("clip", "Cell clip threshold. Clipping bounds the elements of a tensor "
"in the range of [-threshold, +threshold] and is applied to the input "
"of activations. No clip if not specified.",
AttrType::FLOAT)
.Input(0, "input",
"The input sequences packed (and potentially padded) into one 3-D "
"tensor with the shape of `[seq_length, batch_size, input_size]`.", "T")
.Input(1, "W",
"The weight tensor for input gate. Concatenation of `Wi` and `WBi` "
"(if bidirectional). The tensor has shape "
"`num_directions, hidden_size, input_size]`.", "T")
.Input(2, "R",
"The recurrence weight tensor. Concatenation of `Ri` and `RBi` "
"(if bidirectional). The tensor has shape "
"`[num_directions, hidden_size, hidden_size}`.", "T")
.Input(3, "B",
"The bias tensor for input gate. Concatenation of `[Wbi, Rbi]`, "
"and `[WBbi, RBbi]` (if bidirectional). The tensor has shape "
"`[num_directions, 2*hidden_size]`, Optional: If not specified - assumed "
"to be 0.", "T",
true /*optional*/)
.Input(4, "initial_h",
"Optional initial value of the hidden. If not specified - assumed "
"to be 0. It has shape either `[num_directions, batch_size, hidden_size]`.",
"T", true /*optional*/)
.Input(5, "seq_lens",
"Optional tensor specifying lengths of the sequences in a batch. "
"If not specified - assumed all sequences in the batch to have "
"length `seq_length`. It has shape `[batch_size]`.", "T1",
true /*optional*/)
.Output(0, "output",
"A tensor that concats all the intermediate output values of the hidden."
"It has shape `[seq_length, num_directions, batch_size, hidden_size]`.", "T")
.Output(1, "output_h",
"The last output value of the hidden. It has shape "
"`[num_directions, batch_size, hidden_size]`.", "T")
.TypeConstraint("T", { "tensor(float16)", "tensor(float)", "tensor(double)" },
"Constrain input and output types to float tensors.")
.TypeConstraint("T1", { "tensor(int32)" }, "Constrain seq_lens to integer tensor.");
OPERATOR_SCHEMA(GRU)
.NumInputs(3, 6)
.NumOutputs(1, 2)
.SetDoc(R"DOC(
Computes an one-layer GRU. This operator is usually supported via some custom
implementation such as CuDNN.
Notations:
`X` - input tensor
`z` - update gate
`r` - reset gate
`h` - hidden gate
`t` - time step (t-1 means previous time step)
`W[zrh]` - W parameter weight matrix for update, reset, and hidden gates
`R[zrh]` - R recurrence weight matrix for update, reset, and hidden gates
`Wb[zrh]` - W bias vectors for update, reset, and hidden gates
`Rb[zrh]` - R bias vectors for update, reset, and hidden gates
`WB[zrh]` - W parameter weight matrix for backward update, reset, and hidden gates
`RB[zrh]` - R recurrence weight matrix for backward update, reset, and hidden gates
`WBb[zrh]` - W bias vectors for backward update, reset, and hidden gates
`RBb[zrh]` - R bias vectors for backward update, reset, and hidden gates
`tanh(X)` - hyperbolic tangent of X
`sigmoid(X)` - 1 / (1 + e^-X)
`H` - Hidden state
`num_directions` - 2 if direction == bidirectional else 1
Equations (GRU with default activations):
- zt = sigmoid(Wz*Xt + Rz*Ht-1 + Wbz + Rbz)
- rt = sigmoid(Wr*Xt + Rr*Ht-1 + Wbr + Rbr)
- ht = tanh(Wh*Xt + rt*(Rh*Ht-1 + Rbh) + Wbh)
- H = (1 - zt) (.) ht + it (.) Ht-1
)DOC")
.Attr("activations", "A list of 3 activation functions for update, reset, and "
"hidden gates. The activation functions must be one of sigmoid and tanh. "
"See the equations for default if not specified.",
AttrType::STRINGS)
.Attr("hidden_size", "Number of neurons in the hidden layer", AttrType::INT)
.Attr("direction", "Specify if the RNN is forward, reverse, or bidirectional. "
"Must be one of forward (default), reverse, or bidirectional.",
AttrType::STRING)
.Attr("clip", "Cell clip threshold. Clipping bounds the elements of a tensor "
"in the range of [-threshold, +threshold] and is applied to the input "
"of activations. No clip if not specified.",
AttrType::FLOAT)
.Input(0, "input",
"The input sequences packed (and potentially padded) into one 3-D "
"tensor with the shape of `[seq_length, batch_size, input_size]`.", "T")
.Input(1, "W",
"The weight tensor for the gates. Concatenation of `W[zrh]` and `WB[zrh]` "
"(if bidirectional) along dimension 0. This tensor has shape "
"`[num_directions, 3*hidden_size, input_size]`.", "T")
.Input(2, "R",
"The recurrence weight tensor. Concatenation of `R[zrh]` and `RB[zrh]` "
"(if bidirectional) along dimension 0. This tensor has shape "
"`[num_directions, 3*hidden_size, hidden_size}`.", "T")
.Input(3, "B",
"The bias tensor for the gates. Concatenation of `[Wb[zrh], Rb[zrh]]` and "
"`[WBb[zrh], RBb[zrh]]` (if bidirectional) along dimension 0. This tensor "
"has shape `[num_directions, 6*hidden_size]`. Optional: If not specified "
"- assumed to be 0", "T",
true /*optional*/)
.Input(4, "initial_h",
"Optional initial value of the hidden. If not specified - assumed "
"to be 0. It has shape `[num_directions, batch_size, hidden_size]`.",
"T", true /*optional*/)
.Input(5, "seq_lens",
"Optional tensor specifying lengths of the sequences in a batch. "
"If not specified - assumed all sequences in the batch to have "
"length `seq_length`. It has shape `[batch_size]`.",
"T1", true /*optional*/)
.Output(0, "output",
"A tensor that concats all the intermediate output values of the "
"hidden. It has shape `[seq_length, num_directions, batch_size, hidden_size]`.",
"T")
.Output(1, "output_h",
"The last output value of the hidden. It has shape "
"`[num_directions, batch_size, hidden_size]`.", "T")
.TypeConstraint("T", { "tensor(float16)", "tensor(float)", "tensor(double)" },
"Constrain input and output types to float tensors.")
.TypeConstraint("T1", { "tensor(int32)" }, "Constrain seq_lens to integer tensor.");
OPERATOR_SCHEMA(LSTM)
.NumInputs(3, 8)
.NumOutputs(1, 2)
.SetDoc(R"DOC(
Computes an one-layer LSTM. This operator is usually supported via some
custom implementation such as CuDNN.
Notations:
`X` - input tensor
`i` - input gate
`o` - output gate
`f` - forget gate
`c` - cell gate
`t` - time step (t-1 means previous time step)
`W[iofc]` - W parameter weight matrix for input, output, forget, and cell gates
`R[iofc]` - R recurrence weight matrix for input, output, forget, and cell gates
`Wb[iofc]` - W bias vectors for input, output, forget, and cell gates
`Rb[iofc]` - R bias vectors for input, output, forget, and cell gates
`P[iof]` - P peephole weight matrix for input, output, and forget gates
`WB[iofc]` - W parameter weight matrix for backward input, output, forget, and cell gates
`RB[iofc]` - R recurrence weight matrix for backward input, output, forget, and cell gates
`WBb[iofc]` - W bias vectors for backward input, output, forget, and cell gates
`RBb[iofc]` - R bias vectors for backward input, output, forget, and cell gates
`PB[iof]` - P peephole weight matrix for backward input, output, and forget gates
`tanh(X)` - hyperbolic tangent of X
`sigmoid(X)` - 1 / (1 + e^-X)
`H` - Hidden state
`num_directions` - 2 if direction == bidirectional else 1
Equations (forward LSTM with default activations and peepholes):
- it = sigmoid(Wi*Xt + Ri*Ht-1 + Pi (.) Ct-1 + Wbi + Rbi)
- ft = sigmoid(Wf*Xt + Rf*Ht-1 + Pf (.) Ct-1 + Wbf + Rbf)
- ct = tanh(Wc*Xt + Rc*Ht-1 + Wbc + Rbc)
- Ct = ft (.) Ct-1 + it (.) ct
- ot = sigmoid(Wo*Xt + Ro*Ht-1 + Po (.) Ct + Wbo + Rbo)
- H = ot (.) tanh(Ct)
)DOC")
.Attr("activations", "A list of 4 activation functions for input, output, "
"forget, and cell gates. The activation functions must be one of sigmoid "
"and tanh. See the equations for default if not specified.",
AttrType::STRINGS)
.Attr("hidden_size", "Number of neurons in the hidden layer", AttrType::INT)
.Attr("direction", "Specify if RNN is forward, reverse, or bidirectional. "
"Must be one of forward (default), reverse, or bidirectional.",
AttrType::STRING)
.Attr("input_forget", "Couple the input and forget gates if 1, default 0.",
AttrType::INT)
.Attr("clip", "Cell clip threshold. Clipping bounds the elements of a tensor "
"in the range of [-threshold, +threshold] and is applied to the input "
"of activations. No clip if not specified.",
AttrType::FLOAT)
.Input(0, "input",
"The input sequences packed (and potentially padded) into one 3-D "
"tensor with the shape of `[seq_length, batch_size, input_size]`.")
.Input(1, "W",
"The weight tensor for the gates. Concatenation of `W[iofc]` and "
"`WB[iofc]` (if bidirectional) along dimension 0. The tensor has shape "
"`[num_directions, 4*hidden_size, input_size]`.", "T")
.Input(2, "R",
"The recurrence weight tensor. Concatenation of `R[iofc]` and "
"`RB[iofc]` (if bidirectional) along dimension 0. This tensor has shape "
"`[num_directions, 4*hidden_size, hidden_size}`.", "T")
.Input(3, "B",
"The bias tensor for input gate. Concatenation of `[Wb[iofc], Rb[iofc]]`, "
"and `[WBb[iofc], RBb[iofc]]` (if bidirectional) along dimension 0. This "
"tensor has shape `[num_directions, 8*hidden_size]`. Optional: If not "
"specified - assumed to be 0.", "T",
true /*optional*/)
.Input(4, "P",
"The weight tensor for peepholes. Concatenation of `P[iof]` and "
"`PB[iof]` (if bidirectional) along dimension 0. It has shape "
"`[num_directions, 3*hidde_size, hidden_size]`. Optional: If not specified - "
"assumed to be 0.", "T",
true /*optional*/)
.Input(5, "initial_h",
"Optional initial value of the hidden. If not specified - assumed "
"to be 0. It has shape `[num_directions, batch_size, hidden_size]`.",
"T", true /*optional*/)
.Input(6, "initial_c",
"Optional initial value of the cell. If not specified - assumed "
"to be 0. It has shape `[num_directions, batch_size, hidden_size]`.",
"T", true /*optional*/)
.Input(7, "seq_lens",
"Optional tensor specifying lengths of the sequences in a batch. "
"If not specified - assumed all sequences in the batch to have "
"length `seq_length`. It has shape `[batch_size]`.", "T1",
true /*optional*/)
.Output(0, "output",
"A tensor that concats all the intermediate output values of the hidden."
"It has shape `[seq_length, num_directions, batch_size, hidden_size]`.",
"T")
.Output(1, "output_h",
"The last output value of the hidden. It has shape "
"`[num_directions, batch_size, hidden_size]`.", "T")
.TypeConstraint("T", { "tensor(float16)", "tensor(float)", "tensor(double)" },
"Constrain input and output types to float tensors.")
.TypeConstraint("T1", { "tensor(int32)" }, "Constrain seq_lens to integer tensor.");
<commit_msg>Updates<commit_after>// Copyright (c) Facebook Inc. and Microsoft Corporation.
// Licensed under the MIT license.
#include "onnx/defs/schema.h"
using AttrType = onnx::OpSchema::AttrType;
using namespace onnx;
OPERATOR_SCHEMA(SimpleRNN)
.NumInputs(3, 6)
.NumOutputs(1, 2)
.SetDoc(R"DOC(
Computes an one-layer simple RNN. This operator is usually supported
via some custom implementation such as CuDNN.
Notations:
`X` - input tensor
`i` - input gate
`t` - time step (t-1 means previous time step)
`Wi` - W parameter weight matrix for input gate
`Ri` - R recurrence weight matrix for input gate
`Wbi` - W parameter bias vector for input gate
`Rbi` - R parameter bias vector for input gate
`WBi` - W parameter weight matrix for backward input gate
`RBi` - R recurrence weight matrix for backward input gate
`WBbi` - WR bias vectors for backward input gate
`RBbi` - RR bias vectors for backward input gate
`ReLU(X)` - max(X, 0)
`tanh(X)` - hyperbolic tangent of X
`H` - Hidden state
`num_directions` - 2 if direction == bidirectional else 1
Equations:
- Ht = Activation(Wi*Xt + Ri*Ht-1 + Wbi + Rbi)
)DOC")
.Attr("activation", "The activation function for input gate. It must be "
"one of tanh and ReLU. Default `tanh`.",
AttrType::STRING)
.Attr("hidden_size", "Number of neurons in the hidden layer", AttrType::INT)
.Attr("direction", "Specify if the RNN is forward, reverse, or bidirectional. "
"Must be one of forward (default), reverse, or bidirectional.",
AttrType::STRING)
.Attr("clip", "Cell clip threshold. Clipping bounds the elements of a tensor "
"in the range of [-threshold, +threshold] and is applied to the input "
"of activations. No clip if not specified.",
AttrType::FLOAT)
.Input(0, "input",
"The input sequences packed (and potentially padded) into one 3-D "
"tensor with the shape of `[seq_length, batch_size, input_size]`.", "T")
.Input(1, "W",
"The weight tensor for input gate. Concatenation of `Wi` and `WBi` "
"(if bidirectional). The tensor has shape "
"`num_directions, hidden_size, input_size]`.", "T")
.Input(2, "R",
"The recurrence weight tensor. Concatenation of `Ri` and `RBi` "
"(if bidirectional). The tensor has shape "
"`[num_directions, hidden_size, hidden_size}`.", "T")
.Input(3, "B",
"The bias tensor for input gate. Concatenation of `[Wbi, Rbi]`, "
"and `[WBbi, RBbi]` (if bidirectional). The tensor has shape "
"`[num_directions, 2*hidden_size]`, Optional: If not specified - assumed "
"to be 0.", "T",
true /*optional*/)
.Input(4, "initial_h",
"Optional initial value of the hidden. If not specified - assumed "
"to be 0. It has shape either `[num_directions, batch_size, hidden_size]`.",
"T", true /*optional*/)
.Input(5, "seq_lens",
"Optional tensor specifying lengths of the sequences in a batch. "
"If not specified - assumed all sequences in the batch to have "
"length `seq_length`. It has shape `[batch_size]`.", "T1",
true /*optional*/)
.Output(0, "output",
"A tensor that concats all the intermediate output values of the hidden."
"It has shape `[seq_length, num_directions, batch_size, hidden_size]`.", "T")
.Output(1, "output_h",
"The last output value of the hidden. It has shape "
"`[num_directions, batch_size, hidden_size]`.", "T")
.TypeConstraint("T", { "tensor(float16)", "tensor(float)", "tensor(double)" },
"Constrain input and output types to float tensors.")
.TypeConstraint("T1", { "tensor(int32)" }, "Constrain seq_lens to integer tensor.");
OPERATOR_SCHEMA(GRU)
.NumInputs(3, 6)
.NumOutputs(1, 2)
.SetDoc(R"DOC(
Computes an one-layer GRU. This operator is usually supported via some custom
implementation such as CuDNN.
Notations:
`X` - input tensor
`z` - update gate
`r` - reset gate
`h` - hidden gate
`t` - time step (t-1 means previous time step)
`W[zrh]` - W parameter weight matrix for update, reset, and hidden gates
`R[zrh]` - R recurrence weight matrix for update, reset, and hidden gates
`Wb[zrh]` - W bias vectors for update, reset, and hidden gates
`Rb[zrh]` - R bias vectors for update, reset, and hidden gates
`WB[zrh]` - W parameter weight matrix for backward update, reset, and hidden gates
`RB[zrh]` - R recurrence weight matrix for backward update, reset, and hidden gates
`WBb[zrh]` - W bias vectors for backward update, reset, and hidden gates
`RBb[zrh]` - R bias vectors for backward update, reset, and hidden gates
`tanh(X)` - hyperbolic tangent of X
`sigmoid(X)` - 1 / (1 + e^-X)
`H` - Hidden state
`num_directions` - 2 if direction == bidirectional else 1
Equations (GRU with default activations):
- zt = sigmoid(Wz*Xt + Rz*Ht-1 + Wbz + Rbz)
- rt = sigmoid(Wr*Xt + Rr*Ht-1 + Wbr + Rbr)
- ht = tanh(Wh*Xt + rt*(Rh*Ht-1 + Rbh) + Wbh)
- H = (1 - zt) (.) ht + it (.) Ht-1
)DOC")
.Attr("activations", "A list of 3 activation functions for update, reset, and "
"hidden gates. The activation functions must be one of sigmoid and tanh. "
"See the equations for default if not specified.",
AttrType::STRINGS)
.Attr("hidden_size", "Number of neurons in the hidden layer", AttrType::INT)
.Attr("direction", "Specify if the RNN is forward, reverse, or bidirectional. "
"Must be one of forward (default), reverse, or bidirectional.",
AttrType::STRING)
.Attr("clip", "Cell clip threshold. Clipping bounds the elements of a tensor "
"in the range of [-threshold, +threshold] and is applied to the input "
"of activations. No clip if not specified.",
AttrType::FLOAT)
.Input(0, "input",
"The input sequences packed (and potentially padded) into one 3-D "
"tensor with the shape of `[seq_length, batch_size, input_size]`.", "T")
.Input(1, "W",
"The weight tensor for the gates. Concatenation of `W[zrh]` and `WB[zrh]` "
"(if bidirectional) along dimension 0. This tensor has shape "
"`[num_directions, 3*hidden_size, input_size]`.", "T")
.Input(2, "R",
"The recurrence weight tensor. Concatenation of `R[zrh]` and `RB[zrh]` "
"(if bidirectional) along dimension 0. This tensor has shape "
"`[num_directions, 3*hidden_size, hidden_size}`.", "T")
.Input(3, "B",
"The bias tensor for the gates. Concatenation of `[Wb[zrh], Rb[zrh]]` and "
"`[WBb[zrh], RBb[zrh]]` (if bidirectional) along dimension 0. This tensor "
"has shape `[num_directions, 6*hidden_size]`. Optional: If not specified "
"- assumed to be 0", "T",
true /*optional*/)
.Input(4, "initial_h",
"Optional initial value of the hidden. If not specified - assumed "
"to be 0. It has shape `[num_directions, batch_size, hidden_size]`.",
"T", true /*optional*/)
.Input(5, "seq_lens",
"Optional tensor specifying lengths of the sequences in a batch. "
"If not specified - assumed all sequences in the batch to have "
"length `seq_length`. It has shape `[batch_size]`.",
"T1", true /*optional*/)
.Output(0, "output",
"A tensor that concats all the intermediate output values of the "
"hidden. It has shape `[seq_length, num_directions, batch_size, hidden_size]`.",
"T")
.Output(1, "output_h",
"The last output value of the hidden. It has shape "
"`[num_directions, batch_size, hidden_size]`.", "T")
.TypeConstraint("T", { "tensor(float16)", "tensor(float)", "tensor(double)" },
"Constrain input and output types to float tensors.")
.TypeConstraint("T1", { "tensor(int32)" }, "Constrain seq_lens to integer tensor.");
OPERATOR_SCHEMA(LSTM)
.NumInputs(3, 8)
.NumOutputs(1, 2)
.SetDoc(R"DOC(
Computes an one-layer LSTM. This operator is usually supported via some
custom implementation such as CuDNN.
Notations:
`X` - input tensor
`i` - input gate
`o` - output gate
`f` - forget gate
`c` - cell gate
`t` - time step (t-1 means previous time step)
`W[iofc]` - W parameter weight matrix for input, output, forget, and cell gates
`R[iofc]` - R recurrence weight matrix for input, output, forget, and cell gates
`Wb[iofc]` - W bias vectors for input, output, forget, and cell gates
`Rb[iofc]` - R bias vectors for input, output, forget, and cell gates
`P[iof]` - P peephole weight matrix for input, output, and forget gates
`WB[iofc]` - W parameter weight matrix for backward input, output, forget, and cell gates
`RB[iofc]` - R recurrence weight matrix for backward input, output, forget, and cell gates
`WBb[iofc]` - W bias vectors for backward input, output, forget, and cell gates
`RBb[iofc]` - R bias vectors for backward input, output, forget, and cell gates
`PB[iof]` - P peephole weight matrix for backward input, output, and forget gates
`tanh(X)` - hyperbolic tangent of X
`sigmoid(X)` - 1 / (1 + e^-X)
`H` - Hidden state
`num_directions` - 2 if direction == bidirectional else 1
Equations (forward LSTM with default activations and peepholes):
- it = sigmoid(Wi*Xt + Ri*Ht-1 + Pi (.) Ct-1 + Wbi + Rbi)
- ft = sigmoid(Wf*Xt + Rf*Ht-1 + Pf (.) Ct-1 + Wbf + Rbf)
- ct = tanh(Wc*Xt + Rc*Ht-1 + Wbc + Rbc)
- Ct = ft (.) Ct-1 + it (.) ct
- ot = sigmoid(Wo*Xt + Ro*Ht-1 + Po (.) Ct + Wbo + Rbo)
- H = ot (.) tanh(Ct)
)DOC")
.Attr("activations", "A list of 4 activation functions for input, output, "
"forget, and cell gates. The activation functions must be one of sigmoid "
"and tanh. See the equations for default if not specified.",
AttrType::STRINGS)
.Attr("hidden_size", "Number of neurons in the hidden layer", AttrType::INT)
.Attr("direction", "Specify if RNN is forward, reverse, or bidirectional. "
"Must be one of forward (default), reverse, or bidirectional.",
AttrType::STRING)
.Attr("input_forget", "Couple the input and forget gates if 1, default 0.",
AttrType::INT)
.Attr("clip", "Cell clip threshold. Clipping bounds the elements of a tensor "
"in the range of [-threshold, +threshold] and is applied to the input "
"of activations. No clip if not specified.",
AttrType::FLOAT)
.Input(0, "input",
"The input sequences packed (and potentially padded) into one 3-D "
"tensor with the shape of `[seq_length, batch_size, input_size]`.", "T")
.Input(1, "W",
"The weight tensor for the gates. Concatenation of `W[iofc]` and "
"`WB[iofc]` (if bidirectional) along dimension 0. The tensor has shape "
"`[num_directions, 4*hidden_size, input_size]`.", "T")
.Input(2, "R",
"The recurrence weight tensor. Concatenation of `R[iofc]` and "
"`RB[iofc]` (if bidirectional) along dimension 0. This tensor has shape "
"`[num_directions, 4*hidden_size, hidden_size}`.", "T")
.Input(3, "B",
"The bias tensor for input gate. Concatenation of `[Wb[iofc], Rb[iofc]]`, "
"and `[WBb[iofc], RBb[iofc]]` (if bidirectional) along dimension 0. This "
"tensor has shape `[num_directions, 8*hidden_size]`. Optional: If not "
"specified - assumed to be 0.", "T",
true /*optional*/)
.Input(4, "P",
"The weight tensor for peepholes. Concatenation of `P[iof]` and "
"`PB[iof]` (if bidirectional) along dimension 0. It has shape "
"`[num_directions, 3*hidde_size, hidden_size]`. Optional: If not specified - "
"assumed to be 0.", "T",
true /*optional*/)
.Input(5, "initial_h",
"Optional initial value of the hidden. If not specified - assumed "
"to be 0. It has shape `[num_directions, batch_size, hidden_size]`.",
"T", true /*optional*/)
.Input(6, "initial_c",
"Optional initial value of the cell. If not specified - assumed "
"to be 0. It has shape `[num_directions, batch_size, hidden_size]`.",
"T", true /*optional*/)
.Input(7, "seq_lens",
"Optional tensor specifying lengths of the sequences in a batch. "
"If not specified - assumed all sequences in the batch to have "
"length `seq_length`. It has shape `[batch_size]`.", "T1",
true /*optional*/)
.Output(0, "output",
"A tensor that concats all the intermediate output values of the hidden."
"It has shape `[seq_length, num_directions, batch_size, hidden_size]`.",
"T")
.Output(1, "output_h",
"The last output value of the hidden. It has shape "
"`[num_directions, batch_size, hidden_size]`.", "T")
.TypeConstraint("T", { "tensor(float16)", "tensor(float)", "tensor(double)" },
"Constrain input and output types to float tensors.")
.TypeConstraint("T1", { "tensor(int32)" }, "Constrain seq_lens to integer tensor.");
<|endoftext|> |
<commit_before>//------------------------------------------------------------------------------
//
// Name: add.cpp
//
// Purpose: Atomic summation, inspired by:
// http://simpleopencl.blogspot.com/2013/04/performance-of-atomics-atomics-in.html
//
// HISTORY: Written by Tim Mattson, June 2011
// Ported to C++ Wrapper API by Benedict Gaster, September 2011
// Updated to C++ Wrapper API v1.2 by Tom Deakin and Simon McIntosh-Smith, October 2012
// Updated to C++ Wrapper v1.2.6 by Tom Deakin, August 2013
// Rewritten to a different purpose altogther by Jeff Hammond, October 2016
//
//------------------------------------------------------------------------------
#define __CL_ENABLE_EXCEPTIONS
#include <iostream>
#include <fstream>
#include "cl.hpp"
#include "util.hpp"
// pick up device type from compiler command line or from the default type
#ifndef DEVICE
#define DEVICE CL_DEVICE_TYPE_DEFAULT
#endif
int main(int argc, char* argv[])
{
try {
cl::Context context(DEVICE);
cl::Program program(context, util::loadProgram("add.cl"), /* build= */ true);
cl::CommandQueue queue(context);
// create host and device data
int sum=0;
auto bufferSum = cl::Buffer(context, CL_MEM_READ_WRITE, 1 * sizeof(int));
// copy host-to-device
queue.enqueueWriteBuffer(bufferSum, CL_TRUE, 0, 1 * sizeof(int), &sum);
auto kernel=cl::Kernel(program, "AtomicSum");
// bind device buffer to first argument in kernel invocation
kernel.setArg(0,bufferSum);
// run the kernel
queue.enqueueNDRangeKernel(kernel, cl::NullRange, cl::NDRange(1024*1024*128), cl::NullRange);
queue.finish();
// copy device-to-host
queue.enqueueReadBuffer(bufferSum,CL_TRUE,0,1 * sizeof(int),&sum);
std::cout << "Sum: " << sum << std::endl;
}
catch (cl::Error err) {
std::cout << "Exception\n";
std::cerr << "ERROR: " << err.what() << std::endl;
}
return 0;
}
<commit_msg>add verification<commit_after>//------------------------------------------------------------------------------
//
// Name: add.cpp
//
// Purpose: Atomic summation, inspired by:
// http://simpleopencl.blogspot.com/2013/04/performance-of-atomics-atomics-in.html
//
// HISTORY: Written by Tim Mattson, June 2011
// Ported to C++ Wrapper API by Benedict Gaster, September 2011
// Updated to C++ Wrapper API v1.2 by Tom Deakin and Simon McIntosh-Smith, October 2012
// Updated to C++ Wrapper v1.2.6 by Tom Deakin, August 2013
// Rewritten to a different purpose altogther by Jeff Hammond, October 2016
//
//------------------------------------------------------------------------------
#define __CL_ENABLE_EXCEPTIONS
#include <iostream>
#include <fstream>
#include "cl.hpp"
#include "util.hpp"
// pick up device type from compiler command line or from the default type
#ifndef DEVICE
#define DEVICE CL_DEVICE_TYPE_DEFAULT
#endif
const auto range = 1024*1024*128;
int main(int argc, char* argv[])
{
try {
cl::Context context(DEVICE);
cl::Program program(context, util::loadProgram("add.cl"), /* build= */ true);
cl::CommandQueue queue(context);
// create host and device data
int sum=0;
auto bufferSum = cl::Buffer(context, CL_MEM_READ_WRITE, 1 * sizeof(int));
// copy host-to-device
queue.enqueueWriteBuffer(bufferSum, CL_TRUE, 0, 1 * sizeof(int), &sum);
auto kernel=cl::Kernel(program, "AtomicSum");
// bind device buffer to first argument in kernel invocation
kernel.setArg(0,bufferSum);
// run the kernel
queue.enqueueNDRangeKernel(kernel, cl::NullRange, cl::NDRange(range), cl::NullRange);
queue.finish();
// copy device-to-host
queue.enqueueReadBuffer(bufferSum,CL_TRUE,0,1 * sizeof(int),&sum);
std::cout << "Sum: " << sum << " (should be " << range << ")" << std::endl;
}
catch (cl::Error err) {
std::cout << "Exception\n";
std::cerr << "ERROR: " << err.what() << std::endl;
}
return 0;
}
<|endoftext|> |
<commit_before>/*
kopeteidentity.cpp - Kopete Identity
Copyright (c) 2007 by Gustavo Pichorim Boiko <[email protected]>
(c) 2007 Will Stephenson <[email protected]>
Kopete (c) 2002-2007 by the Kopete developers <[email protected]>
*************************************************************************
* *
* 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 of the License, or (at your option) any later version. *
* *
*************************************************************************
*/
#include "kopetepropertycontainer.h"
#include "kopeteidentity.h"
#include "kopeteaccount.h"
#include "kopetecontact.h"
#include "kopeteprotocol.h"
#include <QStringList>
#include <KDebug>
#include <KConfigGroup>
#include <KGlobal>
#include <KSharedConfigPtr>
#include <KLocale>
#include <KRandom>
#include <KMenu>
#include <kdeversion.h>
namespace Kopete
{
class Identity::Private
{
public:
Private(const QString &i, const QString &l) : onlineStatus( OnlineStatus::Unknown )
{
id = i;
label = l;
configGroup = new KConfigGroup(KGlobal::config(), QString::fromLatin1( "Identity_%1" ).arg( id ));
}
QList<Kopete::Account*> accounts;
QString id;
QString label;
KConfigGroup *configGroup;
OnlineStatus::StatusType onlineStatus;
QString statusMessage;
};
Identity::Identity( const QString &id, const QString &label )
: d( new Private(id, label) )
{
load();
connect(this, SIGNAL(propertyChanged(Kopete::PropertyContainer*, const QString&, const QVariant &, const QVariant &)),
this, SLOT(slotSaveProperty(Kopete::PropertyContainer*, const QString&, const QVariant &, const QVariant &)));
}
Identity::Identity(const QString &label)
: d( new Private(KRandom::randomString(10), label) )
{
connect(this, SIGNAL(propertyChanged(Kopete::PropertyContainer*, const QString&, const QVariant &, const QVariant &)),
this, SLOT(slotSaveProperty(Kopete::PropertyContainer*, const QString&, const QVariant &, const QVariant &)));
}
Identity * Identity::clone() const
{
Identity * id = new Identity( label() );
QMap<QString,QString> props;
serializeProperties( props );
id->deserializeProperties( props );
connect(id, SIGNAL(propertyChanged(Kopete::PropertyContainer*, const QString&, const QVariant &, const QVariant &)),
id, SLOT(slotSaveProperty(Kopete::PropertyContainer*, const QString&, const QVariant &, const QVariant &)));
return id;
}
Identity::~Identity()
{
emit identityDestroyed(this);
delete d->configGroup;
delete d;
}
QString Identity::id() const
{
return d->id;
}
QString Identity::label() const
{
return d->label;
}
void Identity::setLabel(const QString& label)
{
d->label = label;
}
bool Identity::excludeConnect() const
{
//TODO implement
return false;
}
void Identity::setOnlineStatus( uint category, const QString &awayMessage )
{
OnlineStatusManager::Categories katgor=(OnlineStatusManager::Categories)category;
d->statusMessage = awayMessage;
foreach( Account *account , d->accounts )
{
Kopete::OnlineStatus status = OnlineStatusManager::self()->onlineStatus(account->protocol() , katgor);
if ( !account->excludeConnect() )
account->setOnlineStatus( status , awayMessage );
}
}
OnlineStatus::StatusType Identity::onlineStatus() const
{
return d->onlineStatus;
}
QString Identity::statusMessage() const
{
return d->statusMessage;
}
QString Identity::toolTip() const
{
QString tt = QLatin1String("<qt>");
QString nick;
if ( hasProperty(Kopete::Global::Properties::self()->nickName().key()) )
nick = property(Kopete::Global::Properties::self()->nickName()).value().toString();
else
nick = d->label;
tt+= i18nc( "Identity tooltip information: <nobr>ICON <b>NAME</b></nobr><br /><br />",
"<nobr><img src=\"kopete-identity-icon:%1\"> <b>%2</b></nobr><br /><br />",
QString(QUrl::toPercentEncoding( d->label )), nick );
foreach(Account *a, d->accounts)
{
Kopete::Contact *self = a->myself();
QString onlineStatus = self ? self->onlineStatus().description() : i18n("Offline");
tt += i18nc( "Account tooltip information: <nobr>ICON <b>PROTOCOL:</b> NAME (<i>STATUS</i>)</nobr><br />",
"<nobr><img src=\"kopete-account-icon:%3:%4\"> <b>%1:</b> %2 (<i>%5</i>)</nobr><br />",
a->protocol()->displayName(), a->accountLabel(), QString(QUrl::toPercentEncoding( a->protocol()->pluginId() )),
QString(QUrl::toPercentEncoding( a->accountId() )), onlineStatus );
}
tt += QLatin1String("</qt>");
return tt;
}
QString Identity::customIcon() const
{
//TODO implement
return "user";
}
QList<Account*> Identity::accounts() const
{
return d->accounts;
}
void Identity::addAccount( Kopete::Account *account )
{
// check if we already have this account
if ( d->accounts.indexOf( account ) != -1 )
return;
d->accounts.append( account );
connect( account->myself(),
SIGNAL(onlineStatusChanged(Kopete::Contact *, const Kopete::OnlineStatus &, const Kopete::OnlineStatus &)),
this, SLOT(updateOnlineStatus()));
connect(account, SIGNAL(accountDestroyed(const Kopete::Account*)),
this, SLOT(removeAccount(const Kopete::Account*)));
updateOnlineStatus();
emit identityChanged( this );
}
void Identity::removeAccount( const Kopete::Account *account )
{
Kopete::Account *a = const_cast<Kopete::Account*>(account);
if ( !d->accounts.contains( a ) )
return;
disconnect( account );
d->accounts.removeAll( a );
updateOnlineStatus();
emit identityChanged( this );
}
KConfigGroup *Identity::configGroup() const
{
return d->configGroup;
}
void Identity::load()
{
QMap<QString,QString>::iterator it;
QMap<QString,QString> props = d->configGroup->entryMap();
deserializeProperties(props);
}
void Identity::save()
{
// FIXME: using kconfig for now, but I guess this is going to change
QMap<QString,QString> props;
serializeProperties(props);
QMap<QString,QString>::iterator it;
for (it = props.begin(); it != props.end(); ++it)
{
d->configGroup->writeEntry(it.key(), it.value());
}
}
void Identity::updateOnlineStatus()
{
Kopete::OnlineStatus mostSignificantStatus;
Kopete::OnlineStatus::StatusType newStatus = Kopete::OnlineStatus::Unknown;
foreach(Account *account, d->accounts)
{
// find most significant status
if ( account->myself() &&
account->myself()->onlineStatus() > mostSignificantStatus )
mostSignificantStatus = account->myself()->onlineStatus();
}
newStatus = mostSignificantStatus.status();
if( newStatus != d->onlineStatus )
{
d->onlineStatus = newStatus;
emit onlineStatusChanged( this );
}
}
void Identity::slotSaveProperty( Kopete::PropertyContainer *container, const QString &key,
const QVariant &oldValue, const QVariant &newValue )
{
save();
}
} //END namespace Kopete
#include "kopeteidentity.moc"
// vim: set noet ts=4 sts=4 sw=4:
<commit_msg>BUG:152609 Implement Identity::customIcon()<commit_after>/*
kopeteidentity.cpp - Kopete Identity
Copyright (c) 2007 by Gustavo Pichorim Boiko <[email protected]>
(c) 2007 Will Stephenson <[email protected]>
Kopete (c) 2002-2007 by the Kopete developers <[email protected]>
*************************************************************************
* *
* 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 of the License, or (at your option) any later version. *
* *
*************************************************************************
*/
#include "kopetepropertycontainer.h"
#include "kopeteidentity.h"
#include "kopeteaccount.h"
#include "kopetecontact.h"
#include "kopeteprotocol.h"
#include <QStringList>
#include <KDebug>
#include <KConfigGroup>
#include <KGlobal>
#include <KSharedConfigPtr>
#include <KLocale>
#include <KRandom>
#include <KMenu>
#include <kdeversion.h>
namespace Kopete
{
class Identity::Private
{
public:
Private(const QString &i, const QString &l) : onlineStatus( OnlineStatus::Unknown )
{
id = i;
label = l;
configGroup = new KConfigGroup(KGlobal::config(), QString::fromLatin1( "Identity_%1" ).arg( id ));
}
QList<Kopete::Account*> accounts;
QString id;
QString label;
KConfigGroup *configGroup;
OnlineStatus::StatusType onlineStatus;
QString statusMessage;
};
Identity::Identity( const QString &id, const QString &label )
: d( new Private(id, label) )
{
load();
connect(this, SIGNAL(propertyChanged(Kopete::PropertyContainer*, const QString&, const QVariant &, const QVariant &)),
this, SLOT(slotSaveProperty(Kopete::PropertyContainer*, const QString&, const QVariant &, const QVariant &)));
}
Identity::Identity(const QString &label)
: d( new Private(KRandom::randomString(10), label) )
{
connect(this, SIGNAL(propertyChanged(Kopete::PropertyContainer*, const QString&, const QVariant &, const QVariant &)),
this, SLOT(slotSaveProperty(Kopete::PropertyContainer*, const QString&, const QVariant &, const QVariant &)));
}
Identity * Identity::clone() const
{
Identity * id = new Identity( label() );
QMap<QString,QString> props;
serializeProperties( props );
id->deserializeProperties( props );
connect(id, SIGNAL(propertyChanged(Kopete::PropertyContainer*, const QString&, const QVariant &, const QVariant &)),
id, SLOT(slotSaveProperty(Kopete::PropertyContainer*, const QString&, const QVariant &, const QVariant &)));
return id;
}
Identity::~Identity()
{
emit identityDestroyed(this);
delete d->configGroup;
delete d;
}
QString Identity::id() const
{
return d->id;
}
QString Identity::label() const
{
return d->label;
}
void Identity::setLabel(const QString& label)
{
d->label = label;
}
bool Identity::excludeConnect() const
{
//TODO implement
return false;
}
void Identity::setOnlineStatus( uint category, const QString &awayMessage )
{
OnlineStatusManager::Categories katgor=(OnlineStatusManager::Categories)category;
d->statusMessage = awayMessage;
foreach( Account *account , d->accounts )
{
Kopete::OnlineStatus status = OnlineStatusManager::self()->onlineStatus(account->protocol() , katgor);
if ( !account->excludeConnect() )
account->setOnlineStatus( status , awayMessage );
}
}
OnlineStatus::StatusType Identity::onlineStatus() const
{
return d->onlineStatus;
}
QString Identity::statusMessage() const
{
return d->statusMessage;
}
QString Identity::toolTip() const
{
QString tt = QLatin1String("<qt>");
QString nick;
if ( hasProperty(Kopete::Global::Properties::self()->nickName().key()) )
nick = property(Kopete::Global::Properties::self()->nickName()).value().toString();
else
nick = d->label;
tt+= i18nc( "Identity tooltip information: <nobr>ICON <b>NAME</b></nobr><br /><br />",
"<nobr><img src=\"kopete-identity-icon:%1\"> <b>%2</b></nobr><br /><br />",
QString(QUrl::toPercentEncoding( d->label )), nick );
foreach(Account *a, d->accounts)
{
Kopete::Contact *self = a->myself();
QString onlineStatus = self ? self->onlineStatus().description() : i18n("Offline");
tt += i18nc( "Account tooltip information: <nobr>ICON <b>PROTOCOL:</b> NAME (<i>STATUS</i>)</nobr><br />",
"<nobr><img src=\"kopete-account-icon:%3:%4\"> <b>%1:</b> %2 (<i>%5</i>)</nobr><br />",
a->protocol()->displayName(), a->accountLabel(), QString(QUrl::toPercentEncoding( a->protocol()->pluginId() )),
QString(QUrl::toPercentEncoding( a->accountId() )), onlineStatus );
}
tt += QLatin1String("</qt>");
return tt;
}
QString Identity::customIcon() const
{
if (hasProperty( Kopete::Global::Properties::self()->photo().key() ))
return property(Kopete::Global::Properties::self()->photo()).value().toString();
else
return "user";
}
QList<Account*> Identity::accounts() const
{
return d->accounts;
}
void Identity::addAccount( Kopete::Account *account )
{
// check if we already have this account
if ( d->accounts.indexOf( account ) != -1 )
return;
d->accounts.append( account );
connect( account->myself(),
SIGNAL(onlineStatusChanged(Kopete::Contact *, const Kopete::OnlineStatus &, const Kopete::OnlineStatus &)),
this, SLOT(updateOnlineStatus()));
connect(account, SIGNAL(accountDestroyed(const Kopete::Account*)),
this, SLOT(removeAccount(const Kopete::Account*)));
updateOnlineStatus();
emit identityChanged( this );
}
void Identity::removeAccount( const Kopete::Account *account )
{
Kopete::Account *a = const_cast<Kopete::Account*>(account);
if ( !d->accounts.contains( a ) )
return;
disconnect( account );
d->accounts.removeAll( a );
updateOnlineStatus();
emit identityChanged( this );
}
KConfigGroup *Identity::configGroup() const
{
return d->configGroup;
}
void Identity::load()
{
QMap<QString,QString>::iterator it;
QMap<QString,QString> props = d->configGroup->entryMap();
deserializeProperties(props);
}
void Identity::save()
{
// FIXME: using kconfig for now, but I guess this is going to change
QMap<QString,QString> props;
serializeProperties(props);
QMap<QString,QString>::iterator it;
for (it = props.begin(); it != props.end(); ++it)
{
d->configGroup->writeEntry(it.key(), it.value());
}
}
void Identity::updateOnlineStatus()
{
Kopete::OnlineStatus mostSignificantStatus;
Kopete::OnlineStatus::StatusType newStatus = Kopete::OnlineStatus::Unknown;
foreach(Account *account, d->accounts)
{
// find most significant status
if ( account->myself() &&
account->myself()->onlineStatus() > mostSignificantStatus )
mostSignificantStatus = account->myself()->onlineStatus();
}
newStatus = mostSignificantStatus.status();
if( newStatus != d->onlineStatus )
{
d->onlineStatus = newStatus;
emit onlineStatusChanged( this );
}
}
void Identity::slotSaveProperty( Kopete::PropertyContainer *container, const QString &key,
const QVariant &oldValue, const QVariant &newValue )
{
save();
}
} //END namespace Kopete
#include "kopeteidentity.moc"
// vim: set noet ts=4 sts=4 sw=4:
<|endoftext|> |
<commit_before>/*-------------------------------------------------------------------------
*
* FILE
* binarystring.cxx
*
* DESCRIPTION
* implementation of bytea (binary string) conversions
*
* Copyright (c) 2003-2004, Jeroen T. Vermeulen <[email protected]>
*
* See COPYING for copyright license. If you did not receive a file called
* COPYING with this source code, please notify the distributor of this mistake,
* or contact the author.
*
*-------------------------------------------------------------------------
*/
#include "pqxx/compiler.h"
#include <new>
#include <stdexcept>
#include "libpq-fe.h"
#include "pqxx/binarystring"
using namespace PGSTD;
using namespace pqxx::internal;
namespace
{
// Convert textual digit to value
inline char DV(unsigned char d) { return d - '0'; }
}
pqxx::binarystring::binarystring(const result::field &F) :
super(),
m_size(0)
{
unsigned char *p = const_cast<unsigned char *>(
reinterpret_cast<const_iterator>(F.c_str()));
#ifdef PQXX_HAVE_PQUNESCAPEBYTEA
size_t sz = 0;
super::operator=(PQunescapeBytea(p, &sz));
if (!c_ptr()) throw bad_alloc();
m_size = sz;
#else
m_str.reserve(F.size()+1);
for (result::field::size_type i=0; i<F.size(); ++i)
{
unsigned char c = p[i];
if (c == '\\')
{
c = p[++i];
if (isdigit(c) && isdigit(p[i+1]) && isdigit(p[i+2]))
{
c = (DV(p[c])<<9) | (DV(p[i+1])<<3) | DV(p[i+2]);
i += 2;
}
}
m_str += char(c);
}
m_size = m_str.size();
void *buf = malloc(m_size+1);
if (!buf)
throw bad_alloc();
super::operator=(static_cast<unsigned char *>(buf));
strcpy(static_cast<char *>(buf), m_str.c_str());
#endif
}
bool pqxx::binarystring::operator==(const binarystring &rhs) const throw ()
{
if (rhs.size() != size()) return false;
for (size_type i=0; i<size(); ++i) if (rhs[i] != data()[i]) return false;
return true;
}
pqxx::binarystring::const_reference pqxx::binarystring::at(size_type n) const
{
if (n >= m_size)
{
if (!m_size)
throw out_of_range("Accessing empty binarystring");
throw out_of_range("binarystring index out of range: " +
to_string(n) + " (should be below " + to_string(m_size) + ")");
}
return data()[n];
}
void pqxx::binarystring::swap(binarystring &rhs)
{
// This might fail, so do it first
m_str.swap(rhs.m_str);
// PQAlloc<>::swap() is nothrow
super::swap(rhs);
// This part very obviously can't go wrong, so do it last
const size_type s(m_size);
m_size = rhs.m_size;
rhs.m_size = s;
}
const string &pqxx::binarystring::str() const
{
if (m_str.empty() && m_size) m_str = string(c_ptr(), m_size);
return m_str;
}
string pqxx::escape_binary(const unsigned char bin[], size_t len)
{
#ifdef PQXX_HAVE_PQESCAPEBYTEA
size_t escapedlen = 0;
unsigned char *p = const_cast<unsigned char *>(bin);
PQAlloc<unsigned char> A(PQescapeBytea(p, len, &escapedlen));
const char *cstr = reinterpret_cast<const char *>(A.c_ptr());
if (!cstr) throw bad_alloc();
return string(cstr, escapedlen-1);
#else
// TODO: Fails to escape "high" bytes!?
string result;
result.reserve(len);
for (size_t i=0; i<len; ++i)
{
if (bin[i] & 0x80)
{
char buf[8];
sprintf(buf, "\\\\%03o", unsigned(bin[i]));
result += buf;
}
else switch (bin[i])
{
case 0:
result += "\\\\000";
break;
case '\'':
result += "\\'";
break;
case '\\':
result += "\\\\\\\\";
break;
default:
result += char(bin[i]);
}
}
return result;
#endif
}
string pqxx::escape_binary(const unsigned char bin[])
{
return escape_binary(bin, strlen(reinterpret_cast<const char *>(bin)));
}
string pqxx::escape_binary(const char bin[], size_t len)
{
return escape_binary(reinterpret_cast<const unsigned char *>(bin), len);
}
string pqxx::escape_binary(const char bin[])
{
return escape_binary(bin, strlen(bin));
}
string pqxx::escape_binary(const string &bin)
{
return escape_binary(bin.c_str(), bin.size());
}
<commit_msg>Removed unneeded "+1" in string reservation<commit_after>/*-------------------------------------------------------------------------
*
* FILE
* binarystring.cxx
*
* DESCRIPTION
* implementation of bytea (binary string) conversions
*
* Copyright (c) 2003-2004, Jeroen T. Vermeulen <[email protected]>
*
* See COPYING for copyright license. If you did not receive a file called
* COPYING with this source code, please notify the distributor of this mistake,
* or contact the author.
*
*-------------------------------------------------------------------------
*/
#include "pqxx/compiler.h"
#include <new>
#include <stdexcept>
#include "libpq-fe.h"
#include "pqxx/binarystring"
using namespace PGSTD;
using namespace pqxx::internal;
namespace
{
// Convert textual digit to value
inline char DV(unsigned char d) { return d - '0'; }
}
pqxx::binarystring::binarystring(const result::field &F) :
super(),
m_size(0)
{
unsigned char *p = const_cast<unsigned char *>(
reinterpret_cast<const_iterator>(F.c_str()));
#ifdef PQXX_HAVE_PQUNESCAPEBYTEA
size_t sz = 0;
super::operator=(PQunescapeBytea(p, &sz));
if (!c_ptr()) throw bad_alloc();
m_size = sz;
#else
m_str.reserve(F.size());
for (result::field::size_type i=0; i<F.size(); ++i)
{
unsigned char c = p[i];
if (c == '\\')
{
c = p[++i];
if (isdigit(c) && isdigit(p[i+1]) && isdigit(p[i+2]))
{
c = (DV(p[c])<<9) | (DV(p[i+1])<<3) | DV(p[i+2]);
i += 2;
}
}
m_str += char(c);
}
m_size = m_str.size();
void *buf = malloc(m_size+1);
if (!buf)
throw bad_alloc();
super::operator=(static_cast<unsigned char *>(buf));
strcpy(static_cast<char *>(buf), m_str.c_str());
#endif
}
bool pqxx::binarystring::operator==(const binarystring &rhs) const throw ()
{
if (rhs.size() != size()) return false;
for (size_type i=0; i<size(); ++i) if (rhs[i] != data()[i]) return false;
return true;
}
pqxx::binarystring::const_reference pqxx::binarystring::at(size_type n) const
{
if (n >= m_size)
{
if (!m_size)
throw out_of_range("Accessing empty binarystring");
throw out_of_range("binarystring index out of range: " +
to_string(n) + " (should be below " + to_string(m_size) + ")");
}
return data()[n];
}
void pqxx::binarystring::swap(binarystring &rhs)
{
// This might fail, so do it first
m_str.swap(rhs.m_str);
// PQAlloc<>::swap() is nothrow
super::swap(rhs);
// This part very obviously can't go wrong, so do it last
const size_type s(m_size);
m_size = rhs.m_size;
rhs.m_size = s;
}
const string &pqxx::binarystring::str() const
{
if (m_str.empty() && m_size) m_str = string(c_ptr(), m_size);
return m_str;
}
string pqxx::escape_binary(const unsigned char bin[], size_t len)
{
#ifdef PQXX_HAVE_PQESCAPEBYTEA
size_t escapedlen = 0;
unsigned char *p = const_cast<unsigned char *>(bin);
PQAlloc<unsigned char> A(PQescapeBytea(p, len, &escapedlen));
const char *cstr = reinterpret_cast<const char *>(A.c_ptr());
if (!cstr) throw bad_alloc();
return string(cstr, escapedlen-1);
#else
// TODO: Fails to escape "high" bytes!?
string result;
result.reserve(len);
for (size_t i=0; i<len; ++i)
{
if (bin[i] & 0x80)
{
char buf[8];
sprintf(buf, "\\\\%03o", unsigned(bin[i]));
result += buf;
}
else switch (bin[i])
{
case 0:
result += "\\\\000";
break;
case '\'':
result += "\\'";
break;
case '\\':
result += "\\\\\\\\";
break;
default:
result += char(bin[i]);
}
}
return result;
#endif
}
string pqxx::escape_binary(const unsigned char bin[])
{
return escape_binary(bin, strlen(reinterpret_cast<const char *>(bin)));
}
string pqxx::escape_binary(const char bin[], size_t len)
{
return escape_binary(reinterpret_cast<const unsigned char *>(bin), len);
}
string pqxx::escape_binary(const char bin[])
{
return escape_binary(bin, strlen(bin));
}
string pqxx::escape_binary(const string &bin)
{
return escape_binary(bin.c_str(), bin.size());
}
<|endoftext|> |
<commit_before>/*-------------------------------------------------------------------------
*
* FILE
* binarystring.cxx
*
* DESCRIPTION
* implementation of bytea (binary string) conversions
*
* Copyright (c) 2003-2004, Jeroen T. Vermeulen <[email protected]>
*
* See COPYING for copyright license. If you did not receive a file called
* COPYING with this source code, please notify the distributor of this mistake,
* or contact the author.
*
*-------------------------------------------------------------------------
*/
#include "pqxx/compiler.h"
#include <new>
#include <stdexcept>
#include "pqxx/binarystring"
using namespace PGSTD;
using namespace pqxx::internal;
using namespace pqxx::internal::pq;
namespace
{
// Convert textual digit to value
inline char DV(unsigned char d) { return d - '0'; }
}
pqxx::binarystring::binarystring(const result::field &F) :
super(),
m_size(0)
{
unsigned char *p = const_cast<unsigned char *>(
reinterpret_cast<const_iterator>(F.c_str()));
#ifdef PQXX_HAVE_PQUNESCAPEBYTEA
size_t sz = 0;
super::operator=(PQunescapeBytea(p, &sz));
if (!c_ptr()) throw bad_alloc();
m_size = sz;
#else
m_str.reserve(F.size());
for (result::field::size_type i=0; i<F.size(); ++i)
{
unsigned char c = p[i];
if (c == '\\')
{
c = p[++i];
if (isdigit(c) && isdigit(p[i+1]) && isdigit(p[i+2]))
{
c = (DV(p[c])<<9) | (DV(p[i+1])<<3) | DV(p[i+2]);
i += 2;
}
}
m_str += char(c);
}
m_size = m_str.size();
void *buf = malloc(m_size+1);
if (!buf)
throw bad_alloc();
super::operator=(static_cast<unsigned char *>(buf));
strcpy(static_cast<char *>(buf), m_str.c_str());
#endif
}
pqxx::binarystring::const_reference pqxx::binarystring::at(size_type n) const
{
if (n >= m_size)
{
if (!m_size)
throw out_of_range("Accessing empty binarystring");
throw out_of_range("binarystring index out of range: " +
to_string(n) + " (should be below " + to_string(m_size) + ")");
}
return data()[n];
}
void pqxx::binarystring::swap(binarystring &rhs)
{
const size_type s(m_size);
m_str.swap(rhs.m_str);
m_size = rhs.m_size;
rhs.m_size = s;
}
const string &pqxx::binarystring::str() const
{
if (m_str.empty() && m_size) m_str = string(c_ptr(), m_size);
return m_str;
}
string pqxx::escape_binary(const unsigned char bin[], size_t len)
{
#ifdef PQXX_HAVE_PQESCAPEBYTEA
size_t escapedlen = 0;
unsigned char *p = const_cast<unsigned char *>(bin);
PQAlloc<unsigned char> A(PQescapeBytea(p, len, &escapedlen));
const char *cstr = reinterpret_cast<const char *>(A.c_ptr());
if (!cstr) throw bad_alloc();
return string(cstr, escapedlen-1);
#else
string result;
result.reserve(len);
for (size_t i=0; i<len; ++i)
{
if (bin[i] & 0x80)
{
char buf[8];
sprintf(buf, "\\\\%03o", unsigned(bin[i]));
result += buf;
}
else switch (bin[i])
{
case 0:
result += "\\\\000";
break;
case '\'':
result += "\\'";
break;
case '\\':
result += "\\\\\\\\";
break;
default:
result += char(bin[i]);
}
}
return result;
#endif
}
string pqxx::escape_binary(const unsigned char bin[])
{
return escape_binary(bin, strlen(reinterpret_cast<const char *>(bin)));
}
string pqxx::escape_binary(const char bin[], size_t len)
{
return escape_binary(reinterpret_cast<const unsigned char *>(bin), len);
}
string pqxx::escape_binary(const char bin[])
{
return escape_binary(bin, strlen(bin));
}
string pqxx::escape_binary(const string &bin)
{
return escape_binary(bin.c_str(), bin.size());
}
<commit_msg>Fixed bug in swap(); added equality comparison<commit_after>/*-------------------------------------------------------------------------
*
* FILE
* binarystring.cxx
*
* DESCRIPTION
* implementation of bytea (binary string) conversions
*
* Copyright (c) 2003-2004, Jeroen T. Vermeulen <[email protected]>
*
* See COPYING for copyright license. If you did not receive a file called
* COPYING with this source code, please notify the distributor of this mistake,
* or contact the author.
*
*-------------------------------------------------------------------------
*/
#include "pqxx/compiler.h"
#include <new>
#include <stdexcept>
#include "pqxx/binarystring"
using namespace PGSTD;
using namespace pqxx::internal;
using namespace pqxx::internal::pq;
namespace
{
// Convert textual digit to value
inline char DV(unsigned char d) { return d - '0'; }
}
pqxx::binarystring::binarystring(const result::field &F) :
super(),
m_size(0)
{
unsigned char *p = const_cast<unsigned char *>(
reinterpret_cast<const_iterator>(F.c_str()));
#ifdef PQXX_HAVE_PQUNESCAPEBYTEA
size_t sz = 0;
super::operator=(PQunescapeBytea(p, &sz));
if (!c_ptr()) throw bad_alloc();
m_size = sz;
#else
m_str.reserve(F.size());
for (result::field::size_type i=0; i<F.size(); ++i)
{
unsigned char c = p[i];
if (c == '\\')
{
c = p[++i];
if (isdigit(c) && isdigit(p[i+1]) && isdigit(p[i+2]))
{
c = (DV(p[c])<<9) | (DV(p[i+1])<<3) | DV(p[i+2]);
i += 2;
}
}
m_str += char(c);
}
m_size = m_str.size();
void *buf = malloc(m_size+1);
if (!buf)
throw bad_alloc();
super::operator=(static_cast<unsigned char *>(buf));
strcpy(static_cast<char *>(buf), m_str.c_str());
#endif
}
bool pqxx::binarystring::operator==(const binarystring &rhs) const throw ()
{
if (rhs.size() != size()) return false;
for (size_type i=0; i<size(); ++i) if (rhs[i] != data()[i]) return false;
return true;
}
pqxx::binarystring::const_reference pqxx::binarystring::at(size_type n) const
{
if (n >= m_size)
{
if (!m_size)
throw out_of_range("Accessing empty binarystring");
throw out_of_range("binarystring index out of range: " +
to_string(n) + " (should be below " + to_string(m_size) + ")");
}
return data()[n];
}
void pqxx::binarystring::swap(binarystring &rhs)
{
const size_type s(m_size);
// This can fail, so do it first
m_str.swap(rhs.m_str);
// PQAlloc<>::swap() is nothrow
super::swap(rhs);
// This part very obviously can't go wrong, so do it last
m_size = rhs.m_size;
rhs.m_size = s;
}
const string &pqxx::binarystring::str() const
{
if (m_str.empty() && m_size) m_str = string(c_ptr(), m_size);
return m_str;
}
string pqxx::escape_binary(const unsigned char bin[], size_t len)
{
#ifdef PQXX_HAVE_PQESCAPEBYTEA
size_t escapedlen = 0;
unsigned char *p = const_cast<unsigned char *>(bin);
PQAlloc<unsigned char> A(PQescapeBytea(p, len, &escapedlen));
const char *cstr = reinterpret_cast<const char *>(A.c_ptr());
if (!cstr) throw bad_alloc();
return string(cstr, escapedlen-1);
#else
string result;
result.reserve(len);
for (size_t i=0; i<len; ++i)
{
if (bin[i] & 0x80)
{
char buf[8];
sprintf(buf, "\\\\%03o", unsigned(bin[i]));
result += buf;
}
else switch (bin[i])
{
case 0:
result += "\\\\000";
break;
case '\'':
result += "\\'";
break;
case '\\':
result += "\\\\\\\\";
break;
default:
result += char(bin[i]);
}
}
return result;
#endif
}
string pqxx::escape_binary(const unsigned char bin[])
{
return escape_binary(bin, strlen(reinterpret_cast<const char *>(bin)));
}
string pqxx::escape_binary(const char bin[], size_t len)
{
return escape_binary(reinterpret_cast<const unsigned char *>(bin), len);
}
string pqxx::escape_binary(const char bin[])
{
return escape_binary(bin, strlen(bin));
}
string pqxx::escape_binary(const string &bin)
{
return escape_binary(bin.c_str(), bin.size());
}
<|endoftext|> |
<commit_before>#include <bts/rpc/rpc_client.hpp>
#include <bts/net/stcp_socket.hpp>
#include <bts/blockchain/address.hpp>
#include <bts/blockchain/transaction.hpp>
#include <bts/blockchain/block.hpp>
#include <bts/utilities/key_conversion.hpp>
#include <bts/utilities/padding_ostream.hpp>
#include <fc/reflect/variant.hpp>
#include <fc/network/tcp_socket.hpp>
#include <fc/rpc/json_connection.hpp>
#include <fc/thread/thread.hpp>
#include <fc/crypto/base58.hpp>
#include <fc/crypto/digest.hpp>
#include <fc/thread/future.hpp>
#include <bts/rpc_stubs/common_api_rpc_client.hpp>
namespace bts { namespace rpc {
namespace detail
{
class rpc_client_impl : public bts::rpc_stubs::common_api_rpc_client
{
public:
fc::rpc::json_connection_ptr _json_connection;
fc::future<void> _json_exec_loop_complete;
virtual fc::rpc::json_connection_ptr get_json_connection() const override { return _json_connection; }
void connect_to(const fc::ip::endpoint& remote_endpoint, const blockchain::public_key_type& remote_public_key);
bool login(const std::string& username, const std::string& password);
};
void rpc_client_impl::connect_to(const fc::ip::endpoint& remote_endpoint,
const bts::blockchain::public_key_type& remote_public_key)
{
fc::buffered_istream_ptr buffered_istream;
fc::buffered_ostream_ptr buffered_ostream;
if( remote_public_key != bts::blockchain::public_key_type() )
{
net::stcp_socket_ptr socket = std::make_shared<bts::net::stcp_socket>();
try
{
socket->connect_to(remote_endpoint);
}
catch ( const fc::exception& e )
{
elog( "fatal: error opening RPC socket to endpoint ${endpoint}: ${e}", ("endpoint", remote_endpoint)("e", e.to_detail_string() ) );
throw;
}
fc::ecc::compact_signature signature;
fc::raw::unpack(*socket, signature);
wdump((signature));
FC_ASSERT(blockchain::public_key_type(fc::ecc::public_key(signature, fc::digest(socket->get_shared_secret())))
== remote_public_key,
"Unable to establish secure connection with server.");
buffered_istream = std::make_shared<fc::buffered_istream>(socket);
buffered_ostream = std::make_shared<utilities::padding_ostream<>>(socket);
} else {
fc::tcp_socket_ptr socket = std::make_shared<fc::tcp_socket>();
try
{
socket->connect_to(remote_endpoint);
}
catch ( const fc::exception& e )
{
elog( "fatal: error opening RPC socket to endpoint ${endpoint}: ${e}", ("endpoint", remote_endpoint)("e", e.to_detail_string() ) );
throw;
}
buffered_istream = std::make_shared<fc::buffered_istream>(socket);
buffered_ostream = std::make_shared<fc::buffered_ostream>(socket);
}
_json_connection = std::make_shared<fc::rpc::json_connection>(std::move(buffered_istream),
std::move(buffered_ostream));
_json_exec_loop_complete = fc::async([=](){ _json_connection->exec(); }, "json exec loop");
}
bool rpc_client_impl::login(const std::string& username, const std::string& password)
{
return _json_connection->call<bool>("login", username, password);
}
} // end namespace detail
rpc_client::rpc_client() :
my(new detail::rpc_client_impl)
{
}
rpc_client::~rpc_client()
{
}
void rpc_client::connect_to(const fc::ip::endpoint& remote_endpoint,
const bts::blockchain::public_key_type& remote_public_key)
{
my->connect_to(remote_endpoint, remote_public_key);
}
bool rpc_client::login(const std::string& username, const std::string& password)
{
return my->login(username, password);
}
fc::rpc::json_connection_ptr rpc_client::get_json_connection() const
{
return my->_json_connection;
}
} } // bts::rpc
<commit_msg>Attempt to fix crash on exit<commit_after>#include <bts/rpc/rpc_client.hpp>
#include <bts/net/stcp_socket.hpp>
#include <bts/blockchain/address.hpp>
#include <bts/blockchain/transaction.hpp>
#include <bts/blockchain/block.hpp>
#include <bts/utilities/key_conversion.hpp>
#include <bts/utilities/padding_ostream.hpp>
#include <fc/reflect/variant.hpp>
#include <fc/network/tcp_socket.hpp>
#include <fc/rpc/json_connection.hpp>
#include <fc/thread/thread.hpp>
#include <fc/crypto/base58.hpp>
#include <fc/crypto/digest.hpp>
#include <fc/thread/future.hpp>
#include <bts/rpc_stubs/common_api_rpc_client.hpp>
namespace bts { namespace rpc {
namespace detail
{
class rpc_client_impl : public bts::rpc_stubs::common_api_rpc_client
{
public:
fc::rpc::json_connection_ptr _json_connection;
fc::future<void> _json_exec_loop_complete;
virtual fc::rpc::json_connection_ptr get_json_connection() const override { return _json_connection; }
void connect_to(const fc::ip::endpoint& remote_endpoint, const blockchain::public_key_type& remote_public_key);
bool login(const std::string& username, const std::string& password);
};
void rpc_client_impl::connect_to(const fc::ip::endpoint& remote_endpoint,
const bts::blockchain::public_key_type& remote_public_key)
{
fc::buffered_istream_ptr buffered_istream;
fc::buffered_ostream_ptr buffered_ostream;
if( remote_public_key != bts::blockchain::public_key_type() )
{
net::stcp_socket_ptr socket = std::make_shared<bts::net::stcp_socket>();
try
{
socket->connect_to(remote_endpoint);
}
catch ( const fc::exception& e )
{
elog( "fatal: error opening RPC socket to endpoint ${endpoint}: ${e}", ("endpoint", remote_endpoint)("e", e.to_detail_string() ) );
throw;
}
fc::ecc::compact_signature signature;
fc::raw::unpack(*socket, signature);
wdump((signature));
FC_ASSERT(blockchain::public_key_type(fc::ecc::public_key(signature, fc::digest(socket->get_shared_secret())))
== remote_public_key,
"Unable to establish secure connection with server.");
buffered_istream = std::make_shared<fc::buffered_istream>(socket);
buffered_ostream = std::make_shared<utilities::padding_ostream<>>(socket);
} else {
fc::tcp_socket_ptr socket = std::make_shared<fc::tcp_socket>();
try
{
socket->connect_to(remote_endpoint);
}
catch ( const fc::exception& e )
{
elog( "fatal: error opening RPC socket to endpoint ${endpoint}: ${e}", ("endpoint", remote_endpoint)("e", e.to_detail_string() ) );
throw;
}
buffered_istream = std::make_shared<fc::buffered_istream>(socket);
buffered_ostream = std::make_shared<fc::buffered_ostream>(socket);
}
_json_connection = std::make_shared<fc::rpc::json_connection>(std::move(buffered_istream),
std::move(buffered_ostream));
_json_exec_loop_complete = fc::async([=](){ _json_connection->exec(); }, "json exec loop");
}
bool rpc_client_impl::login(const std::string& username, const std::string& password)
{
return _json_connection->call<bool>("login", username, password);
}
} // end namespace detail
rpc_client::rpc_client() :
my(new detail::rpc_client_impl)
{
}
rpc_client::~rpc_client()
{
try
{
my->_json_exec_loop_complete.cancel_and_wait("~rpc_client()");
} catch (const fc::exception& e) {
wlog("Caught exception ${e} while canceling json_connection exec loop", ("e", e));
}
}
void rpc_client::connect_to(const fc::ip::endpoint& remote_endpoint,
const bts::blockchain::public_key_type& remote_public_key)
{
my->connect_to(remote_endpoint, remote_public_key);
}
bool rpc_client::login(const std::string& username, const std::string& password)
{
return my->login(username, password);
}
fc::rpc::json_connection_ptr rpc_client::get_json_connection() const
{
return my->_json_connection;
}
} } // bts::rpc
<|endoftext|> |
<commit_before><commit_msg>Replace the NOTIMPLEMENTED() in NPN_ForceRedraw with a comment<commit_after><|endoftext|> |
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "webkit/glue/plugins/plugin_list.h"
#include <algorithm>
#include "base/command_line.h"
#include "base/lazy_instance.h"
#include "base/logging.h"
#include "base/string_split.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "base/time.h"
#include "googleurl/src/gurl.h"
#include "net/base/mime_util.h"
#include "webkit/glue/plugins/plugin_constants_win.h"
#include "webkit/glue/plugins/plugin_lib.h"
#include "webkit/glue/plugins/plugin_switches.h"
#include "webkit/glue/webkit_glue.h"
namespace NPAPI {
base::LazyInstance<PluginList> g_singleton(base::LINKER_INITIALIZED);
// static
PluginList* PluginList::Singleton() {
return g_singleton.Pointer();
}
// static
bool PluginList::DebugPluginLoading() {
return CommandLine::ForCurrentProcess()->HasSwitch(
switches::kDebugPluginLoading);
}
bool PluginList::PluginsLoaded() {
AutoLock lock(lock_);
return plugins_loaded_;
}
void PluginList::RefreshPlugins() {
AutoLock lock(lock_);
plugins_need_refresh_ = true;
}
void PluginList::AddExtraPluginPath(const FilePath& plugin_path) {
// Chrome OS only loads plugins from /opt/google/chrome/plugins.
#if !defined(OS_CHROMEOS)
AutoLock lock(lock_);
extra_plugin_paths_.push_back(plugin_path);
#endif
}
void PluginList::RemoveExtraPluginPath(const FilePath& plugin_path) {
AutoLock lock(lock_);
std::vector<FilePath>::iterator it =
std::find(extra_plugin_paths_.begin(), extra_plugin_paths_.end(),
plugin_path);
if (it != extra_plugin_paths_.end())
extra_plugin_paths_.erase(it);
}
void PluginList::AddExtraPluginDir(const FilePath& plugin_dir) {
// Chrome OS only loads plugins from /opt/google/chrome/plugins.
#if !defined(OS_CHROMEOS)
AutoLock lock(lock_);
extra_plugin_dirs_.push_back(plugin_dir);
#endif
}
void PluginList::RegisterInternalPlugin(const PluginVersionInfo& info) {
AutoLock lock(lock_);
internal_plugins_.push_back(info);
}
void PluginList::UnregisterInternalPlugin(const FilePath& path) {
AutoLock lock(lock_);
for (size_t i = 0; i < internal_plugins_.size(); i++) {
if (internal_plugins_[i].path == path) {
internal_plugins_.erase(internal_plugins_.begin() + i);
return;
}
}
NOTREACHED();
}
bool PluginList::ReadPluginInfo(const FilePath& filename,
WebPluginInfo* info,
const PluginEntryPoints** entry_points) {
{
AutoLock lock(lock_);
for (size_t i = 0; i < internal_plugins_.size(); ++i) {
if (filename == internal_plugins_[i].path) {
*entry_points = &internal_plugins_[i].entry_points;
return CreateWebPluginInfo(internal_plugins_[i], info);
}
}
}
// Not an internal plugin.
*entry_points = NULL;
return PluginLib::ReadWebPluginInfo(filename, info);
}
bool PluginList::CreateWebPluginInfo(const PluginVersionInfo& pvi,
WebPluginInfo* info) {
std::vector<std::string> mime_types, file_extensions;
std::vector<string16> descriptions;
SplitString(WideToUTF8(pvi.mime_types), '|', &mime_types);
SplitString(WideToUTF8(pvi.file_extensions), '|', &file_extensions);
SplitString(WideToUTF16(pvi.type_descriptions), '|', &descriptions);
info->mime_types.clear();
if (mime_types.empty()) {
LOG_IF(ERROR, PluginList::DebugPluginLoading())
<< "Plugin " << pvi.product_name << " has no MIME types, skipping";
return false;
}
info->name = WideToUTF16(pvi.product_name);
info->desc = WideToUTF16(pvi.file_description);
info->version = WideToUTF16(pvi.file_version);
info->path = pvi.path;
info->enabled = true;
for (size_t i = 0; i < mime_types.size(); ++i) {
WebPluginMimeType mime_type;
mime_type.mime_type = StringToLowerASCII(mime_types[i]);
if (file_extensions.size() > i)
SplitString(file_extensions[i], ',', &mime_type.file_extensions);
if (descriptions.size() > i) {
mime_type.description = descriptions[i];
// On Windows, the description likely has a list of file extensions
// embedded in it (e.g. "SurfWriter file (*.swr)"). Remove an extension
// list from the description if it is present.
size_t ext = mime_type.description.find(ASCIIToUTF16("(*"));
if (ext != string16::npos) {
if (ext > 1 && mime_type.description[ext -1] == ' ')
ext--;
mime_type.description.erase(ext);
}
}
info->mime_types.push_back(mime_type);
}
return true;
}
PluginList::PluginList()
: plugins_loaded_(false), plugins_need_refresh_(false) {
PlatformInit();
}
void PluginList::LoadPlugins(bool refresh) {
// Don't want to hold the lock while loading new plugins, so we don't block
// other methods if they're called on other threads.
std::vector<FilePath> extra_plugin_paths;
std::vector<FilePath> extra_plugin_dirs;
std::vector<PluginVersionInfo> internal_plugins;
{
AutoLock lock(lock_);
if (plugins_loaded_ && !refresh && !plugins_need_refresh_)
return;
// Clear the refresh bit now, because it might get set again before we
// reach the end of the method.
plugins_need_refresh_ = false;
extra_plugin_paths = extra_plugin_paths_;
extra_plugin_dirs = extra_plugin_dirs_;
internal_plugins = internal_plugins_;
}
base::TimeTicks start_time = base::TimeTicks::Now();
std::vector<WebPluginInfo> new_plugins;
std::set<FilePath> visited_plugins;
std::vector<FilePath> directories_to_scan;
GetPluginDirectories(&directories_to_scan);
// Load internal plugins first so that, if both an internal plugin and a
// "discovered" plugin want to handle the same type, the internal plugin
// will have precedence.
for (size_t i = 0; i < internal_plugins.size(); ++i) {
if (internal_plugins[i].path.value() == kDefaultPluginLibraryName)
continue;
LoadPlugin(internal_plugins[i].path, &new_plugins);
}
for (size_t i = 0; i < extra_plugin_paths.size(); ++i) {
const FilePath& path = extra_plugin_paths[i];
if (visited_plugins.find(path) != visited_plugins.end())
continue;
LoadPlugin(path, &new_plugins);
visited_plugins.insert(path);
}
for (size_t i = 0; i < extra_plugin_dirs.size(); ++i) {
LoadPluginsFromDir(extra_plugin_dirs[i], &new_plugins, &visited_plugins);
}
for (size_t i = 0; i < directories_to_scan.size(); ++i) {
LoadPluginsFromDir(directories_to_scan[i], &new_plugins, &visited_plugins);
}
#if defined OS_WIN
LoadPluginsFromRegistry(&new_plugins, &visited_plugins);
#endif
// Load the default plugin last.
if (webkit_glue::IsDefaultPluginEnabled())
LoadPlugin(FilePath(kDefaultPluginLibraryName), &new_plugins);
base::TimeTicks end_time = base::TimeTicks::Now();
base::TimeDelta elapsed = end_time - start_time;
DLOG(INFO) << "Loaded plugin list in " << elapsed.InMilliseconds() << " ms.";
// Only update the data now since loading plugins can take a while.
AutoLock lock(lock_);
// Go through and mark new plugins in the disabled list as, well, disabled.
for (std::vector<WebPluginInfo>::iterator it = new_plugins.begin();
it != new_plugins.end();
++it) {
if (disabled_plugins_.find(it->path) != disabled_plugins_.end())
it->enabled = false;
}
plugins_ = new_plugins;
plugins_loaded_ = true;
}
void PluginList::LoadPlugin(const FilePath& path,
std::vector<WebPluginInfo>* plugins) {
LOG_IF(ERROR, PluginList::DebugPluginLoading())
<< "Loading plugin " << path.value();
WebPluginInfo plugin_info;
const PluginEntryPoints* entry_points;
if (!ReadPluginInfo(path, &plugin_info, &entry_points))
return;
if (!ShouldLoadPlugin(plugin_info, plugins))
return;
if (path.value() != kDefaultPluginLibraryName
#if defined(OS_WIN) && !defined(NDEBUG)
&& path.BaseName().value() != L"npspy.dll" // Make an exception for NPSPY
#endif
) {
for (size_t i = 0; i < plugin_info.mime_types.size(); ++i) {
// TODO: don't load global handlers for now.
// WebKit hands to the Plugin before it tries
// to handle mimeTypes on its own.
const std::string &mime_type = plugin_info.mime_types[i].mime_type;
if (mime_type == "*" )
return;
}
}
plugins->push_back(plugin_info);
}
bool PluginList::FindPlugin(const std::string& mime_type,
bool allow_wildcard,
WebPluginInfo* info) {
DCHECK(mime_type == StringToLowerASCII(mime_type));
LoadPlugins(false);
AutoLock lock(lock_);
for (size_t i = 0; i < plugins_.size(); ++i) {
if (plugins_[i].enabled &&
SupportsType(plugins_[i], mime_type, allow_wildcard)) {
*info = plugins_[i];
return true;
}
}
return false;
}
bool PluginList::FindDisabledPlugin(const std::string& mime_type,
bool allow_wildcard,
WebPluginInfo* info) {
DCHECK(mime_type == StringToLowerASCII(mime_type));
LoadPlugins(false);
AutoLock lock(lock_);
for (size_t i = 0; i < plugins_.size(); ++i) {
if (!plugins_[i].enabled &&
SupportsType(plugins_[i], mime_type, allow_wildcard)) {
*info = plugins_[i];
return true;
}
}
return false;
}
bool PluginList::FindPlugin(const GURL &url,
std::string* actual_mime_type,
WebPluginInfo* info) {
LoadPlugins(false);
AutoLock lock(lock_);
std::string path = url.path();
std::string::size_type last_dot = path.rfind('.');
if (last_dot == std::string::npos)
return false;
std::string extension = StringToLowerASCII(std::string(path, last_dot+1));
for (size_t i = 0; i < plugins_.size(); ++i) {
if (plugins_[i].enabled &&
SupportsExtension(plugins_[i], extension, actual_mime_type)) {
*info = plugins_[i];
return true;
}
}
return false;
}
bool PluginList::SupportsType(const WebPluginInfo& info,
const std::string &mime_type,
bool allow_wildcard) {
// Webkit will ask for a plugin to handle empty mime types.
if (mime_type.empty())
return false;
for (size_t i = 0; i < info.mime_types.size(); ++i) {
const WebPluginMimeType& mime_info = info.mime_types[i];
if (net::MatchesMimeType(mime_info.mime_type, mime_type)) {
if (!allow_wildcard && mime_info.mime_type == "*") {
continue;
}
return true;
}
}
return false;
}
bool PluginList::SupportsExtension(const WebPluginInfo& info,
const std::string &extension,
std::string* actual_mime_type) {
for (size_t i = 0; i < info.mime_types.size(); ++i) {
const WebPluginMimeType& mime_type = info.mime_types[i];
for (size_t j = 0; j < mime_type.file_extensions.size(); ++j) {
if (mime_type.file_extensions[j] == extension) {
if (actual_mime_type)
*actual_mime_type = mime_type.mime_type;
return true;
}
}
}
return false;
}
void PluginList::GetPlugins(bool refresh, std::vector<WebPluginInfo>* plugins) {
LoadPlugins(refresh);
AutoLock lock(lock_);
*plugins = plugins_;
}
void PluginList::GetEnabledPlugins(bool refresh,
std::vector<WebPluginInfo>* plugins) {
LoadPlugins(refresh);
plugins->clear();
AutoLock lock(lock_);
for (std::vector<WebPluginInfo>::const_iterator it = plugins_.begin();
it != plugins_.end();
++it) {
if (it->enabled)
plugins->push_back(*it);
}
}
bool PluginList::GetPluginInfo(const GURL& url,
const std::string& mime_type,
bool allow_wildcard,
WebPluginInfo* info,
std::string* actual_mime_type) {
bool found = FindPlugin(mime_type, allow_wildcard, info);
if (!found || (info->path.value() == kDefaultPluginLibraryName)) {
if (FindPlugin(url, actual_mime_type, info) ||
FindDisabledPlugin(mime_type, allow_wildcard, info)) {
found = true;
}
}
return found;
}
bool PluginList::GetPluginInfoByPath(const FilePath& plugin_path,
WebPluginInfo* info) {
LoadPlugins(false);
AutoLock lock(lock_);
for (size_t i = 0; i < plugins_.size(); ++i) {
if (plugins_[i].path == plugin_path) {
*info = plugins_[i];
return true;
}
}
return false;
}
bool PluginList::EnablePlugin(const FilePath& filename) {
AutoLock lock(lock_);
bool did_enable = false;
std::set<FilePath>::iterator entry = disabled_plugins_.find(filename);
if (entry == disabled_plugins_.end())
return did_enable; // Early exit if plugin not in disabled list.
disabled_plugins_.erase(entry); // Remove from disabled list.
// Set enabled flags if necessary.
for (std::vector<WebPluginInfo>::iterator it = plugins_.begin();
it != plugins_.end();
++it) {
if (it->path == filename) {
DCHECK(!it->enabled); // Should have been disabled.
it->enabled = true;
did_enable = true;
}
}
return did_enable;
}
bool PluginList::DisablePlugin(const FilePath& filename) {
AutoLock lock(lock_);
bool did_disable = false;
if (disabled_plugins_.find(filename) != disabled_plugins_.end())
return did_disable; // Early exit if plugin already in disabled list.
disabled_plugins_.insert(filename); // Add to disabled list.
// Unset enabled flags if necessary.
for (std::vector<WebPluginInfo>::iterator it = plugins_.begin();
it != plugins_.end();
++it) {
if (it->path == filename) {
DCHECK(it->enabled); // Should have been enabled.
it->enabled = false;
did_disable = true;
}
}
return did_disable;
}
void PluginList::Shutdown() {
// TODO
}
} // namespace NPAPI
<commit_msg>Reduce console DLOG(INFO) spam in plugin_list<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "webkit/glue/plugins/plugin_list.h"
#include <algorithm>
#include "base/command_line.h"
#include "base/lazy_instance.h"
#include "base/logging.h"
#include "base/string_split.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "googleurl/src/gurl.h"
#include "net/base/mime_util.h"
#include "webkit/glue/plugins/plugin_constants_win.h"
#include "webkit/glue/plugins/plugin_lib.h"
#include "webkit/glue/plugins/plugin_switches.h"
#include "webkit/glue/webkit_glue.h"
namespace NPAPI {
base::LazyInstance<PluginList> g_singleton(base::LINKER_INITIALIZED);
// static
PluginList* PluginList::Singleton() {
return g_singleton.Pointer();
}
// static
bool PluginList::DebugPluginLoading() {
return CommandLine::ForCurrentProcess()->HasSwitch(
switches::kDebugPluginLoading);
}
bool PluginList::PluginsLoaded() {
AutoLock lock(lock_);
return plugins_loaded_;
}
void PluginList::RefreshPlugins() {
AutoLock lock(lock_);
plugins_need_refresh_ = true;
}
void PluginList::AddExtraPluginPath(const FilePath& plugin_path) {
// Chrome OS only loads plugins from /opt/google/chrome/plugins.
#if !defined(OS_CHROMEOS)
AutoLock lock(lock_);
extra_plugin_paths_.push_back(plugin_path);
#endif
}
void PluginList::RemoveExtraPluginPath(const FilePath& plugin_path) {
AutoLock lock(lock_);
std::vector<FilePath>::iterator it =
std::find(extra_plugin_paths_.begin(), extra_plugin_paths_.end(),
plugin_path);
if (it != extra_plugin_paths_.end())
extra_plugin_paths_.erase(it);
}
void PluginList::AddExtraPluginDir(const FilePath& plugin_dir) {
// Chrome OS only loads plugins from /opt/google/chrome/plugins.
#if !defined(OS_CHROMEOS)
AutoLock lock(lock_);
extra_plugin_dirs_.push_back(plugin_dir);
#endif
}
void PluginList::RegisterInternalPlugin(const PluginVersionInfo& info) {
AutoLock lock(lock_);
internal_plugins_.push_back(info);
}
void PluginList::UnregisterInternalPlugin(const FilePath& path) {
AutoLock lock(lock_);
for (size_t i = 0; i < internal_plugins_.size(); i++) {
if (internal_plugins_[i].path == path) {
internal_plugins_.erase(internal_plugins_.begin() + i);
return;
}
}
NOTREACHED();
}
bool PluginList::ReadPluginInfo(const FilePath& filename,
WebPluginInfo* info,
const PluginEntryPoints** entry_points) {
{
AutoLock lock(lock_);
for (size_t i = 0; i < internal_plugins_.size(); ++i) {
if (filename == internal_plugins_[i].path) {
*entry_points = &internal_plugins_[i].entry_points;
return CreateWebPluginInfo(internal_plugins_[i], info);
}
}
}
// Not an internal plugin.
*entry_points = NULL;
return PluginLib::ReadWebPluginInfo(filename, info);
}
bool PluginList::CreateWebPluginInfo(const PluginVersionInfo& pvi,
WebPluginInfo* info) {
std::vector<std::string> mime_types, file_extensions;
std::vector<string16> descriptions;
SplitString(WideToUTF8(pvi.mime_types), '|', &mime_types);
SplitString(WideToUTF8(pvi.file_extensions), '|', &file_extensions);
SplitString(WideToUTF16(pvi.type_descriptions), '|', &descriptions);
info->mime_types.clear();
if (mime_types.empty()) {
LOG_IF(ERROR, PluginList::DebugPluginLoading())
<< "Plugin " << pvi.product_name << " has no MIME types, skipping";
return false;
}
info->name = WideToUTF16(pvi.product_name);
info->desc = WideToUTF16(pvi.file_description);
info->version = WideToUTF16(pvi.file_version);
info->path = pvi.path;
info->enabled = true;
for (size_t i = 0; i < mime_types.size(); ++i) {
WebPluginMimeType mime_type;
mime_type.mime_type = StringToLowerASCII(mime_types[i]);
if (file_extensions.size() > i)
SplitString(file_extensions[i], ',', &mime_type.file_extensions);
if (descriptions.size() > i) {
mime_type.description = descriptions[i];
// On Windows, the description likely has a list of file extensions
// embedded in it (e.g. "SurfWriter file (*.swr)"). Remove an extension
// list from the description if it is present.
size_t ext = mime_type.description.find(ASCIIToUTF16("(*"));
if (ext != string16::npos) {
if (ext > 1 && mime_type.description[ext -1] == ' ')
ext--;
mime_type.description.erase(ext);
}
}
info->mime_types.push_back(mime_type);
}
return true;
}
PluginList::PluginList()
: plugins_loaded_(false), plugins_need_refresh_(false) {
PlatformInit();
}
void PluginList::LoadPlugins(bool refresh) {
// Don't want to hold the lock while loading new plugins, so we don't block
// other methods if they're called on other threads.
std::vector<FilePath> extra_plugin_paths;
std::vector<FilePath> extra_plugin_dirs;
std::vector<PluginVersionInfo> internal_plugins;
{
AutoLock lock(lock_);
if (plugins_loaded_ && !refresh && !plugins_need_refresh_)
return;
// Clear the refresh bit now, because it might get set again before we
// reach the end of the method.
plugins_need_refresh_ = false;
extra_plugin_paths = extra_plugin_paths_;
extra_plugin_dirs = extra_plugin_dirs_;
internal_plugins = internal_plugins_;
}
std::vector<WebPluginInfo> new_plugins;
std::set<FilePath> visited_plugins;
std::vector<FilePath> directories_to_scan;
GetPluginDirectories(&directories_to_scan);
// Load internal plugins first so that, if both an internal plugin and a
// "discovered" plugin want to handle the same type, the internal plugin
// will have precedence.
for (size_t i = 0; i < internal_plugins.size(); ++i) {
if (internal_plugins[i].path.value() == kDefaultPluginLibraryName)
continue;
LoadPlugin(internal_plugins[i].path, &new_plugins);
}
for (size_t i = 0; i < extra_plugin_paths.size(); ++i) {
const FilePath& path = extra_plugin_paths[i];
if (visited_plugins.find(path) != visited_plugins.end())
continue;
LoadPlugin(path, &new_plugins);
visited_plugins.insert(path);
}
for (size_t i = 0; i < extra_plugin_dirs.size(); ++i) {
LoadPluginsFromDir(extra_plugin_dirs[i], &new_plugins, &visited_plugins);
}
for (size_t i = 0; i < directories_to_scan.size(); ++i) {
LoadPluginsFromDir(directories_to_scan[i], &new_plugins, &visited_plugins);
}
#if defined OS_WIN
LoadPluginsFromRegistry(&new_plugins, &visited_plugins);
#endif
// Load the default plugin last.
if (webkit_glue::IsDefaultPluginEnabled())
LoadPlugin(FilePath(kDefaultPluginLibraryName), &new_plugins);
// Only update the data now since loading plugins can take a while.
AutoLock lock(lock_);
// Go through and mark new plugins in the disabled list as, well, disabled.
for (std::vector<WebPluginInfo>::iterator it = new_plugins.begin();
it != new_plugins.end();
++it) {
if (disabled_plugins_.find(it->path) != disabled_plugins_.end())
it->enabled = false;
}
plugins_ = new_plugins;
plugins_loaded_ = true;
}
void PluginList::LoadPlugin(const FilePath& path,
std::vector<WebPluginInfo>* plugins) {
LOG_IF(ERROR, PluginList::DebugPluginLoading())
<< "Loading plugin " << path.value();
WebPluginInfo plugin_info;
const PluginEntryPoints* entry_points;
if (!ReadPluginInfo(path, &plugin_info, &entry_points))
return;
if (!ShouldLoadPlugin(plugin_info, plugins))
return;
if (path.value() != kDefaultPluginLibraryName
#if defined(OS_WIN) && !defined(NDEBUG)
&& path.BaseName().value() != L"npspy.dll" // Make an exception for NPSPY
#endif
) {
for (size_t i = 0; i < plugin_info.mime_types.size(); ++i) {
// TODO: don't load global handlers for now.
// WebKit hands to the Plugin before it tries
// to handle mimeTypes on its own.
const std::string &mime_type = plugin_info.mime_types[i].mime_type;
if (mime_type == "*" )
return;
}
}
plugins->push_back(plugin_info);
}
bool PluginList::FindPlugin(const std::string& mime_type,
bool allow_wildcard,
WebPluginInfo* info) {
DCHECK(mime_type == StringToLowerASCII(mime_type));
LoadPlugins(false);
AutoLock lock(lock_);
for (size_t i = 0; i < plugins_.size(); ++i) {
if (plugins_[i].enabled &&
SupportsType(plugins_[i], mime_type, allow_wildcard)) {
*info = plugins_[i];
return true;
}
}
return false;
}
bool PluginList::FindDisabledPlugin(const std::string& mime_type,
bool allow_wildcard,
WebPluginInfo* info) {
DCHECK(mime_type == StringToLowerASCII(mime_type));
LoadPlugins(false);
AutoLock lock(lock_);
for (size_t i = 0; i < plugins_.size(); ++i) {
if (!plugins_[i].enabled &&
SupportsType(plugins_[i], mime_type, allow_wildcard)) {
*info = plugins_[i];
return true;
}
}
return false;
}
bool PluginList::FindPlugin(const GURL &url,
std::string* actual_mime_type,
WebPluginInfo* info) {
LoadPlugins(false);
AutoLock lock(lock_);
std::string path = url.path();
std::string::size_type last_dot = path.rfind('.');
if (last_dot == std::string::npos)
return false;
std::string extension = StringToLowerASCII(std::string(path, last_dot+1));
for (size_t i = 0; i < plugins_.size(); ++i) {
if (plugins_[i].enabled &&
SupportsExtension(plugins_[i], extension, actual_mime_type)) {
*info = plugins_[i];
return true;
}
}
return false;
}
bool PluginList::SupportsType(const WebPluginInfo& info,
const std::string &mime_type,
bool allow_wildcard) {
// Webkit will ask for a plugin to handle empty mime types.
if (mime_type.empty())
return false;
for (size_t i = 0; i < info.mime_types.size(); ++i) {
const WebPluginMimeType& mime_info = info.mime_types[i];
if (net::MatchesMimeType(mime_info.mime_type, mime_type)) {
if (!allow_wildcard && mime_info.mime_type == "*") {
continue;
}
return true;
}
}
return false;
}
bool PluginList::SupportsExtension(const WebPluginInfo& info,
const std::string &extension,
std::string* actual_mime_type) {
for (size_t i = 0; i < info.mime_types.size(); ++i) {
const WebPluginMimeType& mime_type = info.mime_types[i];
for (size_t j = 0; j < mime_type.file_extensions.size(); ++j) {
if (mime_type.file_extensions[j] == extension) {
if (actual_mime_type)
*actual_mime_type = mime_type.mime_type;
return true;
}
}
}
return false;
}
void PluginList::GetPlugins(bool refresh, std::vector<WebPluginInfo>* plugins) {
LoadPlugins(refresh);
AutoLock lock(lock_);
*plugins = plugins_;
}
void PluginList::GetEnabledPlugins(bool refresh,
std::vector<WebPluginInfo>* plugins) {
LoadPlugins(refresh);
plugins->clear();
AutoLock lock(lock_);
for (std::vector<WebPluginInfo>::const_iterator it = plugins_.begin();
it != plugins_.end();
++it) {
if (it->enabled)
plugins->push_back(*it);
}
}
bool PluginList::GetPluginInfo(const GURL& url,
const std::string& mime_type,
bool allow_wildcard,
WebPluginInfo* info,
std::string* actual_mime_type) {
bool found = FindPlugin(mime_type, allow_wildcard, info);
if (!found || (info->path.value() == kDefaultPluginLibraryName)) {
if (FindPlugin(url, actual_mime_type, info) ||
FindDisabledPlugin(mime_type, allow_wildcard, info)) {
found = true;
}
}
return found;
}
bool PluginList::GetPluginInfoByPath(const FilePath& plugin_path,
WebPluginInfo* info) {
LoadPlugins(false);
AutoLock lock(lock_);
for (size_t i = 0; i < plugins_.size(); ++i) {
if (plugins_[i].path == plugin_path) {
*info = plugins_[i];
return true;
}
}
return false;
}
bool PluginList::EnablePlugin(const FilePath& filename) {
AutoLock lock(lock_);
bool did_enable = false;
std::set<FilePath>::iterator entry = disabled_plugins_.find(filename);
if (entry == disabled_plugins_.end())
return did_enable; // Early exit if plugin not in disabled list.
disabled_plugins_.erase(entry); // Remove from disabled list.
// Set enabled flags if necessary.
for (std::vector<WebPluginInfo>::iterator it = plugins_.begin();
it != plugins_.end();
++it) {
if (it->path == filename) {
DCHECK(!it->enabled); // Should have been disabled.
it->enabled = true;
did_enable = true;
}
}
return did_enable;
}
bool PluginList::DisablePlugin(const FilePath& filename) {
AutoLock lock(lock_);
bool did_disable = false;
if (disabled_plugins_.find(filename) != disabled_plugins_.end())
return did_disable; // Early exit if plugin already in disabled list.
disabled_plugins_.insert(filename); // Add to disabled list.
// Unset enabled flags if necessary.
for (std::vector<WebPluginInfo>::iterator it = plugins_.begin();
it != plugins_.end();
++it) {
if (it->path == filename) {
DCHECK(it->enabled); // Should have been enabled.
it->enabled = false;
did_disable = true;
}
}
return did_disable;
}
void PluginList::Shutdown() {
// TODO
}
} // namespace NPAPI
<|endoftext|> |
<commit_before>#include "scanner.hpp"
#include "compiler_error.hpp"
#include <cctype>
namespace p0
{
namespace
{
bool is_whitespace(char c)
{
switch (c)
{
case ' ':
case '\t':
case '\n':
case '\r':
return true;
default:
return false;
}
}
bool is_identifer_first(char c)
{
c = std::tolower(c);
return
((c >= 'a') && (c <= 'z')) ||
(c == '_');
}
bool is_digit_10(char c)
{
return ((c >= '0') && (c <= '9'));
}
bool is_identifier_tail(char c)
{
return
is_identifer_first(c) ||
is_digit_10(c);
}
bool is_keyword(source_range content, char const *keyword)
{
for (auto i = content.begin(); i != content.end(); ++i, ++keyword)
{
if (*i != *keyword)
{
return false;
}
}
return (*keyword == '\0');
}
struct keyword
{
char const *content;
token_type::Enum token;
};
token_type::Enum find_keyword(source_range content)
{
//a rather simple (= slow) approach of finding keywords
static std::array<keyword, 9> const keywords =
{{
{"var", token_type::var},
{"function", token_type::function},
{"return", token_type::return_},
{"null", token_type::null},
{"if", token_type::if_},
{"else", token_type::else_},
{"while", token_type::while_},
{"break", token_type::break_},
{"continue", token_type::continue_},
}};
using namespace std;
for (auto k = begin(keywords); k != end(keywords); ++k)
{
if (is_keyword(content, k->content))
{
return k->token;
}
}
return token_type::identifier;
}
}
scanner::scanner(
source_range source
)
: m_pos(source.begin())
, m_end(source.end())
, m_was_integer(false)
{
}
token scanner::next_token()
{
skip_whitespace();
if (m_pos == m_end)
{
return token(
token_type::end_of_file,
source_range(m_end, m_end)
);
}
switch (*m_pos)
{
case '(': return eat_single_char_token(token_type::parenthesis_left);
case ')': return eat_single_char_token(token_type::parenthesis_right);
case '{': return eat_single_char_token(token_type::brace_left);
case '}': return eat_single_char_token(token_type::brace_right);
case '[': return eat_single_char_token(token_type::bracket_left);
case ']': return eat_single_char_token(token_type::bracket_right);
case '=': return eat_single_or_double_token(token_type::assign, '=', token_type::equal);
case ',': return eat_single_char_token(token_type::comma);
case '+': return eat_single_char_token(token_type::plus);
case '-': return eat_single_char_token(token_type::minus);
case '*': return eat_single_char_token(token_type::star);
case '/': return eat_single_char_token(token_type::slash);
case '%': return eat_single_char_token(token_type::modulo);
case '&': return eat_single_or_double_token(token_type::ampersand, '&', token_type::ampersands);
case '|': return eat_single_or_double_token(token_type::pipe, '|', token_type::pipes);
case '<': return eat_single_or_triple_token(token_type::less, '<', token_type::shift_left, '=', token_type::less_equal);
case '>': return eat_single_or_triple_token(token_type::greater, '>', token_type::shift_right, '=', token_type::greater_equal);
case '!': return eat_single_or_double_token(token_type::exclamation_mark, '=', token_type::not_equal);
case '.': return eat_single_char_token(token_type::dot);
case '~': return eat_single_char_token(token_type::tilde);
case '^': return eat_single_char_token(token_type::caret);
case '"':
{
++m_pos;
auto const string_begin = m_pos;
for (;;)
{
auto const on_unexpected_eof = [this]()
{
throw compiler_error(
"Unexpected end of file in string literal",
source_range(m_end, m_end)
);
};
if (m_pos == m_end)
{
on_unexpected_eof();
}
if (((*m_pos < 0x20) ||
(*m_pos > 0x7e)) &&
(*m_pos != '\t'))
{
throw compiler_error(
"This character has to be hex-encoded in a string literal",
source_range(m_pos, m_pos + 1)
);
}
if (*m_pos == '\\')
{
++m_pos;
if (m_pos == m_end)
{
on_unexpected_eof();
}
++m_pos;
}
else if (*m_pos == '"')
{
break;
}
else
{
++m_pos;
}
}
auto const string_end = m_pos;
++m_pos;
return token(
token_type::string,
source_range(string_begin, string_end)
);
}
default:
if (is_identifer_first(*m_pos))
{
if (m_was_integer)
{
throw compiler_error(
"An integer may not be directly followed by an identifier or a keyword",
source_range(m_pos, m_pos + 1)
);
}
auto const identifier_begin = m_pos;
do
{
++m_pos;
}
while (
(m_pos != m_end) &&
is_identifier_tail(*m_pos));
auto const identifier_end = m_pos;
source_range const range(
identifier_begin,
identifier_end
);
auto const type = find_keyword(range);
return token(
type,
range
);
}
if (is_digit_10(*m_pos))
{
auto const integer_begin = m_pos;
do
{
++m_pos;
}
while (
(m_pos != m_end) &&
is_digit_10(*m_pos));
auto const integer_end = m_pos;
m_was_integer = true;
return token(
token_type::integer_10,
source_range(integer_begin, integer_end)
);
}
throw compiler_error(
"Unexpected character",
source_range(m_pos, m_pos + 1)
);
}
}
void scanner::skip_line()
{
while (
(m_pos != m_end) &&
(*m_pos != '\n'))
{
++m_pos;
}
}
source_range scanner::rest() const
{
return source_range(
m_pos,
m_end
);
}
void scanner::skip_whitespace()
{
while (m_pos != m_end)
{
if (is_whitespace(*m_pos))
{
++m_pos;
m_was_integer = false;
continue;
}
//a comment starts with a semicolon and ends after the current line
if (*m_pos == ';')
{
do
{
++m_pos;
}
while (
(m_pos != m_end) &&
(*m_pos != '\n')
);
m_was_integer = false;
continue;
}
break;
}
}
token scanner::eat_single_char_token(token_type::Enum type)
{
++m_pos;
return token(
type,
source_range((m_pos - 1), m_pos)
);
}
token scanner::eat_single_or_double_token(
token_type::Enum single_token,
char second_char,
token_type::Enum double_token
)
{
++m_pos;
if ((m_pos != m_end) &&
(*m_pos == second_char))
{
++m_pos;
return token(double_token, source_range(m_pos - 2, m_pos));
}
return token(single_token, source_range(m_pos - 1, m_pos));
}
token scanner::eat_single_or_triple_token(
token_type::Enum single_token,
char second_char_0,
token_type::Enum double_token_0,
char second_char_1,
token_type::Enum double_token_1
)
{
++m_pos;
if (m_pos != m_end)
{
if (*m_pos == second_char_0)
{
++m_pos;
return token(double_token_0, source_range(m_pos - 2, m_pos));
}
if (*m_pos == second_char_1)
{
++m_pos;
return token(double_token_1, source_range(m_pos - 2, m_pos));
}
}
return token(single_token, source_range(m_pos - 1, m_pos));
}
}
<commit_msg>integer followed by identifier/keyword fixed<commit_after>#include "scanner.hpp"
#include "compiler_error.hpp"
#include <cctype>
namespace p0
{
namespace
{
bool is_whitespace(char c)
{
switch (c)
{
case ' ':
case '\t':
case '\n':
case '\r':
return true;
default:
return false;
}
}
bool is_identifer_first(char c)
{
c = std::tolower(c);
return
((c >= 'a') && (c <= 'z')) ||
(c == '_');
}
bool is_digit_10(char c)
{
return ((c >= '0') && (c <= '9'));
}
bool is_identifier_tail(char c)
{
return
is_identifer_first(c) ||
is_digit_10(c);
}
bool is_keyword(source_range content, char const *keyword)
{
for (auto i = content.begin(); i != content.end(); ++i, ++keyword)
{
if (*i != *keyword)
{
return false;
}
}
return (*keyword == '\0');
}
struct keyword
{
char const *content;
token_type::Enum token;
};
token_type::Enum find_keyword(source_range content)
{
//a rather simple (= slow) approach of finding keywords
static std::array<keyword, 9> const keywords =
{{
{"var", token_type::var},
{"function", token_type::function},
{"return", token_type::return_},
{"null", token_type::null},
{"if", token_type::if_},
{"else", token_type::else_},
{"while", token_type::while_},
{"break", token_type::break_},
{"continue", token_type::continue_},
}};
using namespace std;
for (auto k = begin(keywords); k != end(keywords); ++k)
{
if (is_keyword(content, k->content))
{
return k->token;
}
}
return token_type::identifier;
}
}
scanner::scanner(
source_range source
)
: m_pos(source.begin())
, m_end(source.end())
, m_was_integer(false)
{
}
token scanner::next_token()
{
skip_whitespace();
if (m_pos == m_end)
{
return token(
token_type::end_of_file,
source_range(m_end, m_end)
);
}
bool const was_integer = m_was_integer;
m_was_integer = false;
switch (*m_pos)
{
case '(': return eat_single_char_token(token_type::parenthesis_left);
case ')': return eat_single_char_token(token_type::parenthesis_right);
case '{': return eat_single_char_token(token_type::brace_left);
case '}': return eat_single_char_token(token_type::brace_right);
case '[': return eat_single_char_token(token_type::bracket_left);
case ']': return eat_single_char_token(token_type::bracket_right);
case '=': return eat_single_or_double_token(token_type::assign, '=', token_type::equal);
case ',': return eat_single_char_token(token_type::comma);
case '+': return eat_single_char_token(token_type::plus);
case '-': return eat_single_char_token(token_type::minus);
case '*': return eat_single_char_token(token_type::star);
case '/': return eat_single_char_token(token_type::slash);
case '%': return eat_single_char_token(token_type::modulo);
case '&': return eat_single_or_double_token(token_type::ampersand, '&', token_type::ampersands);
case '|': return eat_single_or_double_token(token_type::pipe, '|', token_type::pipes);
case '<': return eat_single_or_triple_token(token_type::less, '<', token_type::shift_left, '=', token_type::less_equal);
case '>': return eat_single_or_triple_token(token_type::greater, '>', token_type::shift_right, '=', token_type::greater_equal);
case '!': return eat_single_or_double_token(token_type::exclamation_mark, '=', token_type::not_equal);
case '.': return eat_single_char_token(token_type::dot);
case '~': return eat_single_char_token(token_type::tilde);
case '^': return eat_single_char_token(token_type::caret);
case '"':
{
++m_pos;
auto const string_begin = m_pos;
for (;;)
{
auto const on_unexpected_eof = [this]()
{
throw compiler_error(
"Unexpected end of file in string literal",
source_range(m_end, m_end)
);
};
if (m_pos == m_end)
{
on_unexpected_eof();
}
if (((*m_pos < 0x20) ||
(*m_pos > 0x7e)) &&
(*m_pos != '\t'))
{
throw compiler_error(
"This character has to be hex-encoded in a string literal",
source_range(m_pos, m_pos + 1)
);
}
if (*m_pos == '\\')
{
++m_pos;
if (m_pos == m_end)
{
on_unexpected_eof();
}
++m_pos;
}
else if (*m_pos == '"')
{
break;
}
else
{
++m_pos;
}
}
auto const string_end = m_pos;
++m_pos;
return token(
token_type::string,
source_range(string_begin, string_end)
);
}
default:
if (is_identifer_first(*m_pos))
{
if (was_integer)
{
throw compiler_error(
"An integer may not be directly followed by an identifier or a keyword",
source_range(m_pos, m_pos + 1)
);
}
auto const identifier_begin = m_pos;
do
{
++m_pos;
}
while (
(m_pos != m_end) &&
is_identifier_tail(*m_pos));
auto const identifier_end = m_pos;
source_range const range(
identifier_begin,
identifier_end
);
auto const type = find_keyword(range);
return token(
type,
range
);
}
if (is_digit_10(*m_pos))
{
auto const integer_begin = m_pos;
do
{
++m_pos;
}
while (
(m_pos != m_end) &&
is_digit_10(*m_pos));
auto const integer_end = m_pos;
m_was_integer = true;
return token(
token_type::integer_10,
source_range(integer_begin, integer_end)
);
}
throw compiler_error(
"Unexpected character",
source_range(m_pos, m_pos + 1)
);
}
}
void scanner::skip_line()
{
while (
(m_pos != m_end) &&
(*m_pos != '\n'))
{
++m_pos;
}
}
source_range scanner::rest() const
{
return source_range(
m_pos,
m_end
);
}
void scanner::skip_whitespace()
{
while (m_pos != m_end)
{
if (is_whitespace(*m_pos))
{
++m_pos;
m_was_integer = false;
continue;
}
//a comment starts with a semicolon and ends after the current line
if (*m_pos == ';')
{
do
{
++m_pos;
}
while (
(m_pos != m_end) &&
(*m_pos != '\n')
);
m_was_integer = false;
continue;
}
break;
}
}
token scanner::eat_single_char_token(token_type::Enum type)
{
++m_pos;
return token(
type,
source_range((m_pos - 1), m_pos)
);
}
token scanner::eat_single_or_double_token(
token_type::Enum single_token,
char second_char,
token_type::Enum double_token
)
{
++m_pos;
if ((m_pos != m_end) &&
(*m_pos == second_char))
{
++m_pos;
return token(double_token, source_range(m_pos - 2, m_pos));
}
return token(single_token, source_range(m_pos - 1, m_pos));
}
token scanner::eat_single_or_triple_token(
token_type::Enum single_token,
char second_char_0,
token_type::Enum double_token_0,
char second_char_1,
token_type::Enum double_token_1
)
{
++m_pos;
if (m_pos != m_end)
{
if (*m_pos == second_char_0)
{
++m_pos;
return token(double_token_0, source_range(m_pos - 2, m_pos));
}
if (*m_pos == second_char_1)
{
++m_pos;
return token(double_token_1, source_range(m_pos - 2, m_pos));
}
}
return token(single_token, source_range(m_pos - 1, m_pos));
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "ReadMaybeMapped.h"
#include <boost/iostreams/device/mapped_file.hpp>
#include <fcntl.h>
#include <sys/stat.h>
#ifdef __linux__
#include <sys/mman.h> // For madvise
#endif
#include "Debug.h"
#include "Macros.h"
namespace redex {
namespace {
std::string strerror_str(int no) { return std::string(strerror(no)); };
// Implementation based on posix read. Avoids heap allocation when data
// is small enough.
template <size_t kDataSize>
struct ReadFileContents final {
size_t size;
std::unique_ptr<char[]> content;
char inline_data[kDataSize];
explicit ReadFileContents(const std::string& file) {
int fd = open(file.c_str(), O_RDONLY | O_BINARY);
if (fd < 0) {
throw std::runtime_error(std::string("Failed to open ") + file + ": " +
strerror_str(errno));
}
struct stat st = {};
if (fstat(fd, &st) == -1) {
auto saved_errno = errno;
close(fd);
throw std::runtime_error(std::string("Failed to get file length of ") +
file + ": " + strerror_str(saved_errno));
}
read_data(file, fd, static_cast<size_t>(st.st_size));
}
ReadFileContents(const std::string& file, int fd, size_t size) {
read_data(file, fd, size);
}
void read_data(const std::string& file, int fd, size_t size_in) {
size = size_in;
if (size == 0) {
close(fd);
return;
}
char* data;
if (size > kDataSize) {
content = std::make_unique<char[]>(size);
data = content.get();
} else {
data = inline_data;
}
// Now read.
size_t remaining = size;
while (remaining > 0) {
ssize_t n = TEMP_FAILURE_RETRY(read(fd, data, remaining));
if (n <= 0) {
auto saved_errno = errno;
close(fd);
throw std::runtime_error(std::string("Failed reading ") + file + ": " +
strerror_str(saved_errno));
}
data += n;
remaining -= n;
}
close(fd);
}
const char* get_content() const {
return size > kDataSize ? content.get() : inline_data;
}
size_t get_content_size() const { return size; }
};
using PageSizeReadFileContents = ReadFileContents<4080>;
static_assert(sizeof(PageSizeReadFileContents) == 4096 || sizeof(void*) != 8,
"Unexpected size");
// Mmap: just map file contents and wrap the mapping, avoiding allocation
// and explicit I/O.
//
// Note: using boost for Windows compat.
template <int kMadviseFlags>
struct MmapFileContents final {
boost::iostreams::mapped_file_source mapped_file{};
explicit MmapFileContents(const std::string& file) {
mapped_file.open(file);
if (!mapped_file.is_open()) {
throw std::runtime_error(std::string("Could not open ") + file);
}
#ifdef __linux__
if (mapped_file.size() > 0) {
madvise(const_cast<char*>(mapped_file.data()),
mapped_file.size(),
kMadviseFlags);
}
#endif
}
const char* get_content() const { return mapped_file.data(); }
size_t get_content_size() const { return mapped_file.size(); }
};
} // namespace
// Mmaps may not amortize for small files. Split between `read` and `mmap`.
void read_file_with_contents(const std::string& file,
const std::function<void(const char*, size_t)>& fn,
size_t threshold) {
int fd = open(file.c_str(), O_RDONLY | O_BINARY);
if (fd < 0) {
throw std::runtime_error(std::string("Failed to open ") + file + ": " +
strerror_str(errno));
}
struct stat st = {};
if (fstat(fd, &st) == -1) {
auto saved_errno = errno;
close(fd);
throw std::runtime_error(std::string("Failed to get file length of ") +
file + ": " + strerror_str(saved_errno));
}
size_t size = static_cast<size_t>(st.st_size);
if (size <= threshold) {
auto content = PageSizeReadFileContents(file, fd, size);
fn(content.get_content(), content.get_content_size());
} else {
close(fd);
constexpr int kAdvFlags =
#ifdef __linux__
MADV_SEQUENTIAL | MADV_WILLNEED;
#else
0;
#endif
auto content = MmapFileContents<kAdvFlags>(file);
fn(content.get_content(), content.get_content_size());
}
}
} // namespace redex
<commit_msg>Add missing include<commit_after>/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "ReadMaybeMapped.h"
#include <boost/iostreams/device/mapped_file.hpp>
#include <fcntl.h>
#include <sys/stat.h>
#ifdef __linux__
#include <sys/mman.h> // For madvise
#endif
#include "utils/Compat.h" // TEMP_FAILURE_RETRY, if necessary.
#include "Debug.h"
#include "Macros.h"
namespace redex {
namespace {
std::string strerror_str(int no) { return std::string(strerror(no)); };
// Implementation based on posix read. Avoids heap allocation when data
// is small enough.
template <size_t kDataSize>
struct ReadFileContents final {
size_t size;
std::unique_ptr<char[]> content;
char inline_data[kDataSize];
explicit ReadFileContents(const std::string& file) {
int fd = open(file.c_str(), O_RDONLY | O_BINARY);
if (fd < 0) {
throw std::runtime_error(std::string("Failed to open ") + file + ": " +
strerror_str(errno));
}
struct stat st = {};
if (fstat(fd, &st) == -1) {
auto saved_errno = errno;
close(fd);
throw std::runtime_error(std::string("Failed to get file length of ") +
file + ": " + strerror_str(saved_errno));
}
read_data(file, fd, static_cast<size_t>(st.st_size));
}
ReadFileContents(const std::string& file, int fd, size_t size) {
read_data(file, fd, size);
}
void read_data(const std::string& file, int fd, size_t size_in) {
size = size_in;
if (size == 0) {
close(fd);
return;
}
char* data;
if (size > kDataSize) {
content = std::make_unique<char[]>(size);
data = content.get();
} else {
data = inline_data;
}
// Now read.
size_t remaining = size;
while (remaining > 0) {
ssize_t n = TEMP_FAILURE_RETRY(read(fd, data, remaining));
if (n <= 0) {
auto saved_errno = errno;
close(fd);
throw std::runtime_error(std::string("Failed reading ") + file + ": " +
strerror_str(saved_errno));
}
data += n;
remaining -= n;
}
close(fd);
}
const char* get_content() const {
return size > kDataSize ? content.get() : inline_data;
}
size_t get_content_size() const { return size; }
};
using PageSizeReadFileContents = ReadFileContents<4080>;
static_assert(sizeof(PageSizeReadFileContents) == 4096 || sizeof(void*) != 8,
"Unexpected size");
// Mmap: just map file contents and wrap the mapping, avoiding allocation
// and explicit I/O.
//
// Note: using boost for Windows compat.
template <int kMadviseFlags>
struct MmapFileContents final {
boost::iostreams::mapped_file_source mapped_file{};
explicit MmapFileContents(const std::string& file) {
mapped_file.open(file);
if (!mapped_file.is_open()) {
throw std::runtime_error(std::string("Could not open ") + file);
}
#ifdef __linux__
if (mapped_file.size() > 0) {
madvise(const_cast<char*>(mapped_file.data()),
mapped_file.size(),
kMadviseFlags);
}
#endif
}
const char* get_content() const { return mapped_file.data(); }
size_t get_content_size() const { return mapped_file.size(); }
};
} // namespace
// Mmaps may not amortize for small files. Split between `read` and `mmap`.
void read_file_with_contents(const std::string& file,
const std::function<void(const char*, size_t)>& fn,
size_t threshold) {
int fd = open(file.c_str(), O_RDONLY | O_BINARY);
if (fd < 0) {
throw std::runtime_error(std::string("Failed to open ") + file + ": " +
strerror_str(errno));
}
struct stat st = {};
if (fstat(fd, &st) == -1) {
auto saved_errno = errno;
close(fd);
throw std::runtime_error(std::string("Failed to get file length of ") +
file + ": " + strerror_str(saved_errno));
}
size_t size = static_cast<size_t>(st.st_size);
if (size <= threshold) {
auto content = PageSizeReadFileContents(file, fd, size);
fn(content.get_content(), content.get_content_size());
} else {
close(fd);
constexpr int kAdvFlags =
#ifdef __linux__
MADV_SEQUENTIAL | MADV_WILLNEED;
#else
0;
#endif
auto content = MmapFileContents<kAdvFlags>(file);
fn(content.get_content(), content.get_content_size());
}
}
} // namespace redex
<|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. *
******************************************************************************/
#pragma once
#include "vast/concept/parseable/vast/json.hpp"
#include "vast/concept/printable/vast/json.hpp"
#include "vast/detail/line_range.hpp"
#include "vast/error.hpp"
#include "vast/event.hpp"
#include "vast/expected.hpp"
#include "vast/format/multi_layout_reader.hpp"
#include "vast/format/printer_writer.hpp"
#include "vast/fwd.hpp"
#include "vast/json.hpp"
#include "vast/schema.hpp"
namespace vast::format::json {
struct event_printer : printer<event_printer> {
using attribute = event;
template <class Iterator>
bool print(Iterator& out, const event& e) const {
vast::json j;
if (!convert(e.data(), j, e.type()))
return false;
return printers::json<policy::oneline>(out, j);
}
};
class writer : public printer_writer<event_printer> {
public:
using printer_writer<event_printer>::printer_writer;
const char* name() const {
return "json-writer";
}
};
/// Adds a JSON object to a table slice builder according to a given layout.
/// @param builder The builder to add the JSON object to.
/// @param xs The JSON object to add to *builder.
/// @param layout The record type describing *xs*.
/// @param name The name of the reader used for logging.
/// @returns An error iff the operation failed.
caf::error add(table_slice_builder& builder, const vast::json::object& xs,
const record_type& layout, const std::string_view name);
/// @relates reader
struct default_selector {
caf::optional<record_type> operator()(const vast::json::object&) {
return layout;
}
caf::error schema(vast::schema sch) {
auto entry = *sch.begin();
if (!caf::holds_alternative<record_type>(entry))
return make_error(ec::invalid_configuration,
"only record_types supported for json schema");
layout = flatten(caf::get<record_type>(entry));
return caf::none;
}
vast::schema schema() const {
vast::schema result;
if (layout)
result.add(*layout);
return result;
}
static const char* name() {
return "json-reader";
}
caf::optional<record_type> layout = caf::none;
};
/// A reader for JSON data. It operates with a *selector* to determine the
/// mapping of JSON object to the appropriate record type in the schema.
template <class Selector = default_selector>
class reader final : public multi_layout_reader {
public:
using super = multi_layout_reader;
/// Constructs a JSON reader.
/// @param table_slice_type The ID for table slice type to build.
/// @param in The stream of JSON objects.
explicit reader(caf::atom_value table_slice_type,
std::unique_ptr<std::istream> in = nullptr);
void reset(std::unique_ptr<std::istream> in);
caf::error schema(vast::schema sch) override;
caf::error schema(vast::type, vast::schema);
vast::schema schema() const override;
const char* name() const override;
protected:
caf::error read_impl(size_t max_events, size_t max_slice_size,
consumer& f) override;
private:
using iterator_type = std::string_view::const_iterator;
Selector selector_;
std::unique_ptr<std::istream> input_;
std::unique_ptr<detail::line_range> lines_;
caf::optional<size_t> proto_field_;
std::vector<size_t> port_fields_;
};
// -- implementation ----------------------------------------------------------
template <class Selector>
reader<Selector>::reader(caf::atom_value table_slice_type,
std::unique_ptr<std::istream> in)
: super(table_slice_type) {
if (in != nullptr)
reset(std::move(in));
}
template <class Selector>
void reader<Selector>::reset(std::unique_ptr<std::istream> in) {
VAST_ASSERT(in != nullptr);
input_ = std::move(in);
lines_ = std::make_unique<detail::line_range>(*input_);
}
template <class Selector>
caf::error reader<Selector>::schema(vast::schema s) {
return selector_.schema(std::move(s));
}
template <class Selector>
vast::schema reader<Selector>::schema() const {
return selector_.schema();
}
template <class Selector>
const char* reader<Selector>::name() const {
return Selector::name();
}
template <class Selector>
caf::error reader<Selector>::read_impl(size_t max_events, size_t max_slice_size,
consumer& cons) {
VAST_ASSERT(max_events > 0);
VAST_ASSERT(max_slice_size > 0);
size_t produced = 0;
while (produced < max_events) {
// EOF check.
if (lines_->done())
return finish(cons, make_error(ec::end_of_input, "input exhausted"));
auto& line = lines_->get();
vast::json j;
if (!parsers::json(line, j))
return make_error(ec::parse_error, "unable to parse json");
auto xs = caf::get_if<vast::json::object>(&j);
if (!xs)
return make_error(ec::type_clash, "not a json object");
auto layout = selector_(*xs);
if (!layout)
return make_error(ec::parse_error, "unable to get a layout");
auto bptr = builder(*layout);
if (bptr == nullptr)
return make_error(ec::parse_error, "unable to get a builder");
if (auto err = add(*bptr, *xs, *layout, selector_.name())) {
err.context() += caf::make_message("line", lines_->line_number());
return finish(cons, err);
}
produced++;
if (bptr->rows() == max_slice_size)
if (auto err = finish(cons, bptr))
return err;
lines_->next();
}
return finish(cons);
}
} // namespace vast::format::json
<commit_msg>Don't abort on unrecognized events<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. *
******************************************************************************/
#pragma once
#include "vast/concept/parseable/vast/json.hpp"
#include "vast/concept/printable/vast/json.hpp"
#include "vast/detail/line_range.hpp"
#include "vast/error.hpp"
#include "vast/event.hpp"
#include "vast/expected.hpp"
#include "vast/format/multi_layout_reader.hpp"
#include "vast/format/printer_writer.hpp"
#include "vast/fwd.hpp"
#include "vast/json.hpp"
#include "vast/logger.hpp"
#include "vast/schema.hpp"
namespace vast::format::json {
struct event_printer : printer<event_printer> {
using attribute = event;
template <class Iterator>
bool print(Iterator& out, const event& e) const {
vast::json j;
if (!convert(e.data(), j, e.type()))
return false;
return printers::json<policy::oneline>(out, j);
}
};
class writer : public printer_writer<event_printer> {
public:
using printer_writer<event_printer>::printer_writer;
const char* name() const {
return "json-writer";
}
};
/// Adds a JSON object to a table slice builder according to a given layout.
/// @param builder The builder to add the JSON object to.
/// @param xs The JSON object to add to *builder.
/// @param layout The record type describing *xs*.
/// @param name The name of the reader used for logging.
/// @returns An error iff the operation failed.
caf::error add(table_slice_builder& builder, const vast::json::object& xs,
const record_type& layout, const std::string_view name);
/// @relates reader
struct default_selector {
caf::optional<record_type> operator()(const vast::json::object&) {
return layout;
}
caf::error schema(vast::schema sch) {
auto entry = *sch.begin();
if (!caf::holds_alternative<record_type>(entry))
return make_error(ec::invalid_configuration,
"only record_types supported for json schema");
layout = flatten(caf::get<record_type>(entry));
return caf::none;
}
vast::schema schema() const {
vast::schema result;
if (layout)
result.add(*layout);
return result;
}
static const char* name() {
return "json-reader";
}
caf::optional<record_type> layout = caf::none;
};
/// A reader for JSON data. It operates with a *selector* to determine the
/// mapping of JSON object to the appropriate record type in the schema.
template <class Selector = default_selector>
class reader final : public multi_layout_reader {
public:
using super = multi_layout_reader;
/// Constructs a JSON reader.
/// @param table_slice_type The ID for table slice type to build.
/// @param in The stream of JSON objects.
explicit reader(caf::atom_value table_slice_type,
std::unique_ptr<std::istream> in = nullptr);
void reset(std::unique_ptr<std::istream> in);
caf::error schema(vast::schema sch) override;
caf::error schema(vast::type, vast::schema);
vast::schema schema() const override;
const char* name() const override;
protected:
caf::error read_impl(size_t max_events, size_t max_slice_size,
consumer& f) override;
private:
using iterator_type = std::string_view::const_iterator;
Selector selector_;
std::unique_ptr<std::istream> input_;
std::unique_ptr<detail::line_range> lines_;
caf::optional<size_t> proto_field_;
std::vector<size_t> port_fields_;
};
// -- implementation ----------------------------------------------------------
template <class Selector>
reader<Selector>::reader(caf::atom_value table_slice_type,
std::unique_ptr<std::istream> in)
: super(table_slice_type) {
if (in != nullptr)
reset(std::move(in));
}
template <class Selector>
void reader<Selector>::reset(std::unique_ptr<std::istream> in) {
VAST_ASSERT(in != nullptr);
input_ = std::move(in);
lines_ = std::make_unique<detail::line_range>(*input_);
}
template <class Selector>
caf::error reader<Selector>::schema(vast::schema s) {
return selector_.schema(std::move(s));
}
template <class Selector>
vast::schema reader<Selector>::schema() const {
return selector_.schema();
}
template <class Selector>
const char* reader<Selector>::name() const {
return Selector::name();
}
template <class Selector>
caf::error reader<Selector>::read_impl(size_t max_events, size_t max_slice_size,
consumer& cons) {
VAST_ASSERT(max_events > 0);
VAST_ASSERT(max_slice_size > 0);
size_t produced = 0;
for (; produced < max_events; lines_->next()) {
// EOF check.
if (lines_->done())
return finish(cons, make_error(ec::end_of_input, "input exhausted"));
auto& line = lines_->get();
vast::json j;
if (!parsers::json(line, j))
return make_error(ec::parse_error, "unable to parse json");
auto xs = caf::get_if<vast::json::object>(&j);
if (!xs)
return make_error(ec::type_clash, "not a json object");
auto layout = selector_(*xs);
if (!layout) {
VAST_INFO(this, "unable to get a layout");
continue;
}
VAST_INFO(this, "got layout", *layout);
auto bptr = builder(*layout);
if (bptr == nullptr)
return make_error(ec::parse_error, "unable to get a builder");
if (auto err = add(*bptr, *xs, *layout, selector_.name())) {
err.context() += caf::make_message("line", lines_->line_number());
return finish(cons, err);
}
produced++;
if (bptr->rows() == max_slice_size)
if (auto err = finish(cons, bptr))
return err;
}
return finish(cons);
}
} // namespace vast::format::json
<|endoftext|> |
<commit_before>/**
* @file
*/
#pragma once
#include "libbirch/FiberState.hpp"
namespace libbirch {
/**
* Fiber.
*
* @ingroup libbirch
*
* @tparam YieldType Yield type.
*/
template<class YieldType>
class Fiber {
public:
/**
* Default constructor.
*/
Fiber(Label* context) {
//
}
/**
* Constructor.
*/
Fiber(Label* context, const Shared<FiberState<YieldType>>& state) :
state(context, state) {
//
}
/**
* Copy constructor.
*/
Fiber(Label* context, const Fiber<YieldType>& o) :
state(context, o.state) {
//
}
/**
* Deep copy constructor.
*/
Fiber(Label* context, Label* label, const Fiber<YieldType>& o) :
state(context, label, o.state) {
//
}
/**
* Clone the fiber.
*/
Fiber<YieldType> clone() const {
return Fiber<YieldType>(state.clone());
}
/**
* Freeze the fiber.
*/
void freeze() const {
state.freeze();
}
/**
* Thaw the fiber.
*/
void thaw(LazyLabel* label) const {
state.thaw(label);
}
/**
* Finish the fiber.
*/
void finish() const {
state.finish();
}
/**
* Run to next yield point.
*
* @return Was a value yielded?
*/
bool query() const {
bool result = false;
if (state.query()) {
result = state->query();
if (!result) {
const_cast<Fiber<YieldType>*>(this)->state.release();
// ^ fiber has finished, delete the state
}
}
return result;
}
/**
* Get the last yield value.
*/
YieldType get() const {
libbirch_assert_msg_(state.query(), "fiber handle undefined");
return state->get();
}
private:
/**
* Fiber state.
*/
Shared<FiberState<YieldType>> state;
};
template<class T>
struct is_value<Fiber<T>> {
static const bool value = false;
};
}
<commit_msg>Updates to Fiber constructors, copy and move constructors.<commit_after>/**
* @file
*/
#pragma once
#include "libbirch/FiberState.hpp"
namespace libbirch {
/**
* Fiber.
*
* @ingroup libbirch
*
* @tparam YieldType Yield type.
*/
template<class YieldType>
class Fiber {
public:
/**
* Constructor.
*/
Fiber() {
//
}
/**
* Constructor.
*/
Fiber(Label* context, const Shared<FiberState<YieldType>>& state) :
state(context, state) {
//
}
/**
* Copy constructor.
*/
Fiber(Label* context, const Fiber<YieldType>& o) :
state(context, o.state) {
//
}
/**
* Move constructor.
*/
Fiber(Label* context, Fiber<YieldType>&& o) :
state(context, std::move(o.state)) {
//
}
/**
* Deep copy constructor.
*/
Fiber(Label* context, Label* label, const Fiber<YieldType>& o) :
state(context, label, o.state) {
//
}
/**
* Copy assignment.
*/
Fiber& assign(Label* context, const Fiber<YieldType>& o) {
state.assign(context, o.state);
return *this;
}
/**
* Move assignment.
*/
Fiber& assign(Label* context, Fiber<YieldType>&& o) {
state.assign(context, std::move(o.state));
return *this;
}
/**
* Clone the fiber.
*/
Fiber<YieldType> clone() const {
return Fiber<YieldType>(state.clone());
}
/**
* Freeze the fiber.
*/
void freeze() const {
state.freeze();
}
/**
* Thaw the fiber.
*/
void thaw(LazyLabel* label) const {
state.thaw(label);
}
/**
* Finish the fiber.
*/
void finish() const {
state.finish();
}
/**
* Run to next yield point.
*
* @return Was a value yielded?
*/
bool query() const {
bool result = false;
if (state.query()) {
result = state->query();
if (!result) {
const_cast<Fiber<YieldType>*>(this)->state.release();
// ^ fiber has finished, delete the state
}
}
return result;
}
/**
* Get the last yield value.
*/
YieldType get() const {
libbirch_assert_msg_(state.query(), "fiber handle undefined");
return state->get();
}
private:
/**
* Fiber state.
*/
Shared<FiberState<YieldType>> state;
};
template<class T>
struct is_value<Fiber<T>> {
static const bool value = 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/host_zoom_map.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/profile.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/pref_service.h"
HostZoomMap::HostZoomMap(Profile* profile) : profile_(profile) {
const DictionaryValue* host_zoom_dictionary =
profile_->GetPrefs()->GetDictionary(prefs::kPerHostZoomLevels);
// Careful: The returned value could be NULL if the pref has never been set.
if (host_zoom_dictionary != NULL) {
for (DictionaryValue::key_iterator i(host_zoom_dictionary->begin_keys());
i != host_zoom_dictionary->end_keys(); ++i) {
std::wstring wide_host(*i);
int zoom_level = 0;
bool success = host_zoom_dictionary->GetIntegerWithoutPathExpansion(
wide_host, &zoom_level);
DCHECK(success);
host_zoom_levels_[WideToUTF8(wide_host)] = zoom_level;
}
}
}
// static
void HostZoomMap::RegisterUserPrefs(PrefService* prefs) {
prefs->RegisterDictionaryPref(prefs::kPerHostZoomLevels);
}
int HostZoomMap::GetZoomLevel(const std::string& host) const {
AutoLock auto_lock(lock_);
HostZoomLevels::const_iterator i(host_zoom_levels_.find(host));
return (i == host_zoom_levels_.end()) ? 0 : i->second;
}
void HostZoomMap::SetZoomLevel(const std::string& host, int level) {
DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
if (host.empty())
return;
{
AutoLock auto_lock(lock_);
if (level == 0)
host_zoom_levels_.erase(host);
else
host_zoom_levels_[host] = level;
}
DictionaryValue* host_zoom_dictionary =
profile_->GetPrefs()->GetMutableDictionary(prefs::kPerHostZoomLevels);
std::wstring wide_host(UTF8ToWide(host));
if (level == 0) {
host_zoom_dictionary->RemoveWithoutPathExpansion(wide_host, NULL);
} else {
host_zoom_dictionary->SetWithoutPathExpansion(wide_host,
Value::CreateIntegerValue(level));
}
}
void HostZoomMap::ResetToDefaults() {
DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
host_zoom_levels_.clear();
profile_->GetPrefs()->ClearPref(prefs::kPerHostZoomLevels);
}
HostZoomMap::~HostZoomMap() {
}
<commit_msg>One more place I forgot to lock.<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/host_zoom_map.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/profile.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/pref_service.h"
HostZoomMap::HostZoomMap(Profile* profile) : profile_(profile) {
const DictionaryValue* host_zoom_dictionary =
profile_->GetPrefs()->GetDictionary(prefs::kPerHostZoomLevels);
// Careful: The returned value could be NULL if the pref has never been set.
if (host_zoom_dictionary != NULL) {
for (DictionaryValue::key_iterator i(host_zoom_dictionary->begin_keys());
i != host_zoom_dictionary->end_keys(); ++i) {
std::wstring wide_host(*i);
int zoom_level = 0;
bool success = host_zoom_dictionary->GetIntegerWithoutPathExpansion(
wide_host, &zoom_level);
DCHECK(success);
host_zoom_levels_[WideToUTF8(wide_host)] = zoom_level;
}
}
}
// static
void HostZoomMap::RegisterUserPrefs(PrefService* prefs) {
prefs->RegisterDictionaryPref(prefs::kPerHostZoomLevels);
}
int HostZoomMap::GetZoomLevel(const std::string& host) const {
AutoLock auto_lock(lock_);
HostZoomLevels::const_iterator i(host_zoom_levels_.find(host));
return (i == host_zoom_levels_.end()) ? 0 : i->second;
}
void HostZoomMap::SetZoomLevel(const std::string& host, int level) {
DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
if (host.empty())
return;
{
AutoLock auto_lock(lock_);
if (level == 0)
host_zoom_levels_.erase(host);
else
host_zoom_levels_[host] = level;
}
DictionaryValue* host_zoom_dictionary =
profile_->GetPrefs()->GetMutableDictionary(prefs::kPerHostZoomLevels);
std::wstring wide_host(UTF8ToWide(host));
if (level == 0) {
host_zoom_dictionary->RemoveWithoutPathExpansion(wide_host, NULL);
} else {
host_zoom_dictionary->SetWithoutPathExpansion(wide_host,
Value::CreateIntegerValue(level));
}
}
void HostZoomMap::ResetToDefaults() {
DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
{
AutoLock auto_lock(lock_);
host_zoom_levels_.clear();
}
profile_->GetPrefs()->ClearPref(prefs::kPerHostZoomLevels);
}
HostZoomMap::~HostZoomMap() {
}
<|endoftext|> |
<commit_before><commit_msg>Invoke the right method (invokeDefault) if a plugin calls NPN_InvokeDefault on its own object.<commit_after><|endoftext|> |
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//------------------------------------------------------------------------------
// Description of the life cycle of a instance of MetricsService.
//
// OVERVIEW
//
// A MetricsService instance is created at ChromeFrame startup in
// the IE process. It is the central controller for the UMA log data.
// Its major job is to manage logs, prepare them for transmission.
// Currently only histogram data is tracked in log. When MetricsService
// prepares log for submission it snapshots the current stats of histograms,
// translates log to XML. Transmission includes submitting a compressed log
// as data in a URL-get, and is performed using functionality provided by
// Urlmon
// The actual transmission is performed using a windows timer procedure which
// basically means that the thread on which the MetricsService object is
// instantiated needs a message pump. Also on IE7 where every tab is created
// on its own thread we would have a case where the timer procedures can
// compete for sending histograms.
//
// When preparing log for submission we acquire a list of all local histograms
// that have been flagged for upload to the UMA server.
//
// When ChromeFrame shuts down, there will typically be a fragment of an ongoing
// log that has not yet been transmitted. Currently this data is ignored.
//
// With the above overview, we can now describe the state machine's various
// stats, based on the State enum specified in the state_ member. Those states
// are:
//
// INITIALIZED, // Constructor was called.
// ACTIVE, // Accumalating log data.
// STOPPED, // Service has stopped.
//
//-----------------------------------------------------------------------------
#include "chrome_frame/metrics_service.h"
#include <windows.h>
#include <objbase.h>
#if defined(USE_SYSTEM_LIBBZ2)
#include <bzlib.h>
#else
#include "third_party/bzip2/bzlib.h"
#endif
#include "base/file_version_info.h"
#include "base/string_util.h"
#include "base/thread.h"
#include "base/string_number_conversions.h"
#include "base/utf_string_conversions.h"
#include "chrome/common/chrome_version_info.h"
#include "chrome/installer/util/browser_distribution.h"
#include "chrome/installer/util/chrome_frame_distribution.h"
#include "chrome/installer/util/google_update_settings.h"
#include "chrome_frame/bind_status_callback_impl.h"
#include "chrome_frame/crash_reporting/crash_metrics.h"
#include "chrome_frame/utils.h"
#include "net/base/upload_data.h"
#include "chrome_frame/urlmon_bind_status_callback.h"
using base::Time;
using base::TimeDelta;
static const char kMetricsType[] =
"Content-Type: application/vnd.mozilla.metrics.bz2\r\n";
// The first UMA upload occurs after this interval.
static const int kInitialUMAUploadTimeoutMilliSeconds = 30000;
// Default to one UMA upload per 10 mins.
static const int kMinMilliSecondsPerUMAUpload = 600000;
base::LazyInstance<base::ThreadLocalPointer<MetricsService> >
MetricsService::g_metrics_instance_(base::LINKER_INITIALIZED);
extern base::LazyInstance<StatisticsRecorder> g_statistics_recorder_;
// This class provides functionality to upload the ChromeFrame UMA data to the
// server. An instance of this class is created whenever we have data to be
// uploaded to the server.
class ChromeFrameMetricsDataUploader : public BSCBImpl {
public:
ChromeFrameMetricsDataUploader()
: cache_stream_(NULL),
upload_data_size_(0) {
DLOG(INFO) << __FUNCTION__;
}
~ChromeFrameMetricsDataUploader() {
DLOG(INFO) << __FUNCTION__;
}
static HRESULT ChromeFrameMetricsDataUploader::UploadDataHelper(
const std::string& upload_data) {
CComObject<ChromeFrameMetricsDataUploader>* data_uploader = NULL;
CComObject<ChromeFrameMetricsDataUploader>::CreateInstance(&data_uploader);
DCHECK(data_uploader != NULL);
data_uploader->AddRef();
HRESULT hr = data_uploader->UploadData(upload_data);
if (FAILED(hr)) {
DLOG(ERROR) << "Failed to initialize ChromeFrame UMA data uploader: Err"
<< hr;
}
data_uploader->Release();
return hr;
}
HRESULT UploadData(const std::string& upload_data) {
if (upload_data.empty()) {
NOTREACHED() << "Invalid upload data";
return E_INVALIDARG;
}
DCHECK(cache_stream_.get() == NULL);
upload_data_size_ = upload_data.size() + 1;
HRESULT hr = CreateStreamOnHGlobal(NULL, TRUE, cache_stream_.Receive());
if (FAILED(hr)) {
NOTREACHED() << "Failed to create stream. Error:"
<< hr;
return hr;
}
DCHECK(cache_stream_.get());
unsigned long written = 0;
cache_stream_->Write(upload_data.c_str(), upload_data_size_, &written);
DCHECK(written == upload_data_size_);
RewindStream(cache_stream_);
BrowserDistribution* dist = ChromeFrameDistribution::GetDistribution();
server_url_ = dist->GetStatsServerURL();
DCHECK(!server_url_.empty());
hr = CreateURLMoniker(NULL, server_url_.c_str(),
upload_moniker_.Receive());
if (FAILED(hr)) {
DLOG(ERROR) << "Failed to create url moniker for url:"
<< server_url_.c_str()
<< " Error:"
<< hr;
} else {
ScopedComPtr<IBindCtx> context;
hr = CreateAsyncBindCtx(0, this, NULL, context.Receive());
DCHECK(SUCCEEDED(hr));
DCHECK(context);
ScopedComPtr<IStream> stream;
hr = upload_moniker_->BindToStorage(
context, NULL, IID_IStream,
reinterpret_cast<void**>(stream.Receive()));
if (FAILED(hr)) {
NOTREACHED();
DLOG(ERROR) << "Failed to bind to upload data moniker. Error:"
<< hr;
}
}
return hr;
}
STDMETHOD(BeginningTransaction)(LPCWSTR url, LPCWSTR headers, DWORD reserved,
LPWSTR* additional_headers) {
std::string new_headers;
new_headers = StringPrintf("Content-Length: %s\r\n",
base::Int64ToString(upload_data_size_).c_str());
new_headers += kMetricsType;
*additional_headers = reinterpret_cast<wchar_t*>(
CoTaskMemAlloc((new_headers.size() + 1) * sizeof(wchar_t)));
lstrcpynW(*additional_headers, ASCIIToWide(new_headers).c_str(),
new_headers.size());
return BSCBImpl::BeginningTransaction(url, headers, reserved,
additional_headers);
}
STDMETHOD(GetBindInfo)(DWORD* bind_flags, BINDINFO* bind_info) {
if ((bind_info == NULL) || (bind_info->cbSize == 0) ||
(bind_flags == NULL))
return E_INVALIDARG;
*bind_flags = BINDF_ASYNCHRONOUS | BINDF_ASYNCSTORAGE | BINDF_PULLDATA;
// Bypass caching proxies on POSTs and PUTs and avoid writing responses to
// these requests to the browser's cache
*bind_flags |= BINDF_GETNEWESTVERSION | BINDF_PRAGMA_NO_CACHE;
DCHECK(cache_stream_.get());
// Initialize the STGMEDIUM.
memset(&bind_info->stgmedData, 0, sizeof(STGMEDIUM));
bind_info->grfBindInfoF = 0;
bind_info->szCustomVerb = NULL;
bind_info->dwBindVerb = BINDVERB_POST;
bind_info->stgmedData.tymed = TYMED_ISTREAM;
bind_info->stgmedData.pstm = cache_stream_.get();
bind_info->stgmedData.pstm->AddRef();
return BSCBImpl::GetBindInfo(bind_flags, bind_info);
}
STDMETHOD(OnResponse)(DWORD response_code, LPCWSTR response_headers,
LPCWSTR request_headers, LPWSTR* additional_headers) {
DLOG(INFO) << __FUNCTION__ << " headers: \n" << response_headers;
return BSCBImpl::OnResponse(response_code, response_headers,
request_headers, additional_headers);
}
private:
std::wstring server_url_;
size_t upload_data_size_;
ScopedComPtr<IStream> cache_stream_;
ScopedComPtr<IMoniker> upload_moniker_;
};
MetricsService* MetricsService::GetInstance() {
if (g_metrics_instance_.Pointer()->Get())
return g_metrics_instance_.Pointer()->Get();
g_metrics_instance_.Pointer()->Set(new MetricsService);
return g_metrics_instance_.Pointer()->Get();
}
MetricsService::MetricsService()
: recording_active_(false),
reporting_active_(false),
user_permits_upload_(false),
state_(INITIALIZED),
thread_(NULL),
initial_uma_upload_(true),
transmission_timer_id_(0) {
}
MetricsService::~MetricsService() {
SetRecording(false);
if (pending_log_) {
delete pending_log_;
pending_log_ = NULL;
}
if (current_log_) {
delete current_log_;
current_log_ = NULL;
}
}
void MetricsService::InitializeMetricsState() {
DCHECK(state_ == INITIALIZED);
thread_ = PlatformThread::CurrentId();
user_permits_upload_ = GoogleUpdateSettings::GetCollectStatsConsent();
// Update session ID
session_id_ = CrashMetricsReporter::GetInstance()->IncrementMetric(
CrashMetricsReporter::SESSION_ID);
// Ensure that an instance of the StatisticsRecorder object is created.
g_statistics_recorder_.Get();
CrashMetricsReporter::GetInstance()->set_active(true);
}
// static
void MetricsService::Start() {
if (GetInstance()->state_ == ACTIVE)
return;
GetInstance()->InitializeMetricsState();
GetInstance()->SetRecording(true);
GetInstance()->SetReporting(true);
}
// static
void MetricsService::Stop() {
GetInstance()->SetReporting(false);
GetInstance()->SetRecording(false);
}
void MetricsService::SetRecording(bool enabled) {
DCHECK_EQ(thread_, PlatformThread::CurrentId());
if (enabled == recording_active_)
return;
if (enabled) {
if (client_id_.empty()) {
client_id_ = GenerateClientID();
// Save client id somewhere.
}
StartRecording();
} else {
state_ = STOPPED;
}
recording_active_ = enabled;
}
// static
std::string MetricsService::GenerateClientID() {
const int kGUIDSize = 39;
GUID guid;
HRESULT guid_result = CoCreateGuid(&guid);
DCHECK(SUCCEEDED(guid_result));
std::wstring guid_string;
int result = StringFromGUID2(guid,
WriteInto(&guid_string, kGUIDSize), kGUIDSize);
DCHECK(result == kGUIDSize);
return WideToUTF8(guid_string.substr(1, guid_string.length() - 2));
}
// static
void CALLBACK MetricsService::TransmissionTimerProc(HWND window,
unsigned int message,
unsigned int event_id,
unsigned int time) {
DLOG(INFO) << "Transmission timer notified";
DCHECK(GetInstance() != NULL);
GetInstance()->UploadData();
if (GetInstance()->initial_uma_upload_) {
// If this is the first uma upload by this process then subsequent uma
// uploads should occur once every 10 minutes(default).
GetInstance()->initial_uma_upload_ = false;
DCHECK(GetInstance()->transmission_timer_id_ != 0);
SetTimer(NULL, GetInstance()->transmission_timer_id_,
kMinMilliSecondsPerUMAUpload,
reinterpret_cast<TIMERPROC>(TransmissionTimerProc));
}
}
void MetricsService::SetReporting(bool enable) {
static const int kChromeFrameMetricsTimerId = 0xFFFFFFFF;
DCHECK_EQ(thread_, PlatformThread::CurrentId());
if (reporting_active_ != enable) {
reporting_active_ = enable;
if (reporting_active_) {
transmission_timer_id_ =
SetTimer(NULL, kChromeFrameMetricsTimerId,
kInitialUMAUploadTimeoutMilliSeconds,
reinterpret_cast<TIMERPROC>(TransmissionTimerProc));
}
}
}
//------------------------------------------------------------------------------
// Recording control methods
void MetricsService::StartRecording() {
DCHECK_EQ(thread_, PlatformThread::CurrentId());
if (current_log_)
return;
current_log_ = new MetricsLogBase(client_id_, session_id_,
GetVersionString());
if (state_ == INITIALIZED)
state_ = ACTIVE;
}
void MetricsService::StopRecording(bool save_log) {
DCHECK_EQ(thread_, PlatformThread::CurrentId());
if (!current_log_)
return;
// Put incremental histogram deltas at the end of all log transmissions.
// Don't bother if we're going to discard current_log_.
if (save_log) {
CrashMetricsReporter::GetInstance()->RecordCrashMetrics();
RecordCurrentHistograms();
}
if (save_log) {
pending_log_ = current_log_;
}
current_log_ = NULL;
}
void MetricsService::MakePendingLog() {
DCHECK_EQ(thread_, PlatformThread::CurrentId());
if (pending_log())
return;
switch (state_) {
case INITIALIZED: // We should be further along by now.
DCHECK(false);
return;
case ACTIVE:
StopRecording(true);
StartRecording();
break;
default:
DCHECK(false);
return;
}
DCHECK(pending_log());
}
bool MetricsService::TransmissionPermitted() const {
// If the user forbids uploading that's their business, and we don't upload
// anything.
return user_permits_upload_;
}
std::string MetricsService::PrepareLogSubmissionString() {
DCHECK_EQ(thread_, PlatformThread::CurrentId());
MakePendingLog();
DCHECK(pending_log());
if (pending_log_== NULL) {
return std::string();
}
pending_log_->CloseLog();
std::string pending_log_text = pending_log_->GetEncodedLogString();
DCHECK(!pending_log_text.empty());
DiscardPendingLog();
return pending_log_text;
}
bool MetricsService::UploadData() {
DCHECK_EQ(thread_, PlatformThread::CurrentId());
if (!GetInstance()->TransmissionPermitted())
return false;
static long currently_uploading = 0;
if (InterlockedCompareExchange(¤tly_uploading, 1, 0)) {
DLOG(INFO) << "Contention for uploading metrics data. Backing off";
return false;
}
std::string pending_log_text = PrepareLogSubmissionString();
DCHECK(!pending_log_text.empty());
// Allow security conscious users to see all metrics logs that we send.
LOG(INFO) << "METRICS LOG: " << pending_log_text;
bool ret = true;
if (!Bzip2Compress(pending_log_text, &compressed_log_)) {
NOTREACHED() << "Failed to compress log for transmission.";
ret = false;
} else {
HRESULT hr = ChromeFrameMetricsDataUploader::UploadDataHelper(
compressed_log_);
DCHECK(SUCCEEDED(hr));
}
DiscardPendingLog();
currently_uploading = 0;
return ret;
}
// static
std::string MetricsService::GetVersionString() {
chrome::VersionInfo version_info;
if (version_info.is_valid()) {
std::string version = version_info.Version();
// Add the -F extensions to ensure that UMA data uploaded by ChromeFrame
// lands in the ChromeFrame bucket.
version += "-F";
if (!version_info.IsOfficialBuild())
version.append("-devel");
return version;
} else {
NOTREACHED() << "Unable to retrieve version string.";
}
return std::string();
}
<commit_msg>Add ChromeFrame to the useragent string in outgoing UMA requests from ChromeFrame.<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.
//------------------------------------------------------------------------------
// Description of the life cycle of a instance of MetricsService.
//
// OVERVIEW
//
// A MetricsService instance is created at ChromeFrame startup in
// the IE process. It is the central controller for the UMA log data.
// Its major job is to manage logs, prepare them for transmission.
// Currently only histogram data is tracked in log. When MetricsService
// prepares log for submission it snapshots the current stats of histograms,
// translates log to XML. Transmission includes submitting a compressed log
// as data in a URL-get, and is performed using functionality provided by
// Urlmon
// The actual transmission is performed using a windows timer procedure which
// basically means that the thread on which the MetricsService object is
// instantiated needs a message pump. Also on IE7 where every tab is created
// on its own thread we would have a case where the timer procedures can
// compete for sending histograms.
//
// When preparing log for submission we acquire a list of all local histograms
// that have been flagged for upload to the UMA server.
//
// When ChromeFrame shuts down, there will typically be a fragment of an ongoing
// log that has not yet been transmitted. Currently this data is ignored.
//
// With the above overview, we can now describe the state machine's various
// stats, based on the State enum specified in the state_ member. Those states
// are:
//
// INITIALIZED, // Constructor was called.
// ACTIVE, // Accumalating log data.
// STOPPED, // Service has stopped.
//
//-----------------------------------------------------------------------------
#include "chrome_frame/metrics_service.h"
#include <windows.h>
#include <objbase.h>
#if defined(USE_SYSTEM_LIBBZ2)
#include <bzlib.h>
#else
#include "third_party/bzip2/bzlib.h"
#endif
#include "base/file_version_info.h"
#include "base/string_util.h"
#include "base/thread.h"
#include "base/string_number_conversions.h"
#include "base/utf_string_conversions.h"
#include "chrome/common/chrome_version_info.h"
#include "chrome/installer/util/browser_distribution.h"
#include "chrome/installer/util/chrome_frame_distribution.h"
#include "chrome/installer/util/google_update_settings.h"
#include "chrome_frame/bind_status_callback_impl.h"
#include "chrome_frame/crash_reporting/crash_metrics.h"
#include "chrome_frame/html_utils.h"
#include "chrome_frame/http_negotiate.h"
#include "chrome_frame/utils.h"
#include "net/base/upload_data.h"
#include "chrome_frame/urlmon_bind_status_callback.h"
using base::Time;
using base::TimeDelta;
static const char kMetricsType[] =
"Content-Type: application/vnd.mozilla.metrics.bz2\r\n";
// The first UMA upload occurs after this interval.
static const int kInitialUMAUploadTimeoutMilliSeconds = 30000;
// Default to one UMA upload per 10 mins.
static const int kMinMilliSecondsPerUMAUpload = 600000;
base::LazyInstance<base::ThreadLocalPointer<MetricsService> >
MetricsService::g_metrics_instance_(base::LINKER_INITIALIZED);
extern base::LazyInstance<StatisticsRecorder> g_statistics_recorder_;
// This class provides functionality to upload the ChromeFrame UMA data to the
// server. An instance of this class is created whenever we have data to be
// uploaded to the server.
class ChromeFrameMetricsDataUploader : public BSCBImpl {
public:
ChromeFrameMetricsDataUploader()
: cache_stream_(NULL),
upload_data_size_(0) {
DLOG(INFO) << __FUNCTION__;
}
~ChromeFrameMetricsDataUploader() {
DLOG(INFO) << __FUNCTION__;
}
static HRESULT ChromeFrameMetricsDataUploader::UploadDataHelper(
const std::string& upload_data) {
CComObject<ChromeFrameMetricsDataUploader>* data_uploader = NULL;
CComObject<ChromeFrameMetricsDataUploader>::CreateInstance(&data_uploader);
DCHECK(data_uploader != NULL);
data_uploader->AddRef();
HRESULT hr = data_uploader->UploadData(upload_data);
if (FAILED(hr)) {
DLOG(ERROR) << "Failed to initialize ChromeFrame UMA data uploader: Err"
<< hr;
}
data_uploader->Release();
return hr;
}
HRESULT UploadData(const std::string& upload_data) {
if (upload_data.empty()) {
NOTREACHED() << "Invalid upload data";
return E_INVALIDARG;
}
DCHECK(cache_stream_.get() == NULL);
upload_data_size_ = upload_data.size() + 1;
HRESULT hr = CreateStreamOnHGlobal(NULL, TRUE, cache_stream_.Receive());
if (FAILED(hr)) {
NOTREACHED() << "Failed to create stream. Error:"
<< hr;
return hr;
}
DCHECK(cache_stream_.get());
unsigned long written = 0;
cache_stream_->Write(upload_data.c_str(), upload_data_size_, &written);
DCHECK(written == upload_data_size_);
RewindStream(cache_stream_);
BrowserDistribution* dist = ChromeFrameDistribution::GetDistribution();
server_url_ = dist->GetStatsServerURL();
DCHECK(!server_url_.empty());
hr = CreateURLMoniker(NULL, server_url_.c_str(),
upload_moniker_.Receive());
if (FAILED(hr)) {
DLOG(ERROR) << "Failed to create url moniker for url:"
<< server_url_.c_str()
<< " Error:"
<< hr;
} else {
ScopedComPtr<IBindCtx> context;
hr = CreateAsyncBindCtx(0, this, NULL, context.Receive());
DCHECK(SUCCEEDED(hr));
DCHECK(context);
ScopedComPtr<IStream> stream;
hr = upload_moniker_->BindToStorage(
context, NULL, IID_IStream,
reinterpret_cast<void**>(stream.Receive()));
if (FAILED(hr)) {
NOTREACHED();
DLOG(ERROR) << "Failed to bind to upload data moniker. Error:"
<< hr;
}
}
return hr;
}
STDMETHOD(BeginningTransaction)(LPCWSTR url, LPCWSTR headers, DWORD reserved,
LPWSTR* additional_headers) {
std::string new_headers;
new_headers = StringPrintf("Content-Length: %s\r\n",
base::Int64ToString(upload_data_size_).c_str());
new_headers += kMetricsType;
std::string user_agent_value = http_utils::GetDefaultUserAgent();
user_agent_value = http_utils::AddChromeFrameToUserAgentValue(
user_agent_value);
new_headers += "User-Agent: " + user_agent_value;
new_headers += "\r\n";
*additional_headers = reinterpret_cast<wchar_t*>(
CoTaskMemAlloc((new_headers.size() + 1) * sizeof(wchar_t)));
lstrcpynW(*additional_headers, ASCIIToWide(new_headers).c_str(),
new_headers.size());
return BSCBImpl::BeginningTransaction(url, headers, reserved,
additional_headers);
}
STDMETHOD(GetBindInfo)(DWORD* bind_flags, BINDINFO* bind_info) {
if ((bind_info == NULL) || (bind_info->cbSize == 0) ||
(bind_flags == NULL))
return E_INVALIDARG;
*bind_flags = BINDF_ASYNCHRONOUS | BINDF_ASYNCSTORAGE | BINDF_PULLDATA;
// Bypass caching proxies on POSTs and PUTs and avoid writing responses to
// these requests to the browser's cache
*bind_flags |= BINDF_GETNEWESTVERSION | BINDF_PRAGMA_NO_CACHE;
DCHECK(cache_stream_.get());
// Initialize the STGMEDIUM.
memset(&bind_info->stgmedData, 0, sizeof(STGMEDIUM));
bind_info->grfBindInfoF = 0;
bind_info->szCustomVerb = NULL;
bind_info->dwBindVerb = BINDVERB_POST;
bind_info->stgmedData.tymed = TYMED_ISTREAM;
bind_info->stgmedData.pstm = cache_stream_.get();
bind_info->stgmedData.pstm->AddRef();
return BSCBImpl::GetBindInfo(bind_flags, bind_info);
}
STDMETHOD(OnResponse)(DWORD response_code, LPCWSTR response_headers,
LPCWSTR request_headers, LPWSTR* additional_headers) {
DLOG(INFO) << __FUNCTION__ << " headers: \n" << response_headers;
return BSCBImpl::OnResponse(response_code, response_headers,
request_headers, additional_headers);
}
private:
std::wstring server_url_;
size_t upload_data_size_;
ScopedComPtr<IStream> cache_stream_;
ScopedComPtr<IMoniker> upload_moniker_;
};
MetricsService* MetricsService::GetInstance() {
if (g_metrics_instance_.Pointer()->Get())
return g_metrics_instance_.Pointer()->Get();
g_metrics_instance_.Pointer()->Set(new MetricsService);
return g_metrics_instance_.Pointer()->Get();
}
MetricsService::MetricsService()
: recording_active_(false),
reporting_active_(false),
user_permits_upload_(false),
state_(INITIALIZED),
thread_(NULL),
initial_uma_upload_(true),
transmission_timer_id_(0) {
}
MetricsService::~MetricsService() {
SetRecording(false);
if (pending_log_) {
delete pending_log_;
pending_log_ = NULL;
}
if (current_log_) {
delete current_log_;
current_log_ = NULL;
}
}
void MetricsService::InitializeMetricsState() {
DCHECK(state_ == INITIALIZED);
thread_ = PlatformThread::CurrentId();
user_permits_upload_ = GoogleUpdateSettings::GetCollectStatsConsent();
// Update session ID
session_id_ = CrashMetricsReporter::GetInstance()->IncrementMetric(
CrashMetricsReporter::SESSION_ID);
// Ensure that an instance of the StatisticsRecorder object is created.
g_statistics_recorder_.Get();
CrashMetricsReporter::GetInstance()->set_active(true);
}
// static
void MetricsService::Start() {
if (GetInstance()->state_ == ACTIVE)
return;
GetInstance()->InitializeMetricsState();
GetInstance()->SetRecording(true);
GetInstance()->SetReporting(true);
}
// static
void MetricsService::Stop() {
GetInstance()->SetReporting(false);
GetInstance()->SetRecording(false);
}
void MetricsService::SetRecording(bool enabled) {
DCHECK_EQ(thread_, PlatformThread::CurrentId());
if (enabled == recording_active_)
return;
if (enabled) {
if (client_id_.empty()) {
client_id_ = GenerateClientID();
// Save client id somewhere.
}
StartRecording();
} else {
state_ = STOPPED;
}
recording_active_ = enabled;
}
// static
std::string MetricsService::GenerateClientID() {
const int kGUIDSize = 39;
GUID guid;
HRESULT guid_result = CoCreateGuid(&guid);
DCHECK(SUCCEEDED(guid_result));
std::wstring guid_string;
int result = StringFromGUID2(guid,
WriteInto(&guid_string, kGUIDSize), kGUIDSize);
DCHECK(result == kGUIDSize);
return WideToUTF8(guid_string.substr(1, guid_string.length() - 2));
}
// static
void CALLBACK MetricsService::TransmissionTimerProc(HWND window,
unsigned int message,
unsigned int event_id,
unsigned int time) {
DLOG(INFO) << "Transmission timer notified";
DCHECK(GetInstance() != NULL);
GetInstance()->UploadData();
if (GetInstance()->initial_uma_upload_) {
// If this is the first uma upload by this process then subsequent uma
// uploads should occur once every 10 minutes(default).
GetInstance()->initial_uma_upload_ = false;
DCHECK(GetInstance()->transmission_timer_id_ != 0);
SetTimer(NULL, GetInstance()->transmission_timer_id_,
kMinMilliSecondsPerUMAUpload,
reinterpret_cast<TIMERPROC>(TransmissionTimerProc));
}
}
void MetricsService::SetReporting(bool enable) {
static const int kChromeFrameMetricsTimerId = 0xFFFFFFFF;
DCHECK_EQ(thread_, PlatformThread::CurrentId());
if (reporting_active_ != enable) {
reporting_active_ = enable;
if (reporting_active_) {
transmission_timer_id_ =
SetTimer(NULL, kChromeFrameMetricsTimerId,
kInitialUMAUploadTimeoutMilliSeconds,
reinterpret_cast<TIMERPROC>(TransmissionTimerProc));
}
}
}
//------------------------------------------------------------------------------
// Recording control methods
void MetricsService::StartRecording() {
DCHECK_EQ(thread_, PlatformThread::CurrentId());
if (current_log_)
return;
current_log_ = new MetricsLogBase(client_id_, session_id_,
GetVersionString());
if (state_ == INITIALIZED)
state_ = ACTIVE;
}
void MetricsService::StopRecording(bool save_log) {
DCHECK_EQ(thread_, PlatformThread::CurrentId());
if (!current_log_)
return;
// Put incremental histogram deltas at the end of all log transmissions.
// Don't bother if we're going to discard current_log_.
if (save_log) {
CrashMetricsReporter::GetInstance()->RecordCrashMetrics();
RecordCurrentHistograms();
}
if (save_log) {
pending_log_ = current_log_;
}
current_log_ = NULL;
}
void MetricsService::MakePendingLog() {
DCHECK_EQ(thread_, PlatformThread::CurrentId());
if (pending_log())
return;
switch (state_) {
case INITIALIZED: // We should be further along by now.
DCHECK(false);
return;
case ACTIVE:
StopRecording(true);
StartRecording();
break;
default:
DCHECK(false);
return;
}
DCHECK(pending_log());
}
bool MetricsService::TransmissionPermitted() const {
// If the user forbids uploading that's their business, and we don't upload
// anything.
return user_permits_upload_;
}
std::string MetricsService::PrepareLogSubmissionString() {
DCHECK_EQ(thread_, PlatformThread::CurrentId());
MakePendingLog();
DCHECK(pending_log());
if (pending_log_== NULL) {
return std::string();
}
pending_log_->CloseLog();
std::string pending_log_text = pending_log_->GetEncodedLogString();
DCHECK(!pending_log_text.empty());
DiscardPendingLog();
return pending_log_text;
}
bool MetricsService::UploadData() {
DCHECK_EQ(thread_, PlatformThread::CurrentId());
if (!GetInstance()->TransmissionPermitted())
return false;
static long currently_uploading = 0;
if (InterlockedCompareExchange(¤tly_uploading, 1, 0)) {
DLOG(INFO) << "Contention for uploading metrics data. Backing off";
return false;
}
std::string pending_log_text = PrepareLogSubmissionString();
DCHECK(!pending_log_text.empty());
// Allow security conscious users to see all metrics logs that we send.
LOG(INFO) << "METRICS LOG: " << pending_log_text;
bool ret = true;
if (!Bzip2Compress(pending_log_text, &compressed_log_)) {
NOTREACHED() << "Failed to compress log for transmission.";
ret = false;
} else {
HRESULT hr = ChromeFrameMetricsDataUploader::UploadDataHelper(
compressed_log_);
DCHECK(SUCCEEDED(hr));
}
DiscardPendingLog();
currently_uploading = 0;
return ret;
}
// static
std::string MetricsService::GetVersionString() {
chrome::VersionInfo version_info;
if (version_info.is_valid()) {
std::string version = version_info.Version();
// Add the -F extensions to ensure that UMA data uploaded by ChromeFrame
// lands in the ChromeFrame bucket.
version += "-F";
if (!version_info.IsOfficialBuild())
version.append("-devel");
return version;
} else {
NOTREACHED() << "Unable to retrieve version string.";
}
return std::string();
}
<|endoftext|> |
<commit_before>#include <boost/python.hpp>
#include <vector>
typedef int player_id;
class TBT_game_core;
struct TBT_game_player
{
TBT_game_player(player_id p_id,TBT_game_core * core)
{
this->p_id = p_id;
this->game_core = core;
}
void do_turn(int hand);
player_id p_id;
TBT_game_core * game_core;
};
class TBT_game_core
{
public:
TBT_game_core()
{
initial_stage = true;
last_player_id = -1;
}
TBT_game_player& generate_new_player()
{
players.push_back(new TBT_game_player(++last_player_id,this));
return &(players[last_player_id]);
}
void end_initial_stage()
{
initial_stage = false;
current_turn_no = 0;
score = std::vector<int> (last_player_id,0);
current_turn = new std::vector<int>(last_player_id,0);
current_turn_done = std::vector<bool>(last_player_id,false);
}
void inform_turn_done(player_id id,int hand)
{
current_turn->at(id) = hand;
current_turn_done[id] = true;
check_next_turn();
}
player_id get_winner()
{
if (current_turn_no < 10)
return -1;
player_id maxi = 0;
for (int i = 0; i < last_player_id; i++)
if (score[i] > score[maxi])
maxi = i;
return maxi;
}
private:
void check_next_turn()
{
player_id i;
for (i=0;i<last_player_id;i++)
if (!current_turn_done[i])
return;
do_next_turn();
current_turn_done = std::vector<bool>(last_player_id,false);
old_turns.push_back(*current_turn);
current_turn = new std::vector<int> (last_player_id,0);
}
/*
All the logic is in here.
*
*/
void do_next_turn()
{
for (player_id i = 0;i<last_player_id;i++)
for (player_id j=0;i<last_player_id;j++)
if (current_turn->at(i) == (current_turn->at(j)+1)%3)
score[i]++;
}
bool initial_stage;
player_id last_player_id;
int current_turn_no;
std::vector<TBT_game_player> players;
std::vector<int> score;
std::vector<int> * current_turn;
std::vector<bool> current_turn_done;
std::vector< std::vector<int> > old_turns;
};
void TBT_game_player::do_turn(int hand)
{
this->game_core->inform_turn_done(this->p_id,hand);
}
using namespace boost::python;
BOOST_PYTHON_MODULE(libtbtg)
{
class_<TBT_game_core>("TBT_game_core")
.def("end_initial_stage", &TBT_game_core::end_initial_stage)
.def("inform_turn_done", &TBT_game_core::inform_turn_done)
.def("get_winner", &TBT_game_core::get_winner)
.def("generate_new_player", &TBT_game_core::generate_new_player)
;
class_<TBT_game_player>("TBT_game_player", init<player_id,TBT_game_core*>())
.def("do_turn", &TBT_game_player::do_turn)
;
}
<commit_msg>fixing shivs bugs<commit_after>#include <boost/python.hpp>
#include <vector>
using namespace boost::python;
typedef int player_id;
class TBT_game_core;
struct TBT_game_player
{
TBT_game_player(player_id p_id,TBT_game_core * core)
{
this->p_id = p_id;
this->game_core = core;
}
void do_turn(int hand);
player_id p_id;
TBT_game_core * game_core;
};
struct TBT_game_player_python
{
static PyObject* convert(TBT_game_player const& p)
{
return boost::python::incref(boost::python::object(p).ptr());
}
};
class TBT_game_core
{
public:
TBT_game_core()
{
initial_stage = true;
last_player_id = -1;
}
PyObject * generate_new_player()
{
players.push_back(*(new TBT_game_player(++last_player_id, this)));
return TBT_game_player_python::convert(players[last_player_id]);
}
void end_initial_stage()
{
initial_stage = false;
current_turn_no = 0;
score = std::vector<int> (last_player_id + 1, 0);
current_turn = new std::vector<int>(last_player_id + 1, 0);
current_turn_done = std::vector<bool>(last_player_id + 1,false);
}
void inform_turn_done(player_id id,int hand)
{
current_turn->at(id) = hand;
current_turn_done[id] = true;
check_next_turn();
}
player_id get_winner()
{
if (current_turn_no < 10)
return -1;
player_id maxi = 0;
for (int i = 0; i < last_player_id; i++)
if (score[i] > score[maxi])
maxi = i;
return maxi;
}
private:
void check_next_turn()
{
player_id i;
for (i=0;i<last_player_id;i++)
if (!current_turn_done[i])
return;
do_next_turn();
current_turn_done = std::vector<bool>(last_player_id,false);
old_turns.push_back(*current_turn);
current_turn = new std::vector<int> (last_player_id,0);
}
/*
All the logic is in here.
*
*/
void do_next_turn()
{
for (player_id i = 0;i<last_player_id;i++)
for (player_id j=0;i<last_player_id;j++)
if (current_turn->at(i) == (current_turn->at(j)+1)%3)
score[i]++;
}
bool initial_stage;
player_id last_player_id;
int current_turn_no;
std::vector<TBT_game_player> players;
std::vector<int> score;
std::vector<int> * current_turn;
std::vector<bool> current_turn_done;
std::vector< std::vector<int> > old_turns;
};
void TBT_game_player::do_turn(int hand)
{
this->game_core->inform_turn_done(this->p_id, hand);
}
BOOST_PYTHON_MODULE(libtbtg)
{
boost::python::to_python_converter<
TBT_game_player,
TBT_game_player_python>();
class_<TBT_game_core>("TBT_game_core")
.def("end_initial_stage", &TBT_game_core::end_initial_stage)
.def("inform_turn_done", &TBT_game_core::inform_turn_done)
.def("get_winner", &TBT_game_core::get_winner)
.def("generate_new_player", &TBT_game_core::generate_new_player)
;
class_<TBT_game_player>("TBT_game_player", init<player_id,TBT_game_core*>())
.def("do_turn", &TBT_game_player::do_turn)
;
}
<|endoftext|> |
<commit_before>// Copyright 2013 Sean McKenna
//
// 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.
//
// light sub-classes (e.g. generic, ambient, direct, point)
// originally adapted from code provided by Cem Yuksel
// namespace
using namespace scene;
namespace scene{
// generic light definition (from main light class)
class GenericLight: public Light{
public:
// calculate a shadow for any light (never call from ambient!)
float shadow(Cone ray, float z = FLOAT_MAX){
// set initial hit info
HitInfo h = HitInfo();
h.z = z;
// check ray from point to light, is it occluded?
bool occlude = traceRay(ray, h);
// return 0 if in shadow, 1 if lit directly
if(occlude)
return 0.0;
else
return 1.0;
}
};
// ambient light definition
class AmbientLight: public GenericLight{
public:
// constructor
AmbientLight(){
intensity.Set(0, 0, 0);
}
// get color of ambient light
Color illuminate(Point p){
return intensity;
}
// get direction of ambient light (non-sensical)
Point direction(Point p){
return Point(0, 0, 0);
}
// return true, since light is ambient
bool isAmbient(){
return true;
}
// set color of ambient light
void setIntensity(Color c){
intensity = c;
}
private:
// intensity (or color) of light
Color intensity;
};
// direct light definition
class DirectLight: public GenericLight{
public:
// constructor
DirectLight(){
intensity.Set(0, 0, 0);
dir.Set(0, 0, 1);
}
// get color of direct light (check for shadows)
Color illuminate(Point p){
Cone r = Cone();
r.pos = p;
r.dir = -dir;
return shadow(r) * intensity;
}
// get direction of direct light (constant)
Point direction(Point p){
return dir;
}
// set color of direct light
void setIntensity(Color c){
intensity = c;
}
// set direction of direct light
void setDirection(Point d){
dir = d.GetNormalized();
}
private:
// intensity (or color) of light
Color intensity;
// direction of light
Point dir;
};
// point light definition
class PointLight: public GenericLight{
public:
// constructor
PointLight(){
intensity.Set(0, 0, 0);
position.Set(0, 0, 0);
size = 0.0;
}
// get color of point light (check for shadows)
Color illuminate(Point p){
if(size == 0.0){
Cone r = Cone();
r.pos = p;
r.dir = position - p;
return shadow(r, 1.0) * intensity;
// otherwise, we have a spherical light, cast multiple shadow rays
}else{
// to detect if we are in the penumbra
bool penumbra = false;
// keep track of running shadow variables
int count;
float mean = 0.0;
// calculate random rotation for Halton sequence on our sphere of confusion
float rotate = dist(rnd) * 2.0 * M_PI;
// cast our minmum number of shadow rays
for(count = 0; count < shadowMin; count++){
// calculate (partially) randomized shadow ray
Cone r = getShadowRay(p, count, rotate);
// cast shadow ray
int val = shadow(r, 1.0);
// update our mean shadow value
mean = ((float) (mean * count + val)) / ((float) (count + 1));
// check if we are in penumbra
if(mean != 0.0 && mean != 1.0)
penumbra = true;
}
// continue casting more shadow rays, if in penumbra
if(penumbra){
// continue casting shadow rays
for(count = shadowMin; count < shadowMax; count++){
// calculate (partially) randomized shadow ray
Cone r = getShadowRay(p, count, rotate);
// cast shadow ray
int val = shadow(r, 1.0);
// update our mean shadow value
mean = ((float) (mean * count + val)) / ((float) (count + 1));
}
}
// return our final shaded intensity
return mean * intensity;
}
}
// get direction of point light (calculated)
Point direction(Point p){
return (p - position).GetNormalized();
}
// set color of point light
void setIntensity(Color c){
intensity = c;
}
// set the location of the point light
void setPosition(Point pos){
position = pos;
}
// set the size of the point light (now a sphere)
void setSize(float s){
size = s;
}
// set shadow ray samples (min & max)
void setShadowRays(int min, int max){
shadowMin = min;
shadowMax = max;
}
private:
// intensity (or color) of light
Color intensity;
// location of light
Point position;
// size of point light (sphere if not zero)
float size;
// how many shadow rays to cast
int shadowMin;
int shadowMax;
// random number generation for light disk rotation
mt19937 rnd;
uniform_real_distribution<float> dist{0.0, 1.0};
// calculate a randomized light position on a spherical light
Cone getShadowRay(Point p, int c, float r){
// get original direction
Point dir = (position - p).GetNormalized();
// get two vectors for spanning our light disk
Point v0 = Point(0.0, 1.0, 0.0);
if(v0 % dir < 0.1 && v0 % dir > -0.1)
v0 = Point(0.0, 0.0, 1.0);
Point v1 = (v0 ^ dir).GetNormalized();
// grab Halton sequence to shift point along light disk
// first four points on the perimeter of the disk
float diskRad;
if(c < 4)
diskRad = 1.0 * size;
else
diskRad = sqrt(Halton(c - 4, 2)) * size;
// grab Halton sequence to shift point around light disk
// first four points will be distributed about the perimeter
float diskRot;
if(c == 0)
diskRot = 0.0;
else if(c == 1)
diskRot = 1.0 * M_PI;
else if(c == 2)
diskRot = 0.5 * M_PI;
else if(c == 3)
diskRot = 1.5 * M_PI;
else
diskRot = Halton(c - 4, 3) * 2.0 * M_PI;
// compute our semi-random position inside the disk
Point pos = position + (v0 * diskRad * cos(diskRot + r)) + (v1 * diskRad * sin(diskRot + r));
// shadow ray to return
Cone ray = Cone();
ray.pos = p;
ray.dir = pos - p;
return ray;
}
};
}
<commit_msg>update shadow ray calculation, better vectors to span light disk<commit_after>// Copyright 2013 Sean McKenna
//
// 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.
//
// light sub-classes (e.g. generic, ambient, direct, point)
// originally adapted from code provided by Cem Yuksel
// namespace
using namespace scene;
namespace scene{
// generic light definition (from main light class)
class GenericLight: public Light{
public:
// calculate a shadow for any light (never call from ambient!)
float shadow(Cone ray, float z = FLOAT_MAX){
// set initial hit info
HitInfo h = HitInfo();
h.z = z;
// check ray from point to light, is it occluded?
bool occlude = traceRay(ray, h);
// return 0 if in shadow, 1 if lit directly
if(occlude)
return 0.0;
else
return 1.0;
}
};
// ambient light definition
class AmbientLight: public GenericLight{
public:
// constructor
AmbientLight(){
intensity.Set(0, 0, 0);
}
// get color of ambient light
Color illuminate(Point p){
return intensity;
}
// get direction of ambient light (non-sensical)
Point direction(Point p){
return Point(0, 0, 0);
}
// return true, since light is ambient
bool isAmbient(){
return true;
}
// set color of ambient light
void setIntensity(Color c){
intensity = c;
}
private:
// intensity (or color) of light
Color intensity;
};
// direct light definition
class DirectLight: public GenericLight{
public:
// constructor
DirectLight(){
intensity.Set(0, 0, 0);
dir.Set(0, 0, 1);
}
// get color of direct light (check for shadows)
Color illuminate(Point p){
Cone r = Cone();
r.pos = p;
r.dir = -dir;
return shadow(r) * intensity;
}
// get direction of direct light (constant)
Point direction(Point p){
return dir;
}
// set color of direct light
void setIntensity(Color c){
intensity = c;
}
// set direction of direct light
void setDirection(Point d){
dir = d.GetNormalized();
}
private:
// intensity (or color) of light
Color intensity;
// direction of light
Point dir;
};
// point light definition
class PointLight: public GenericLight{
public:
// constructor
PointLight(){
intensity.Set(0, 0, 0);
position.Set(0, 0, 0);
size = 0.0;
}
// get color of point light (check for shadows)
Color illuminate(Point p){
if(size == 0.0){
Cone r = Cone();
r.pos = p;
r.dir = position - p;
return shadow(r, 1.0) * intensity;
// otherwise, we have a spherical light, cast multiple shadow rays
}else{
// to detect if we are in the penumbra
bool penumbra = false;
// keep track of running shadow variables
int count;
float mean = 0.0;
// calculate random rotation for Halton sequence on our sphere of confusion
float rotate = dist(rnd) * 2.0 * M_PI;
// cast our minmum number of shadow rays
for(count = 0; count < shadowMin; count++){
// calculate (partially) randomized shadow ray
Cone r = getShadowRay(p, count, rotate);
// cast shadow ray
int val = shadow(r, 1.0);
// update our mean shadow value
mean = ((float) (mean * count + val)) / ((float) (count + 1));
// check if we are in penumbra
if(mean != 0.0 && mean != 1.0)
penumbra = true;
}
// continue casting more shadow rays, if in penumbra
if(penumbra){
// continue casting shadow rays
for(count = shadowMin; count < shadowMax; count++){
// calculate (partially) randomized shadow ray
Cone r = getShadowRay(p, count, rotate);
// cast shadow ray
int val = shadow(r, 1.0);
// update our mean shadow value
mean = ((float) (mean * count + val)) / ((float) (count + 1));
}
}
// return our final shaded intensity
return mean * intensity;
}
}
// get direction of point light (calculated)
Point direction(Point p){
return (p - position).GetNormalized();
}
// set color of point light
void setIntensity(Color c){
intensity = c;
}
// set the location of the point light
void setPosition(Point pos){
position = pos;
}
// set the size of the point light (now a sphere)
void setSize(float s){
size = s;
}
// set shadow ray samples (min & max)
void setShadowRays(int min, int max){
shadowMin = min;
shadowMax = max;
}
private:
// intensity (or color) of light
Color intensity;
// location of light
Point position;
// size of point light (sphere if not zero)
float size;
// how many shadow rays to cast
int shadowMin;
int shadowMax;
// random number generation for light disk rotation
mt19937 rnd;
uniform_real_distribution<float> dist{0.0, 1.0};
// calculate a randomized light position on a spherical light
Cone getShadowRay(Point p, int c, float r){
// get original direction
Point dir = (position - p).GetNormalized();
// get two vectors for spanning our light disk
Point v0 = Point(0.0, 1.0, 0.0);
if(v0 % dir < 0.5 && v0 % dir > -0.5)
v0 = Point(0.0, 0.0, 1.0);
Point v1 = (v0 ^ dir).GetNormalized();
// grab Halton sequence to shift point along light disk
// first four points on the perimeter of the disk
float diskRad;
if(c < 4)
diskRad = 1.0 * size;
else
diskRad = sqrt(Halton(c - 4, 2)) * size;
// grab Halton sequence to shift point around light disk
// first four points will be distributed about the perimeter
float diskRot;
if(c == 0)
diskRot = 0.0;
else if(c == 1)
diskRot = 1.0 * M_PI;
else if(c == 2)
diskRot = 0.5 * M_PI;
else if(c == 3)
diskRot = 1.5 * M_PI;
else
diskRot = Halton(c - 4, 3) * 2.0 * M_PI;
// compute our semi-random position inside the disk
Point pos = position + (v0 * diskRad * cos(diskRot + r)) + (v1 * diskRad * sin(diskRot + r));
// shadow ray to return
Cone ray = Cone();
ray.pos = p;
ray.dir = pos - p;
return ray;
}
};
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <cstdlib> // exit()
#include <cstdio> // printf()
#include <cstring> // strcmp()
#include <string>
#include <stack>
#include <openssl/sha.h>
#include <byteswap.h>
#include "alphabet.h"
using namespace std;
string pwd;
char pwdHash[SHA256_DIGEST_LENGTH];
char bruteHash[SHA256_DIGEST_LENGTH];
static const unsigned char MaxChars = 3;
void printSHAHash(unsigned int* pbuf)
{
// byteswap the integer pointed to, to display hex dump in correct order
// TODO: how to deal with big endian machines
printf("%X%X%X%X%X%X%X%X\n",
bswap_32(*(pbuf)),
bswap_32(*(pbuf+1)),
bswap_32(*(pbuf+2)),
bswap_32(*(pbuf+3)),
bswap_32(*(pbuf+4)),
bswap_32(*(pbuf+5)),
bswap_32(*(pbuf+6)),
bswap_32(*(pbuf+7))
);
}
bool generateSHA256(const void *const inputStr, const size_t &length, char *const hashStr)
{
SHA256_CTX hash;
if(!SHA256_Init(&hash))
{
return false;
}
if(!SHA256_Update(&hash, inputStr, length))
{
return false;
}
if(!SHA256_Final(reinterpret_cast<unsigned char*>(hashStr), &hash))
{
return false;
}
return true;
}
void checkPassword(const string &password)
{
//#ifdef VERBOSE
cout << "checking " << password << endl;
//#endif // VERBOSE
// generate sha hash from entered string and write it to pwdHash
if(!generateSHA256(password.c_str(), password.length(), bruteHash))
{
cerr << "Error when generating SHA256 from \"" << password << "\"" << endl;
//return;
}
if (!memcmp(bruteHash, pwdHash, SHA256_DIGEST_LENGTH))
{
cout << "match [" << password << "]" << endl << "hash: " << endl;
printSHAHash((unsigned int*)bruteHash);
exit(0);
}
}
void bruteRecursive(const string baseString, const unsigned int width)
{
for(int i=0; i<SizeAlphabet; i++)
{
if (baseString.length()+1 < width)
{
bruteRecursive(baseString+alphabet[i], width);
}
checkPassword(baseString+alphabet[i]);
}
}
void bruteIterative(const unsigned int width)
{
stack<string> myStack;
// myStack must contain at least one element when entering loop
// else: SIGSEGV
// hence, start checking with an empty string
myStack.push("");
do
{
string baseString = myStack.top();
myStack.pop();
cout << "checking passwords with " << baseString.length()+1 << " characters..." << endl;
for(int i=0; i<SizeAlphabet; i++)
{
if (baseString.length()+1 < width)
{
myStack.push(baseString+alphabet[i]);
}
checkPassword(baseString+alphabet[i]);
}
}
while(!myStack.empty());
}
int main()
{
cout << "Enter a string: " << endl;
cin >> pwd;
// generate sha hash from entered string and write it to pwdHash
if(!generateSHA256(pwd.c_str(), pwd.length(), pwdHash))
{
cerr << "Error when generating SHA256 from \"" << pwd << "\"" << endl;
return -2;
}
else
{
printf("SHA256 Hash for your string is:\n");
printSHAHash((unsigned int*)pwdHash);
}
cout << "checking using Recusive Method" << endl;
for(int i=1; i<=MaxChars; i++)
{
cout << "checking passwords with " << i << " characters..." << endl;
bruteRecursive(string(""),i);
}
cout << "checking using Iterative Method" << endl;
bruteIterative(MaxChars);
return -1;
}
<commit_msg>added lots of comments<commit_after>#include <iostream>
#include <cstdlib> // exit()
#include <cstdio> // printf()
#include <cstring> // memcmp()
#include <string>
#include <stack>
#include <openssl/sha.h>
#include <byteswap.h>
#include "alphabet.h"
using namespace std;
// clear text password entered by user
string pwd;
// contains the hash of the unknown password
char pwdHash[SHA256_DIGEST_LENGTH];
// contains the hash of a bruteforced string
char bruteHash[SHA256_DIGEST_LENGTH];
// the maximum number of characters bruteforce shall check
static const unsigned char MaxChars = 3;
/**
* @brief prints 32 bytes of memory
*
* prints a hex dump of 32 bytes of memory pointed to
*
* @param[in] pbuf: pointer to some memory, usually containing an SHA256 hash
*/
void printSHAHash(const unsigned int *const pbuf)
{
// byteswap the integer pointed to, to display hex dump in correct order
// TODO: how to deal with big endian machines
printf("%X%X%X%X%X%X%X%X\n",
bswap_32(*(pbuf)),
bswap_32(*(pbuf+1)),
bswap_32(*(pbuf+2)),
bswap_32(*(pbuf+3)),
bswap_32(*(pbuf+4)),
bswap_32(*(pbuf+5)),
bswap_32(*(pbuf+6)),
bswap_32(*(pbuf+7))
);
}
/**
* @brief generates an SHA256 hash
*
* generates an SHA256 hash using openSSL
*
* @param[in] input: a const pointer to const block of data, usually a char array of which the hash is being generated
* @param[in] length: the number of bytes the that input points to holds
* @param[in,out] hashStr: const pointer to an array of SHA256_DIGEST_LENGTH bytes that will receive the hash
*
* @return returns true if the hash has been generated successfully; returns false if input or hashStr is NULL or length==0; else: false
*/
bool generateSHA256(const void *const input, const size_t &length, char *const hashStr)
{
if(!hashStr || !input || length==0)
{
return false;
}
SHA256_CTX hash;
if(!SHA256_Init(&hash))
{
return false;
}
if(!SHA256_Update(&hash, input, length))
{
return false;
}
if(!SHA256_Final(reinterpret_cast<unsigned char*>(hashStr), &hash))
{
return false;
}
return true;
}
/**
* @brief checks equality of two hashes
*
* calculates the SHA256 hash of 'password' and compares it
* with the initial password hash
*
* @param[in] password: a const string containing a guessed password
*/
void checkPassword(const string &password)
{
//#ifdef VERBOSE
cout << "checking " << password << endl;
//#endif // VERBOSE
// generate sha hash from entered string and write it to pwdHash
if(!generateSHA256(password.c_str(), password.length(), bruteHash))
{
cerr << "Error when generating SHA256 from \"" << password << "\"" << endl;
//return;
}
if (!memcmp(bruteHash, pwdHash, SHA256_DIGEST_LENGTH))
{
cout << "match [" << password << "]" << endl << "hash: " << endl;
printSHAHash((unsigned int*)bruteHash);
exit(0);
}
}
/**
* @brief recursive implementation of bruteforce
*
* recursive implementation of bruteforce attack
* call it as follows: bruteRecursive(string(""), width);
*
* @param[in] baseString: a const string indicates the prefix of a string to be checked
* @param[in] width: the maximum number of characters you wish to be checked
*/
void bruteRecursive(const string baseString, const unsigned int width)
{
for(int i=0; i<SizeAlphabet; i++)
{
if (baseString.length()+1 < width)
{
bruteRecursive(baseString+alphabet[i], width);
}
checkPassword(baseString+alphabet[i]);
}
}
/**
* @brief iterative implementation of bruteforce
*
* iterative implementation of bruteforce attack
* call it as follows: bruteIterative(width);
*
* @param[in] width: the maximum number of characters you wish to be checked
*/
void bruteIterative(const unsigned int width)
{
stack<string> myStack;
// myStack must contain at least one element when entering loop
// else: SIGSEGV
// hence, start checking with an empty string
myStack.push("");
do
{
string baseString = myStack.top();
myStack.pop();
cout << "checking passwords with " << baseString.length()+1 << " characters..." << endl;
for(int i=0; i<SizeAlphabet; i++)
{
if (baseString.length()+1 < width)
{
myStack.push(baseString+alphabet[i]);
}
checkPassword(baseString+alphabet[i]);
}
}
while(!myStack.empty());
}
int main()
{
cout << "Enter a string: " << endl;
cin >> pwd;
// generate sha hash from entered string and write it to pwdHash
if(!generateSHA256(pwd.c_str(), pwd.length(), pwdHash))
{
cerr << "Error when generating SHA256 from \"" << pwd << "\"" << endl;
return -2;
}
else
{
printf("SHA256 Hash for your string is:\n");
printSHAHash((unsigned int*)pwdHash);
}
cout << "checking using Recusive Method" << endl;
for(int i=1; i<=MaxChars; i++)
{
cout << "checking passwords with " << i << " characters..." << endl;
bruteRecursive(string(""),i);
}
cout << "checking using Iterative Method" << endl;
bruteIterative(MaxChars);
return -1;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <immintrin.h>
#include <new>
#include <cassert>
#include <sstream>
#include "simd_util.h"
#include "pauli_string.h"
#include <cstring>
#include <cstdlib>
#include <bit>
PauliStringPtr::PauliStringPtr(
size_t init_size,
BitPtr init_sign,
uint64_t *init_x,
uint64_t *init_z,
size_t init_stride256) :
size(init_size),
bit_ptr_sign(init_sign),
_x(init_x),
_z(init_z),
stride256(init_stride256) {
}
PauliStringVal::PauliStringVal(size_t init_size) :
val_sign(false),
x_data(init_size),
z_data(init_size) {
}
PauliStringVal::PauliStringVal(const PauliStringPtr &other) :
val_sign(other.bit_ptr_sign.get()),
x_data(other.size, other._x),
z_data(other.size, other._z) {
}
PauliStringPtr PauliStringVal::ptr() const {
return PauliStringPtr(*this);
}
std::string PauliStringVal::str() const {
return ptr().str();
}
void PauliStringPtr::swap_with(PauliStringPtr &other) {
assert(size == other.size);
bit_ptr_sign.swap(other.bit_ptr_sign);
auto x256 = (__m256i *)_x;
auto z256 = (__m256i *)_z;
auto ox256 = (__m256i *)other._x;
auto oz256 = (__m256i *)other._z;
auto end = &x256[num_words256() * stride256];
while (x256 != end) {
std::swap(*x256, *ox256);
std::swap(*z256, *oz256);
x256 += stride256;
z256 += stride256;
ox256 += other.stride256;
oz256 += other.stride256;
}
}
void PauliStringPtr::overwrite_with(const PauliStringPtr &other) {
assert(size == other.size);
bit_ptr_sign.set(other.bit_ptr_sign.get());
auto x256 = (__m256i *)_x;
auto z256 = (__m256i *)_z;
auto ox256 = (__m256i *)other._x;
auto oz256 = (__m256i *)other._z;
auto end = &x256[num_words256() * stride256];
while (x256 != end) {
*x256 = *ox256;
*z256 = *oz256;
x256 += stride256;
z256 += stride256;
ox256 += other.stride256;
oz256 += other.stride256;
}
}
PauliStringVal& PauliStringVal::operator=(const PauliStringPtr &other) noexcept {
(*this).~PauliStringVal();
new(this) PauliStringVal(other);
return *this;
}
PauliStringPtr::PauliStringPtr(const PauliStringVal &other) :
size(other.x_data.num_bits),
bit_ptr_sign(BitPtr((void *)&other.val_sign, 0)),
_x(other.x_data.u64),
_z(other.z_data.u64),
stride256(1) {
}
uint8_t PauliStringPtr::log_i_scalar_byproduct(const PauliStringPtr &other) const {
assert(size == other.size);
union {__m256i u256; uint64_t u64[4]; } cnt1 {};
union {__m256i u256; uint64_t u64[4]; } cnt2 {};
auto x256 = (__m256i *)_x;
auto z256 = (__m256i *)_z;
auto ox256 = (__m256i *)other._x;
auto oz256 = (__m256i *)other._z;
auto end = &x256[num_words256() * stride256];
while (x256 != end) {
auto x1 = *x256;
auto z2 = *oz256;
auto z1 = *z256;
auto x2 = *ox256;
auto t1 = x1 & z2;
auto t2 = x2 & z1;
auto f = t1 ^ t2;
auto b = ((x1 ^ z2) & t2) ^ _mm256_andnot_si256(z1, _mm256_andnot_si256(x2, t1));
cnt1.u256 ^= b;
cnt2.u256 ^= cnt1.u256 & f;
cnt1.u256 ^= f ^ b;
x256 += stride256;
z256 += stride256;
ox256 += other.stride256;
oz256 += other.stride256;
}
size_t s = 0;
for (size_t k = 0; k < 4; k++) {
s += (uint8_t) std::popcount(cnt1.u64[k]);
s ^= (uint8_t) std::popcount(cnt2.u64[k]) << 1;
}
return s & 3;
}
std::string PauliStringPtr::str() const {
std::stringstream ss;
ss << *this;
return ss.str();
}
bool PauliStringPtr::operator==(const PauliStringPtr &other) const {
if (size != other.size || bit_ptr_sign.get() != other.bit_ptr_sign.get()) {
return false;
}
__m256i acc {};
auto x256 = (__m256i *)_x;
auto z256 = (__m256i *)_z;
auto ox256 = (__m256i *)other._x;
auto oz256 = (__m256i *)other._z;
auto end = &x256[num_words256() * stride256];
while (x256 != end) {
acc |= *x256 ^ *ox256;
acc |= *z256 ^ *oz256;
x256 += stride256;
z256 += stride256;
ox256 += other.stride256;
oz256 += other.stride256;
}
auto acc64 = (uint64_t *)&acc;
for (size_t k = 0; k < 4; k++) {
if (acc64[k]) {
return false;
}
}
return true;
}
bool PauliStringPtr::operator!=(const PauliStringPtr &other) const {
return !(*this == other);
}
std::ostream &operator<<(std::ostream &out, const PauliStringVal &ps) {
return out << ps.ptr();
}
size_t PauliStringPtr::num_words256() const {
return ceil256(size) >> 8;
}
std::ostream &operator<<(std::ostream &out, const PauliStringPtr &ps) {
out << (ps.bit_ptr_sign.get() ? '-' : '+');
auto x256 = (__m256i *)ps._x;
auto z256 = (__m256i *)ps._z;
auto end = &x256[ps.num_words256() * ps.stride256];
size_t remaining = ps.size;
while (x256 != end) {
auto xs = m256i_to_bits(*x256);
auto zs = m256i_to_bits(*z256);
for (int j = 0; j < 256 && remaining; j++) {
out << "_XZY"[xs[j] + 2 * zs[j]];
remaining--;
}
x256 += ps.stride256;
z256 += ps.stride256;
}
return out;
}
PauliStringVal PauliStringVal::from_pattern(bool sign, size_t size, const std::function<char(size_t)> &func) {
PauliStringVal result(size);
result.val_sign = sign;
for (size_t i = 0; i < size; i++) {
char c = func(i);
bool x;
bool z;
if (c == 'X') {
x = true;
z = false;
} else if (c == 'Y') {
x = true;
z = true;
} else if (c == 'Z') {
x = false;
z = true;
} else if (c == '_' || c == 'I') {
x = false;
z = false;
} else {
throw std::runtime_error("Unrecognized pauli character. " + std::to_string(c));
}
result.x_data.u64[i / 64] ^= (uint64_t)x << (i & 63);
result.z_data.u64[i / 64] ^= (uint64_t)z << (i & 63);
}
return result;
}
PauliStringVal PauliStringVal::from_str(const char *text) {
auto sign = text[0] == '-';
if (text[0] == '+' || text[0] == '-') {
text++;
}
return PauliStringVal::from_pattern(sign, strlen(text), [&](size_t i){ return text[i]; });
}
PauliStringVal PauliStringVal::identity(size_t size) {
return PauliStringVal(size);
}
PauliStringPtr& PauliStringPtr::operator*=(const PauliStringPtr& rhs) {
uint8_t log_i = inplace_right_mul_with_scalar_output(rhs);
assert((log_i & 1) == 0);
bit_ptr_sign.toggle_if(log_i & 2);
return *this;
}
uint8_t PauliStringPtr::inplace_right_mul_with_scalar_output(const PauliStringPtr& rhs) {
uint8_t result = log_i_scalar_byproduct(rhs);
result ^= (uint8_t)rhs.bit_ptr_sign.get() << 1;
auto x256 = (__m256i *)_x;
auto z256 = (__m256i *)_z;
auto ox256 = (__m256i *)rhs._x;
auto oz256 = (__m256i *)rhs._z;
auto end = &x256[num_words256() * stride256];
while (x256 != end) {
*x256 ^= *ox256;
x256 += stride256;
ox256 += rhs.stride256;
}
end = &z256[num_words256() * stride256];
while (z256 != end) {
*z256 ^= *oz256;
z256 += stride256;
oz256 += rhs.stride256;
}
return result;
}
bool PauliStringPtr::get_x_bit(size_t k) const {
k = (k & ~0xFF)*stride256 | (k & 0xFF);
size_t i0 = k >> 6;
size_t i1 = k & 63;
return ((_x[i0] >> i1) & 1) != 0;
}
bool PauliStringPtr::get_z_bit(size_t k) const {
k = (k & ~0xFF)*stride256 | (k & 0xFF);
size_t i0 = k >> 6;
size_t i1 = k & 63;
return ((_z[i0] >> i1) & 1) != 0;
}
void PauliStringPtr::toggle_x_bit(size_t k) {
k = (k & ~0xFF)*stride256 | (k & 0xFF);
size_t i0 = k >> 6;
size_t i1 = k & 63;
_x[i0] ^= 1ull << i1;
}
void PauliStringPtr::toggle_z_bit(size_t k) {
k = (k & ~0xFF)*stride256 | (k & 0xFF);
size_t i0 = k >> 6;
size_t i1 = k & 63;
_z[i0] ^= 1ull << i1;
}
void PauliStringPtr::set_x_bit(size_t k, bool val) {
k = (k & ~0xFF)*stride256 | (k & 0xFF);
size_t i0 = k >> 6;
size_t i1 = k & 63;
_x[i0] &= ~(1ull << i1);
_x[i0] ^= (uint64_t)val << i1;
}
void PauliStringPtr::set_z_bit(size_t k, bool val) {
k = (k & ~0xFF)*stride256 | (k & 0xFF);
size_t i0 = k >> 6;
size_t i1 = k & 63;
_z[i0] &= ~(1ull << i1);
_z[i0] ^= (uint64_t)val << i1;
}
void PauliStringPtr::gather_into(PauliStringPtr &out, const std::vector<size_t> &in_indices) const {
assert(in_indices.size() == out.size);
for (size_t k_out = 0; k_out < out.size; k_out++) {
size_t k_in = in_indices[k_out];
out.set_x_bit(k_out, get_x_bit(k_in));
out.set_z_bit(k_out, get_z_bit(k_in));
}
}
void PauliStringPtr::scatter_into(PauliStringPtr &out, const std::vector<size_t> &out_indices) const {
assert(size == out_indices.size());
for (size_t k_in = 0; k_in < size; k_in++) {
size_t k_out = out_indices[k_in];
out.set_x_bit(k_out, get_x_bit(k_in));
out.set_z_bit(k_out, get_z_bit(k_in));
}
out.bit_ptr_sign.toggle_if(bit_ptr_sign.get());
}
bool PauliStringVal::operator==(const PauliStringPtr &other) const {
return ptr() == other;
}
bool PauliStringVal::operator!=(const PauliStringPtr &other) const {
return ptr() != other;
}
<commit_msg>Commenting<commit_after>#include <iostream>
#include <immintrin.h>
#include <new>
#include <cassert>
#include <sstream>
#include "simd_util.h"
#include "pauli_string.h"
#include <cstring>
#include <cstdlib>
#include <bit>
PauliStringPtr::PauliStringPtr(
size_t init_size,
BitPtr init_sign,
uint64_t *init_x,
uint64_t *init_z,
size_t init_stride256) :
size(init_size),
bit_ptr_sign(init_sign),
_x(init_x),
_z(init_z),
stride256(init_stride256) {
}
PauliStringVal::PauliStringVal(size_t init_size) :
val_sign(false),
x_data(init_size),
z_data(init_size) {
}
PauliStringVal::PauliStringVal(const PauliStringPtr &other) :
val_sign(other.bit_ptr_sign.get()),
x_data(other.size, other._x),
z_data(other.size, other._z) {
}
PauliStringPtr PauliStringVal::ptr() const {
return PauliStringPtr(*this);
}
std::string PauliStringVal::str() const {
return ptr().str();
}
void PauliStringPtr::swap_with(PauliStringPtr &other) {
assert(size == other.size);
bit_ptr_sign.swap(other.bit_ptr_sign);
auto x256 = (__m256i *)_x;
auto z256 = (__m256i *)_z;
auto ox256 = (__m256i *)other._x;
auto oz256 = (__m256i *)other._z;
auto end = &x256[num_words256() * stride256];
while (x256 != end) {
std::swap(*x256, *ox256);
std::swap(*z256, *oz256);
x256 += stride256;
z256 += stride256;
ox256 += other.stride256;
oz256 += other.stride256;
}
}
void PauliStringPtr::overwrite_with(const PauliStringPtr &other) {
assert(size == other.size);
bit_ptr_sign.set(other.bit_ptr_sign.get());
auto x256 = (__m256i *)_x;
auto z256 = (__m256i *)_z;
auto ox256 = (__m256i *)other._x;
auto oz256 = (__m256i *)other._z;
auto end = &x256[num_words256() * stride256];
while (x256 != end) {
*x256 = *ox256;
*z256 = *oz256;
x256 += stride256;
z256 += stride256;
ox256 += other.stride256;
oz256 += other.stride256;
}
}
PauliStringVal& PauliStringVal::operator=(const PauliStringPtr &other) noexcept {
(*this).~PauliStringVal();
new(this) PauliStringVal(other);
return *this;
}
PauliStringPtr::PauliStringPtr(const PauliStringVal &other) :
size(other.x_data.num_bits),
bit_ptr_sign(BitPtr((void *)&other.val_sign, 0)),
_x(other.x_data.u64),
_z(other.z_data.u64),
stride256(1) {
}
uint8_t PauliStringPtr::log_i_scalar_byproduct(const PauliStringPtr &other) const {
assert(size == other.size);
union {__m256i u256; uint64_t u64[4]; } cnt1 {};
union {__m256i u256; uint64_t u64[4]; } cnt2 {};
auto x256 = (__m256i *)_x;
auto z256 = (__m256i *)_z;
auto ox256 = (__m256i *)other._x;
auto oz256 = (__m256i *)other._z;
auto end = &x256[num_words256() * stride256];
while (x256 != end) {
// Load into registers.
auto x1 = *x256;
auto z2 = *oz256;
auto z1 = *z256;
auto x2 = *ox256;
auto t1 = x1 & z2;
auto t2 = x2 & z1;
// At each bit position: do the Paulis anti-commute?
auto a = t1 ^ t2;
// At each bit position: do the Paulis anti-commute and produce a -i instead of a +i?
auto b = ((x1 ^ z2) & t2) ^ _mm256_andnot_si256(z1, _mm256_andnot_si256(x2, t1));
// At each bit position: `count += forward - backward` where `backward=b`, `forward=a^b`, `count=cnt1 + 2*cnt2`.
cnt1.u256 ^= b;
cnt2.u256 ^= cnt1.u256 & a;
cnt1.u256 ^= a ^ b;
// Move along.
x256 += stride256;
z256 += stride256;
ox256 += other.stride256;
oz256 += other.stride256;
}
// Combine final anti-commutation phase tally (mod 4).
size_t s = 0;
for (size_t k = 0; k < 4; k++) {
s += (uint8_t) std::popcount(cnt1.u64[k]);
s ^= (uint8_t) std::popcount(cnt2.u64[k]) << 1;
}
return s & 3;
}
std::string PauliStringPtr::str() const {
std::stringstream ss;
ss << *this;
return ss.str();
}
bool PauliStringPtr::operator==(const PauliStringPtr &other) const {
if (size != other.size || bit_ptr_sign.get() != other.bit_ptr_sign.get()) {
return false;
}
__m256i acc {};
auto x256 = (__m256i *)_x;
auto z256 = (__m256i *)_z;
auto ox256 = (__m256i *)other._x;
auto oz256 = (__m256i *)other._z;
auto end = &x256[num_words256() * stride256];
while (x256 != end) {
acc |= *x256 ^ *ox256;
acc |= *z256 ^ *oz256;
x256 += stride256;
z256 += stride256;
ox256 += other.stride256;
oz256 += other.stride256;
}
auto acc64 = (uint64_t *)&acc;
for (size_t k = 0; k < 4; k++) {
if (acc64[k]) {
return false;
}
}
return true;
}
bool PauliStringPtr::operator!=(const PauliStringPtr &other) const {
return !(*this == other);
}
std::ostream &operator<<(std::ostream &out, const PauliStringVal &ps) {
return out << ps.ptr();
}
size_t PauliStringPtr::num_words256() const {
return ceil256(size) >> 8;
}
std::ostream &operator<<(std::ostream &out, const PauliStringPtr &ps) {
out << (ps.bit_ptr_sign.get() ? '-' : '+');
auto x256 = (__m256i *)ps._x;
auto z256 = (__m256i *)ps._z;
auto end = &x256[ps.num_words256() * ps.stride256];
size_t remaining = ps.size;
while (x256 != end) {
auto xs = m256i_to_bits(*x256);
auto zs = m256i_to_bits(*z256);
for (int j = 0; j < 256 && remaining; j++) {
out << "_XZY"[xs[j] + 2 * zs[j]];
remaining--;
}
x256 += ps.stride256;
z256 += ps.stride256;
}
return out;
}
PauliStringVal PauliStringVal::from_pattern(bool sign, size_t size, const std::function<char(size_t)> &func) {
PauliStringVal result(size);
result.val_sign = sign;
for (size_t i = 0; i < size; i++) {
char c = func(i);
bool x;
bool z;
if (c == 'X') {
x = true;
z = false;
} else if (c == 'Y') {
x = true;
z = true;
} else if (c == 'Z') {
x = false;
z = true;
} else if (c == '_' || c == 'I') {
x = false;
z = false;
} else {
throw std::runtime_error("Unrecognized pauli character. " + std::to_string(c));
}
result.x_data.u64[i / 64] ^= (uint64_t)x << (i & 63);
result.z_data.u64[i / 64] ^= (uint64_t)z << (i & 63);
}
return result;
}
PauliStringVal PauliStringVal::from_str(const char *text) {
auto sign = text[0] == '-';
if (text[0] == '+' || text[0] == '-') {
text++;
}
return PauliStringVal::from_pattern(sign, strlen(text), [&](size_t i){ return text[i]; });
}
PauliStringVal PauliStringVal::identity(size_t size) {
return PauliStringVal(size);
}
PauliStringPtr& PauliStringPtr::operator*=(const PauliStringPtr& rhs) {
uint8_t log_i = inplace_right_mul_with_scalar_output(rhs);
assert((log_i & 1) == 0);
bit_ptr_sign.toggle_if(log_i & 2);
return *this;
}
uint8_t PauliStringPtr::inplace_right_mul_with_scalar_output(const PauliStringPtr& rhs) {
uint8_t result = log_i_scalar_byproduct(rhs);
result ^= (uint8_t)rhs.bit_ptr_sign.get() << 1;
auto x256 = (__m256i *)_x;
auto z256 = (__m256i *)_z;
auto ox256 = (__m256i *)rhs._x;
auto oz256 = (__m256i *)rhs._z;
auto end = &x256[num_words256() * stride256];
while (x256 != end) {
*x256 ^= *ox256;
x256 += stride256;
ox256 += rhs.stride256;
}
end = &z256[num_words256() * stride256];
while (z256 != end) {
*z256 ^= *oz256;
z256 += stride256;
oz256 += rhs.stride256;
}
return result;
}
bool PauliStringPtr::get_x_bit(size_t k) const {
k = (k & ~0xFF)*stride256 | (k & 0xFF);
size_t i0 = k >> 6;
size_t i1 = k & 63;
return ((_x[i0] >> i1) & 1) != 0;
}
bool PauliStringPtr::get_z_bit(size_t k) const {
k = (k & ~0xFF)*stride256 | (k & 0xFF);
size_t i0 = k >> 6;
size_t i1 = k & 63;
return ((_z[i0] >> i1) & 1) != 0;
}
void PauliStringPtr::toggle_x_bit(size_t k) {
k = (k & ~0xFF)*stride256 | (k & 0xFF);
size_t i0 = k >> 6;
size_t i1 = k & 63;
_x[i0] ^= 1ull << i1;
}
void PauliStringPtr::toggle_z_bit(size_t k) {
k = (k & ~0xFF)*stride256 | (k & 0xFF);
size_t i0 = k >> 6;
size_t i1 = k & 63;
_z[i0] ^= 1ull << i1;
}
void PauliStringPtr::set_x_bit(size_t k, bool val) {
k = (k & ~0xFF)*stride256 | (k & 0xFF);
size_t i0 = k >> 6;
size_t i1 = k & 63;
_x[i0] &= ~(1ull << i1);
_x[i0] ^= (uint64_t)val << i1;
}
void PauliStringPtr::set_z_bit(size_t k, bool val) {
k = (k & ~0xFF)*stride256 | (k & 0xFF);
size_t i0 = k >> 6;
size_t i1 = k & 63;
_z[i0] &= ~(1ull << i1);
_z[i0] ^= (uint64_t)val << i1;
}
void PauliStringPtr::gather_into(PauliStringPtr &out, const std::vector<size_t> &in_indices) const {
assert(in_indices.size() == out.size);
for (size_t k_out = 0; k_out < out.size; k_out++) {
size_t k_in = in_indices[k_out];
out.set_x_bit(k_out, get_x_bit(k_in));
out.set_z_bit(k_out, get_z_bit(k_in));
}
}
void PauliStringPtr::scatter_into(PauliStringPtr &out, const std::vector<size_t> &out_indices) const {
assert(size == out_indices.size());
for (size_t k_in = 0; k_in < size; k_in++) {
size_t k_out = out_indices[k_in];
out.set_x_bit(k_out, get_x_bit(k_in));
out.set_z_bit(k_out, get_z_bit(k_in));
}
out.bit_ptr_sign.toggle_if(bit_ptr_sign.get());
}
bool PauliStringVal::operator==(const PauliStringPtr &other) const {
return ptr() == other;
}
bool PauliStringVal::operator!=(const PauliStringPtr &other) const {
return ptr() != other;
}
<|endoftext|> |
<commit_before>/*
* Adplug - Replayer for many OPL2/OPL3 audio file formats.
* Copyright (C) 1999, 2000, 2001 Simon Peter, <[email protected]>, et al.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*
* sa2.cpp - SAdT2 Loader by Simon Peter ([email protected])
*
* NOTES:
* SAdT2 version 7 files are unimplemented (i don't have any).
*/
#include <stdio.h>
#include "sa2.h"
bool Csa2Loader::load(istream &f)
{
struct {
unsigned char data[11],arpstart,arpspeed,arppos,arpspdcnt;
} insts[31];
unsigned char buf;
int i,j;
const unsigned char convfx[16] = {0,1,2,3,4,5,6,255,8,255,10,11,12,13,255,15};
// file validation section
f.read((char *)&header,sizeof(sa2header));
if(strncmp(header.sadt,"SAdT",4) || (header.version != 9 && header.version != 8))
return false;
// load section
f.read((char *)insts,31*15); // instruments
f.read((char *)instname,29*17); // instrument names
f.ignore(3); // dummy bytes
f.read(order,sizeof(order)); // pattern orders
f.read((char *)&nop,2); f.read(&length,1); f.read(&restartpos,1); f.read((char *)&bpm,2); // infos
f.read(arplist,sizeof(arplist)); // arpeggio list
f.read(arpcmd,sizeof(arpcmd)); // arpeggio commands
for(i=0;i<64*9;i++) // track orders
f.read((char *)&trackord[i/9][i%9],1);
if(header.version == 9)
f.read((char *)&activechan,2); // active channels
else
activechan = 0xffff; // v8 files have always all channels active
// track data
i = 0;
while(f.peek() != EOF) {
for(j=0;j<64;j++) {
buf = f.get();
tracks[i][j].note = buf >> 1;
tracks[i][j].inst = (buf & 1) << 4;
buf = f.get();
tracks[i][j].inst += buf >> 4;
tracks[i][j].command = convfx[buf & 0x0f];
buf = f.get();
tracks[i][j].param1 = buf >> 4;
tracks[i][j].param2 = buf & 0x0f;
}
i++;
}
// convert instruments
for(i=0;i<31;i++) {
for(j=0;j<11;j++)
inst[i].data[j] = insts[i].data[j];
inst[i].arpstart = insts[i].arpstart;
inst[i].arpspeed = insts[i].arpspeed;
inst[i].arppos = insts[i].arppos;
inst[i].arpspdcnt = insts[i].arpspdcnt;
inst[i].misc = 0;
inst[i].slide = 0;
}
// fix instrument names
for(i=0;i<29;i++)
for(j=0;j<17;j++)
if(!instname[i][j])
instname[i][j] = ' ';
rewind(0); // rewind module
return true;
}
std::string Csa2Loader::gettype()
{
char tmpstr[40];
sprintf(tmpstr,"Surprise! Adlib Tracker 2 (version %d)",header.version);
return std::string(tmpstr);
}
std::string Csa2Loader::gettitle()
{
char bufinst[29*17],buf[18];
int i,ptr;
// parse instrument names for song name
memset(bufinst,'\0',29*17);
for(i=0;i<29;i++) {
buf[16] = ' '; buf[17] = '\0';
memcpy(buf,instname[i]+1,16);
for(ptr=16;ptr>0;ptr--)
if(buf[ptr] == ' ')
buf[ptr] = '\0';
else {
if(ptr<16)
buf[ptr+1] = ' ';
break;
}
strcat(bufinst,buf);
}
if(strchr(bufinst,'"'))
return std::string(bufinst,strchr(bufinst,'"')-bufinst+1,strrchr(bufinst,'"')-strchr(bufinst,'"')-1);
else
return std::string();
}
<commit_msg>.SAT support added to sa2.cpp - thanks mamiya<commit_after>/*
* Adplug - Replayer for many OPL2/OPL3 audio file formats.
* Copyright (C) 1999, 2000, 2001 Simon Peter, <[email protected]>, et al.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*
* sa2.cpp - SAdT2 Loader by Simon Peter ([email protected])
* SAdT Loader by Mamiya([email protected])
*
*/
#include <stdio.h>
#include "sa2.h"
bool Csa2Loader::load(istream &f)
{
struct {
unsigned char data[11],arpstart,arpspeed,arppos,arpspdcnt;
} insts;
unsigned char buf;
int i,j, k, notedis = 0;
const unsigned char convfx[16] = {0,1,2,3,4,5,6,255,8,255,10,11,12,13,255,15};
unsigned sat_type;
enum SAT_TYPE {
HAS_ARPEGIOLIST = (1 << 7),
HAS_V7PATTERNS = (1 << 6),
HAS_ACTIVECHANNELS = (1 << 5),
HAS_TRACKORDER = (1 << 4),
HAS_ARPEGIO = (1 << 3),
HAS_OLDBPM = (1 << 2),
HAS_OLDPATTERNS = (1 << 1),
HAS_UNKNOWN127 = (1 << 0)
};
// file validation section
f.read((char *)&header,sizeof(sa2header));
if(strncmp(header.sadt,"SAdT",4))
return false;
switch(header.version) {
case 1:
notedis = +0x18;
sat_type = HAS_UNKNOWN127 | HAS_OLDPATTERNS | HAS_OLDBPM;
break;
case 2:
notedis = +0x18;
sat_type = HAS_OLDPATTERNS | HAS_OLDBPM;
break;
case 3:
notedis = +0x0c;
sat_type = HAS_OLDPATTERNS | HAS_OLDBPM;
break;
case 4:
notedis = +0x0c;
sat_type = HAS_ARPEGIO | HAS_OLDPATTERNS | HAS_OLDBPM;
break;
case 5:
notedis = +0x0c;
sat_type = HAS_ARPEGIO | HAS_ARPEGIOLIST | HAS_OLDPATTERNS | HAS_OLDBPM;
break;
case 6:
sat_type = HAS_ARPEGIO | HAS_ARPEGIOLIST | HAS_OLDPATTERNS | HAS_OLDBPM;
break;
case 7:
sat_type = HAS_ARPEGIO | HAS_ARPEGIOLIST | HAS_V7PATTERNS;
break;
case 8:
sat_type = HAS_ARPEGIO | HAS_ARPEGIOLIST | HAS_TRACKORDER;
break;
case 9:
sat_type = HAS_ARPEGIO | HAS_ARPEGIOLIST | HAS_TRACKORDER | HAS_ACTIVECHANNELS;
break;
default: /* unknown */
return false;
}
// load section
for(i = 0; i < 31; i++) {
if(sat_type & HAS_ARPEGIO) {
f.read((char *)&insts,15); // instruments
inst[i].arpstart = insts.arpstart;
inst[i].arpspeed = insts.arpspeed;
inst[i].arppos = insts.arppos;
inst[i].arpspdcnt = insts.arpspdcnt;
} else {
f.read((char *)&insts,11); // instruments
inst[i].arpstart = 0;
inst[i].arpspeed = 0;
inst[i].arppos = 0;
inst[i].arpspdcnt = 0;
}
for(j=0;j<11;j++)
inst[i].data[j] = insts.data[j];
inst[i].misc = 0;
inst[i].slide = 0;
}
f.read((char *)instname,29*17); // instrument names
f.ignore(3); // dummy bytes
f.read(order,128); // pattern orders
if (sat_type & HAS_UNKNOWN127) f.ignore(127);
// infos
f.read((char *)&nop,2); f.read(&length,1); f.read(&restartpos,1);
// bpm
f.read((char *)&bpm,2);
if(sat_type & HAS_OLDBPM) {
bpm = bpm * 125 / 50; // cps -> bpm
}
if(sat_type & HAS_ARPEGIOLIST) {
f.read(arplist,sizeof(arplist)); // arpeggio list
f.read(arpcmd,sizeof(arpcmd)); // arpeggio commands
}
for(i=0;i<64;i++) { // track orders
for(j=0;j<9;j++) {
if(sat_type & HAS_TRACKORDER)
f.read((char *)&trackord[i][j],1);
else
{
trackord[i][j] = i * 9 + j;
}
}
}
if(sat_type & HAS_ACTIVECHANNELS)
f.read((char *)&activechan,2); // active channels
else
activechan = 0xffff;
// track data
if(sat_type & HAS_OLDPATTERNS) {
i = 0;
while(f.peek() != EOF) {
for(j=0;j<64;j++) {
for(k=0;k<9;k++) {
buf = f.get();
tracks[i+k][j].note = buf ? (buf + notedis) : 0;
tracks[i+k][j].inst = f.get();
tracks[i+k][j].command = convfx[f.get() & 0xf];
tracks[i+k][j].param1 = f.get();
tracks[i+k][j].param2 = f.get();
}
}
i+=9;
}
} else if(sat_type & HAS_V7PATTERNS) {
i = 0;
while(f.peek() != EOF) {
for(j=0;j<64;j++) {
for(k=0;k<9;k++) {
buf = f.get();
tracks[i+k][j].note = buf >> 1;
tracks[i+k][j].inst = (buf & 1) << 4;
buf = f.get();
tracks[i+k][j].inst += buf >> 4;
tracks[i+k][j].command = convfx[buf & 0x0f];
buf = f.get();
tracks[i+k][j].param1 = buf >> 4;
tracks[i+k][j].param2 = buf & 0x0f;
}
}
i+=9;
}
} else {
i = 0;
while(f.peek() != EOF) {
for(j=0;j<64;j++) {
buf = f.get();
tracks[i][j].note = buf >> 1;
tracks[i][j].inst = (buf & 1) << 4;
buf = f.get();
tracks[i][j].inst += buf >> 4;
tracks[i][j].command = convfx[buf & 0x0f];
buf = f.get();
tracks[i][j].param1 = buf >> 4;
tracks[i][j].param2 = buf & 0x0f;
}
i++;
}
}
// fix instrument names
for(i=0;i<29;i++)
for(j=0;j<17;j++)
if(!instname[i][j])
instname[i][j] = ' ';
rewind(0); // rewind module
return true;
}
std::string Csa2Loader::gettype()
{
char tmpstr[40];
sprintf(tmpstr,"Surprise! Adlib Tracker 2 (version %d)",header.version);
return std::string(tmpstr);
}
std::string Csa2Loader::gettitle()
{
char bufinst[29*17],buf[18];
int i,ptr;
// parse instrument names for song name
memset(bufinst,'\0',29*17);
for(i=0;i<29;i++) {
buf[16] = ' '; buf[17] = '\0';
memcpy(buf,instname[i]+1,16);
for(ptr=16;ptr>0;ptr--)
if(buf[ptr] == ' ')
buf[ptr] = '\0';
else {
if(ptr<16)
buf[ptr+1] = ' ';
break;
}
strcat(bufinst,buf);
}
if(strchr(bufinst,'"'))
return std::string(bufinst,strchr(bufinst,'"')-bufinst+1,strrchr(bufinst,'"')-strchr(bufinst,'"')-1);
else
return std::string();
}
<|endoftext|> |
<commit_before>//
// ExecutorImplementation.hpp
// Clock Signal
//
// Created by Thomas Harte on 01/05/2022.
// Copyright © 2022 Thomas Harte. All rights reserved.
//
#ifndef InstructionSets_M68k_ExecutorImplementation_hpp
#define InstructionSets_M68k_ExecutorImplementation_hpp
#include "../Perform.hpp"
#include <cassert>
namespace InstructionSet {
namespace M68k {
template <Model model, typename BusHandler>
Executor<model, BusHandler>::Executor(BusHandler &handler) : bus_handler_(handler) {
reset();
}
template <Model model, typename BusHandler>
void Executor<model, BusHandler>::reset() {
// Establish: supervisor state, all interrupts blocked.
status_.set_status(0b0010'0011'1000'0000);
// Seed stack pointer and program counter.
data_[7] = bus_handler_.template read<uint32_t>(0);
program_counter_.l = bus_handler_.template read<uint32_t>(4);
}
template <Model model, typename BusHandler>
void Executor<model, BusHandler>::read(DataSize size, uint32_t address, CPU::SlicedInt32 &value) {
switch(size) {
case DataSize::Byte:
value.b = bus_handler_.template read<uint8_t>(address);
break;
case DataSize::Word:
value.w = bus_handler_.template read<uint16_t>(address);
break;
case DataSize::LongWord:
value.l = bus_handler_.template read<uint32_t>(address);
break;
}
}
template <Model model, typename BusHandler>
void Executor<model, BusHandler>::write(DataSize size, uint32_t address, CPU::SlicedInt32 value) {
switch(size) {
case DataSize::Byte:
bus_handler_.template write<uint8_t>(address, value.b);
break;
case DataSize::Word:
bus_handler_.template write<uint16_t>(address, value.w);
break;
case DataSize::LongWord:
bus_handler_.template write<uint32_t>(address, value.l);
break;
}
}
template <Model model, typename BusHandler>
template <typename IntT> IntT Executor<model, BusHandler>::read_pc() {
const IntT result = bus_handler_.template read<IntT>(program_counter_.l);
if constexpr (sizeof(IntT) == 4) {
program_counter_.l += 4;
} else {
program_counter_.l += 2;
}
return result;
}
template <Model model, typename BusHandler>
uint32_t Executor<model, BusHandler>::index_8bitdisplacement() {
// TODO: if not a 68000, check bit 8 for whether this should be a full extension word;
// also include the scale field even if not.
const auto extension = read_pc<uint16_t>();
const auto offset = int8_t(extension);
const int register_index = (extension >> 11) & 7;
const uint32_t displacement = (extension & 0x8000) ? address_[register_index].l : data_[register_index].l;
return offset + (extension & 0x800) ? displacement : uint16_t(displacement);
}
template <Model model, typename BusHandler>
typename Executor<model, BusHandler>::EffectiveAddress Executor<model, BusHandler>::calculate_effective_address(Preinstruction instruction, uint16_t opcode, int index) {
EffectiveAddress ea;
switch(instruction.mode(index)) {
case AddressingMode::None:
// Permit an uninitialised effective address to be returned;
// this value shouldn't be used.
break;
//
// Operands that don't have effective addresses, which are returned as values.
//
case AddressingMode::DataRegisterDirect:
ea.value = data_[instruction.reg(index)];
ea.requires_fetch = false;
break;
case AddressingMode::AddressRegisterDirect:
ea.value = address_[instruction.reg(index)];
ea.requires_fetch = false;
break;
case AddressingMode::Quick:
ea.value.l = quick(instruction.operation, opcode);
ea.requires_fetch = false;
break;
case AddressingMode::ImmediateData:
read(instruction.size(), program_counter_.l, ea.value.l);
program_counter_.l += (instruction.size() == DataSize::LongWord) ? 4 : 2;
ea.requires_fetch = false;
break;
//
// Absolute addresses.
//
case AddressingMode::AbsoluteShort:
ea.value.l = int16_t(read_pc<uint16_t>());
ea.requires_fetch = true;
break;
case AddressingMode::AbsoluteLong:
ea.value.l = read_pc<uint32_t>();
ea.requires_fetch = true;
break;
//
// Address register indirects.
//
case AddressingMode::AddressRegisterIndirect:
ea.value.l = address_[instruction.reg(index)];
ea.requires_fetch = true;
break;
case AddressingMode::AddressRegisterIndirectWithPostincrement: {
const auto reg = instruction.reg(index);
ea.value.l = address_[reg];
ea.requires_fetch = true;
switch(instruction.size()) {
case DataSize::Byte: address_[reg].l += byte_increments[reg]; break;
case DataSize::Word: address_[reg].l += 2; break;
case DataSize::LongWord: address_[reg].l += 4; break;
}
} break;
case AddressingMode::AddressRegisterIndirectWithPredecrement: {
const auto reg = instruction.reg(index);
switch(instruction.size()) {
case DataSize::Byte: address_[reg].l -= byte_increments[reg]; break;
case DataSize::Word: address_[reg].l -= 2; break;
case DataSize::LongWord: address_[reg].l -= 4; break;
}
ea.value.l = address_[reg];
ea.requires_fetch = true;
} break;
case AddressingMode::AddressRegisterIndirectWithDisplacement:
ea.value.l = address_[instruction.reg(index)].l + int16_t(read_pc<uint16_t>());
ea.requires_fetch = true;
break;
case AddressingMode::AddressRegisterIndirectWithIndex8bitDisplacement:
ea.value.l = address_[instruction.reg(index)].l + index_8bitdisplacement();
ea.requires_fetch = true;
break;
//
// PC-relative addresses.
//
// TODO: rephrase these in terms of instruction_address_. Just for security
// against whatever mutations the PC has been through already to get to here.
//
case AddressingMode::ProgramCounterIndirectWithDisplacement:
ea.value.l = program_counter_.l + int16_t(read_pc<uint16_t>());
ea.requires_fetch = true;
break;
case AddressingMode::ProgramCounterIndirectWithIndex8bitDisplacement:
ea.value.l = program_counter_.l + index_8bitdisplacement();
ea.requires_fetch = true;
break;
default:
// TODO.
assert(false);
break;
}
return ea;
}
template <Model model, typename BusHandler>
void Executor<model, BusHandler>::run_for_instructions(int count) {
while(count--) {
// TODO: check interrupt level, trace flag.
// Read the next instruction.
instruction_address_ = program_counter_.l;
const auto opcode = read_pc<uint16_t>();
const Preinstruction instruction = decoder_.decode(opcode);
program_counter_.l += 2;
// TODO: check privilege level.
// Temporary storage.
CPU::SlicedInt32 operand_[2];
EffectiveAddress effective_address_[2];
// Calculate effective addresses; copy 'addresses' into the
// operands by default both: (i) because they might be values,
// rather than addresses; and (ii) then they'll be there for use
// by LEA and PEA.
//
// TODO: this work should be performed by a full Decoder, so that it can be cached.
effective_address_[0] = calculate_effective_address(instruction, opcode, 0);
effective_address_[1] = calculate_effective_address(instruction, opcode, 1);
operand_[0] = effective_address_[0].value;
operand_[1] = effective_address_[1].value;
// Obtain the appropriate sequence.
//
// TODO: make a decision about whether this goes into a fully-decoded Instruction.
Sequence<model> sequence(instruction.operation);
// Perform it.
while(!sequence.empty()) {
const auto step = sequence.pop_front();
switch(step) {
default: assert(false); // i.e. TODO
case Step::FetchOp1:
case Step::FetchOp2: {
const auto index = int(step) & 1;
// If the operand wasn't indirect, it's already fetched.
if(!effective_address_[index].requires_fetch) continue;
// TODO: potential bus alignment exception.
read(instruction.size(), effective_address_[index].value, operand_[index]);
} break;
case Step::Perform:
perform<model>(instruction, operand_[0], operand_[1], status_, this);
break;
case Step::StoreOp1:
case Step::StoreOp2: {
const auto index = int(step) & 1;
// If the operand wasn't indirect, store directly to Dn or An.
if(!effective_address_[index].requires_fetch) {
// This must be either address or data register indirect.
assert(
instruction.mode(index) == AddressingMode::DataRegisterDirect ||
instruction.mode(index) == AddressingMode::AddressRegisterDirect);
// TODO: is it worth holding registers as a single block to avoid this conditional?
if(instruction.mode(index) == AddressingMode::DataRegisterDirect) {
data_[instruction.reg(index)] = operand_[index];
} else {
address_[instruction.reg(index)] = operand_[index];
}
break;
}
// TODO: potential bus alignment exception.
write(instruction.size(), effective_address_[index].value, operand_[index]);
} break;
}
}
}
}
}
}
#endif /* InstructionSets_M68k_ExecutorImplementation_hpp */
<commit_msg>Equivocate.<commit_after>//
// ExecutorImplementation.hpp
// Clock Signal
//
// Created by Thomas Harte on 01/05/2022.
// Copyright © 2022 Thomas Harte. All rights reserved.
//
#ifndef InstructionSets_M68k_ExecutorImplementation_hpp
#define InstructionSets_M68k_ExecutorImplementation_hpp
#include "../Perform.hpp"
#include <cassert>
namespace InstructionSet {
namespace M68k {
template <Model model, typename BusHandler>
Executor<model, BusHandler>::Executor(BusHandler &handler) : bus_handler_(handler) {
reset();
}
template <Model model, typename BusHandler>
void Executor<model, BusHandler>::reset() {
// Establish: supervisor state, all interrupts blocked.
status_.set_status(0b0010'0011'1000'0000);
// Seed stack pointer and program counter.
data_[7] = bus_handler_.template read<uint32_t>(0);
program_counter_.l = bus_handler_.template read<uint32_t>(4);
}
template <Model model, typename BusHandler>
void Executor<model, BusHandler>::read(DataSize size, uint32_t address, CPU::SlicedInt32 &value) {
switch(size) {
case DataSize::Byte:
value.b = bus_handler_.template read<uint8_t>(address);
break;
case DataSize::Word:
value.w = bus_handler_.template read<uint16_t>(address);
break;
case DataSize::LongWord:
value.l = bus_handler_.template read<uint32_t>(address);
break;
}
}
template <Model model, typename BusHandler>
void Executor<model, BusHandler>::write(DataSize size, uint32_t address, CPU::SlicedInt32 value) {
switch(size) {
case DataSize::Byte:
bus_handler_.template write<uint8_t>(address, value.b);
break;
case DataSize::Word:
bus_handler_.template write<uint16_t>(address, value.w);
break;
case DataSize::LongWord:
bus_handler_.template write<uint32_t>(address, value.l);
break;
}
}
template <Model model, typename BusHandler>
template <typename IntT> IntT Executor<model, BusHandler>::read_pc() {
const IntT result = bus_handler_.template read<IntT>(program_counter_.l);
if constexpr (sizeof(IntT) == 4) {
program_counter_.l += 4;
} else {
program_counter_.l += 2;
}
return result;
}
template <Model model, typename BusHandler>
uint32_t Executor<model, BusHandler>::index_8bitdisplacement() {
// TODO: if not a 68000, check bit 8 for whether this should be a full extension word;
// also include the scale field even if not.
const auto extension = read_pc<uint16_t>();
const auto offset = int8_t(extension);
const int register_index = (extension >> 11) & 7;
const uint32_t displacement = (extension & 0x8000) ? address_[register_index].l : data_[register_index].l;
return offset + (extension & 0x800) ? displacement : uint16_t(displacement);
}
template <Model model, typename BusHandler>
typename Executor<model, BusHandler>::EffectiveAddress Executor<model, BusHandler>::calculate_effective_address(Preinstruction instruction, uint16_t opcode, int index) {
EffectiveAddress ea;
switch(instruction.mode(index)) {
case AddressingMode::None:
// Permit an uninitialised effective address to be returned;
// this value shouldn't be used.
break;
//
// Operands that don't have effective addresses, which are returned as values.
//
case AddressingMode::DataRegisterDirect:
ea.value = data_[instruction.reg(index)];
ea.requires_fetch = false;
break;
case AddressingMode::AddressRegisterDirect:
ea.value = address_[instruction.reg(index)];
ea.requires_fetch = false;
break;
case AddressingMode::Quick:
ea.value.l = quick(instruction.operation, opcode);
ea.requires_fetch = false;
break;
case AddressingMode::ImmediateData:
read(instruction.size(), program_counter_.l, ea.value.l);
program_counter_.l += (instruction.size() == DataSize::LongWord) ? 4 : 2;
ea.requires_fetch = false;
break;
//
// Absolute addresses.
//
case AddressingMode::AbsoluteShort:
ea.value.l = int16_t(read_pc<uint16_t>());
ea.requires_fetch = true;
break;
case AddressingMode::AbsoluteLong:
ea.value.l = read_pc<uint32_t>();
ea.requires_fetch = true;
break;
//
// Address register indirects.
//
case AddressingMode::AddressRegisterIndirect:
ea.value.l = address_[instruction.reg(index)];
ea.requires_fetch = true;
break;
case AddressingMode::AddressRegisterIndirectWithPostincrement: {
const auto reg = instruction.reg(index);
ea.value.l = address_[reg];
ea.requires_fetch = true;
switch(instruction.size()) {
case DataSize::Byte: address_[reg].l += byte_increments[reg]; break;
case DataSize::Word: address_[reg].l += 2; break;
case DataSize::LongWord: address_[reg].l += 4; break;
}
} break;
case AddressingMode::AddressRegisterIndirectWithPredecrement: {
const auto reg = instruction.reg(index);
switch(instruction.size()) {
case DataSize::Byte: address_[reg].l -= byte_increments[reg]; break;
case DataSize::Word: address_[reg].l -= 2; break;
case DataSize::LongWord: address_[reg].l -= 4; break;
}
ea.value.l = address_[reg];
ea.requires_fetch = true;
} break;
case AddressingMode::AddressRegisterIndirectWithDisplacement:
ea.value.l = address_[instruction.reg(index)].l + int16_t(read_pc<uint16_t>());
ea.requires_fetch = true;
break;
case AddressingMode::AddressRegisterIndirectWithIndex8bitDisplacement:
ea.value.l = address_[instruction.reg(index)].l + index_8bitdisplacement();
ea.requires_fetch = true;
break;
//
// PC-relative addresses.
//
// TODO: rephrase these in terms of instruction_address_. Just for security
// against whatever mutations the PC has been through already to get to here.
//
case AddressingMode::ProgramCounterIndirectWithDisplacement:
ea.value.l = program_counter_.l + int16_t(read_pc<uint16_t>());
ea.requires_fetch = true;
break;
case AddressingMode::ProgramCounterIndirectWithIndex8bitDisplacement:
ea.value.l = program_counter_.l + index_8bitdisplacement();
ea.requires_fetch = true;
break;
default:
// TODO.
assert(false);
break;
}
return ea;
}
template <Model model, typename BusHandler>
void Executor<model, BusHandler>::run_for_instructions(int count) {
while(count--) {
// TODO: check interrupt level, trace flag.
// Read the next instruction.
instruction_address_ = program_counter_.l;
const auto opcode = read_pc<uint16_t>();
const Preinstruction instruction = decoder_.decode(opcode);
program_counter_.l += 2;
// TODO: check privilege level.
// Temporary storage.
CPU::SlicedInt32 operand_[2];
EffectiveAddress effective_address_[2];
// Calculate effective addresses; copy 'addresses' into the
// operands by default both: (i) because they might be values,
// rather than addresses; and (ii) then they'll be there for use
// by LEA and PEA.
//
// TODO: much of this work should be performed by a full Decoder,
// so that it can be cached.
effective_address_[0] = calculate_effective_address(instruction, opcode, 0);
effective_address_[1] = calculate_effective_address(instruction, opcode, 1);
operand_[0] = effective_address_[0].value;
operand_[1] = effective_address_[1].value;
// Obtain the appropriate sequence.
//
// TODO: make a decision about whether this goes into a fully-decoded Instruction.
Sequence<model> sequence(instruction.operation);
// Perform it.
while(!sequence.empty()) {
const auto step = sequence.pop_front();
switch(step) {
default: assert(false); // i.e. TODO
case Step::FetchOp1:
case Step::FetchOp2: {
const auto index = int(step) & 1;
// If the operand wasn't indirect, it's already fetched.
if(!effective_address_[index].requires_fetch) continue;
// TODO: potential bus alignment exception.
read(instruction.size(), effective_address_[index].value, operand_[index]);
} break;
case Step::Perform:
perform<model>(instruction, operand_[0], operand_[1], status_, this);
break;
case Step::StoreOp1:
case Step::StoreOp2: {
const auto index = int(step) & 1;
// If the operand wasn't indirect, store directly to Dn or An.
if(!effective_address_[index].requires_fetch) {
// This must be either address or data register indirect.
assert(
instruction.mode(index) == AddressingMode::DataRegisterDirect ||
instruction.mode(index) == AddressingMode::AddressRegisterDirect);
// TODO: is it worth holding registers as a single block to avoid this conditional?
if(instruction.mode(index) == AddressingMode::DataRegisterDirect) {
data_[instruction.reg(index)] = operand_[index];
} else {
address_[instruction.reg(index)] = operand_[index];
}
break;
}
// TODO: potential bus alignment exception.
write(instruction.size(), effective_address_[index].value, operand_[index]);
} break;
}
}
}
}
}
}
#endif /* InstructionSets_M68k_ExecutorImplementation_hpp */
<|endoftext|> |
<commit_before>#include <orbsvcs/NotifyExtC.h>
#include <iostream>
#include <maciContainerImpl.h>
#include <acsContainerServices.h>
#include "acsncReconnectionCallback.h"
using namespace nc;
ReconnectionCallback::ReconnectionCallback(nc::Helper *sub):
sub_(sub),
id_is_valid_(false),
root_poa_(0),
services_(0)
{
if (::maci::ContainerImpl::getContainer() != NULL)
services_ = ::maci::ContainerImpl::getContainer()->getContainerServices();
}
bool ReconnectionCallback::is_alive()
{
return true;
}
void ReconnectionCallback::reconnect(::CORBA::Object_ptr new_connection)
{
ecf_ = NotifyMonitoringExt::EventChannelFactory::_narrow(new_connection);
if(!::CORBA::is_nil(ecf_))
sub_->reconnect(ecf_);
}
void ReconnectionCallback::init( CORBA::ORB_ptr orb_mp,
NotifyMonitoringExt::EventChannelFactory_ptr ecf)
{
if (::CORBA::is_nil(ecf)){
std::cout << "-- ECF is nil :( --" << std::endl;
return;
}
ecf_ = NotifyMonitoringExt::EventChannelFactory::_duplicate(ecf);
NotifyExt::ReconnectionCallback_var callback;
if (!::CORBA::is_nil(orb_mp)){
::CORBA::Object_ptr poa = orb_mp->resolve_initial_references("RootPOA");
root_poa_ = PortableServer::POA::_narrow (poa);
callback_obj_id_ = root_poa_->activate_object(this);
CORBA::Object_var obj =
root_poa_->id_to_reference(callback_obj_id_.in());
callback = NotifyExt::ReconnectionCallback::_narrow(obj);
}
else if (services_ != NULL){
callback = NotifyExt::ReconnectionCallback::_narrow(
services_->activateOffShoot(this));
}
else
return;
if (::CORBA::is_nil(callback))
std::cout << "Callback not initializated" << std::endl;
NotifyExt::ReconnectionRegistry_var registry =
NotifyExt::ReconnectionRegistry::_narrow(ecf_);
callback_id_ = registry->register_callback(callback);
id_is_valid_ = true;
}
void ReconnectionCallback::disconnect()
{
if (id_is_valid_){
NotifyExt::ReconnectionRegistry_var registry =
NotifyExt::ReconnectionRegistry::_narrow(ecf_);
registry->unregister_callback(callback_id_);
if (!::CORBA::is_nil(root_poa_))
root_poa_->deactivate_object(callback_obj_id_);
else
services_->deactivateOffShoot(this);
id_is_valid_ = false;
}
}
ReconnectionCallback::~ReconnectionCallback()
{
}
<commit_msg>ICTJ:ICT-4935: Fix memory leak in C++ callback<commit_after>#include <orbsvcs/NotifyExtC.h>
#include <iostream>
#include <maciContainerImpl.h>
#include <acsContainerServices.h>
#include "acsncReconnectionCallback.h"
using namespace nc;
ReconnectionCallback::ReconnectionCallback(nc::Helper *sub):
sub_(sub),
id_is_valid_(false),
root_poa_(0),
services_(0)
{
if (::maci::ContainerImpl::getContainer() != NULL)
services_ = ::maci::ContainerImpl::getContainer()->getContainerServices();
}
bool ReconnectionCallback::is_alive()
{
return true;
}
void ReconnectionCallback::reconnect(::CORBA::Object_ptr new_connection)
{
ecf_ = NotifyMonitoringExt::EventChannelFactory::_narrow(new_connection);
if(!::CORBA::is_nil(ecf_))
sub_->reconnect(ecf_);
}
void ReconnectionCallback::init( CORBA::ORB_ptr orb_mp,
NotifyMonitoringExt::EventChannelFactory_ptr ecf)
{
if (::CORBA::is_nil(ecf)){
std::cout << "-- ECF is nil :( --" << std::endl;
return;
}
ecf_ = NotifyMonitoringExt::EventChannelFactory::_duplicate(ecf);
NotifyExt::ReconnectionCallback_var callback;
if (!::CORBA::is_nil(orb_mp)){
::CORBA::Object_ptr poa = orb_mp->resolve_initial_references("RootPOA");
root_poa_ = PortableServer::POA::_narrow (poa);
callback_obj_id_ = root_poa_->activate_object(this);
CORBA::Object_var obj =
root_poa_->id_to_reference(callback_obj_id_.in());
callback = NotifyExt::ReconnectionCallback::_narrow(obj);
}
else if (services_ != NULL){
ACS::OffShoot_var shoot = services_->activateOffShoot(this);
callback = NotifyExt::ReconnectionCallback::_narrow(shoot.in());
}
else
return;
if (::CORBA::is_nil(callback))
std::cout << "Callback not initializated" << std::endl;
NotifyExt::ReconnectionRegistry_var registry =
NotifyExt::ReconnectionRegistry::_narrow(ecf_);
callback_id_ = registry->register_callback(callback);
id_is_valid_ = true;
}
void ReconnectionCallback::disconnect()
{
if (id_is_valid_){
NotifyExt::ReconnectionRegistry_var registry =
NotifyExt::ReconnectionRegistry::_narrow(ecf_);
registry->unregister_callback(callback_id_);
if (!::CORBA::is_nil(root_poa_))
root_poa_->deactivate_object(callback_obj_id_);
else
services_->deactivateOffShoot(this);
id_is_valid_ = false;
}
}
ReconnectionCallback::~ReconnectionCallback()
{
}
<|endoftext|> |
<commit_before>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "QmitkTrackingDeviceConfigurationWidget.h"
#include "mitkNDIPolarisTypeInformation.h"
#include <QSettings>
const std::string QmitkTrackingDeviceConfigurationWidget::VIEW_ID = "org.mitk.views.trackingdeviceconfigurationwidget";
QmitkTrackingDeviceConfigurationWidget::QmitkTrackingDeviceConfigurationWidget(QWidget* parent, Qt::WindowFlags f)
: QWidget(parent, f)
, m_Controls(nullptr)
, m_TrackingDevice(nullptr)
, m_DeviceToWidgetIndexMap()
{
//initializations
CreateQtPartControl(this);
CreateConnections();
RefreshTrackingDeviceCollection();
//initialize a few UI elements
AddOutput("<br>First Element selected"); //Order from Collection List
//reset a few things
ResetOutput();
//restore old UI settings
LoadUISettings();
}
QmitkTrackingDeviceConfigurationWidget::~QmitkTrackingDeviceConfigurationWidget()
{
StoreUISettings();
delete m_Controls;
m_TrackingDevice = nullptr;
}
void QmitkTrackingDeviceConfigurationWidget::CreateQtPartControl(QWidget *parent)
{
if (!m_Controls)
{
// create GUI widgets
m_Controls = new Ui::QmitkTrackingDeviceConfigurationWidgetControls;
m_Controls->setupUi(parent);
}
}
void QmitkTrackingDeviceConfigurationWidget::CreateConnections()
{
if (m_Controls)
{
connect((QObject*)(m_Controls->m_TrackingDeviceChooser), SIGNAL(currentIndexChanged(int)), this, SLOT(TrackingDeviceChanged()));
}
}
void QmitkTrackingDeviceConfigurationWidget::TrackingDeviceChanged()
{
const std::string currentDevice = this->GetCurrentDeviceName();
//show the correspondig widget
m_Controls->m_TrackingSystemWidget->setCurrentIndex(m_DeviceToWidgetIndexMap[currentDevice]);
//reset output
ResetOutput();
AddOutput("<br>");
AddOutput(currentDevice);
AddOutput(" selected");
QmitkAbstractTrackingDeviceWidget* widget = GetWidget(currentDevice);
if (widget == nullptr || !widget->IsDeviceInstalled())
{
AddOutput("<br>ERROR: not installed!");
}
emit TrackingDeviceSelectionChanged();
}
void QmitkTrackingDeviceConfigurationWidget::RefreshTrackingDeviceCollection()
{
// clean-up of stacked widget, drop-down box and map
for (auto& item : m_DeviceToWidgetIndexMap)
{
m_Controls->m_TrackingSystemWidget->removeWidget(m_Controls->m_TrackingSystemWidget->widget(item.second));
MITK_INFO << "removing widget for device '" << item.first << "'";
}
m_Controls->m_TrackingDeviceChooser->clear();
m_DeviceToWidgetIndexMap.clear();
// get tracking device type service references
us::ModuleContext* context = us::GetModuleContext();
std::vector<us::ServiceReference<mitk::TrackingDeviceTypeCollection> > deviceRefs =
context->GetServiceReferences<mitk::TrackingDeviceTypeCollection>();
if (deviceRefs.empty())
{
MITK_ERROR << "No tracking device type service found!";
return;
}
// get tracking device configuration widget service references
std::vector<us::ServiceReference<mitk::TrackingDeviceWidgetCollection> > widgetRefs =
context->GetServiceReferences<mitk::TrackingDeviceWidgetCollection>();
if (widgetRefs.empty())
{
MITK_ERROR << "No tracking device configuration widget service found!";
return;
}
const us::ServiceReference<mitk::TrackingDeviceTypeCollection>& deviceServiceReference = deviceRefs.front();
const us::ServiceReference<mitk::TrackingDeviceWidgetCollection>& widgetServiceReference = widgetRefs.front();
mitk::TrackingDeviceTypeCollection* deviceTypeCollection =
context->GetService<mitk::TrackingDeviceTypeCollection>(deviceServiceReference);
mitk::TrackingDeviceWidgetCollection* deviceWidgetCollection =
context->GetService<mitk::TrackingDeviceWidgetCollection>(widgetServiceReference);
for (auto name : deviceTypeCollection->GetTrackingDeviceTypeNames())
{
// if the device is not included yet, add name to comboBox and widget to stackedWidget
if (m_Controls->m_TrackingDeviceChooser->findText(QString::fromStdString(name)) == -1)
{
m_Controls->m_TrackingDeviceChooser->addItem(QString::fromStdString(name));
QWidget* current = deviceWidgetCollection->GetTrackingDeviceWidgetClone(name);
if (current == nullptr)
{
MITK_WARN << "No widget for tracking device type " << name << " available. Please implement and register it!";
current = new QWidget();
}
m_DeviceToWidgetIndexMap[name] = m_Controls->m_TrackingSystemWidget->addWidget(current);
}
}
if (!m_DeviceToWidgetIndexMap.empty())
{
m_Controls->m_TrackingDeviceChooser->setCurrentIndex(0);
m_Controls->m_TrackingSystemWidget->setCurrentIndex(0);
}
context->UngetService(deviceServiceReference);
context->UngetService(widgetServiceReference);
}
//######################### internal help methods #######################################
void QmitkTrackingDeviceConfigurationWidget::ResetOutput()
{
QmitkAbstractTrackingDeviceWidget* currentWidget = this->GetWidget(this->GetCurrentDeviceName());
if (currentWidget == nullptr)
{
return;
}
currentWidget->ResetOutput();
currentWidget->repaint();
}
void QmitkTrackingDeviceConfigurationWidget::AddOutput(std::string s)
{
QmitkAbstractTrackingDeviceWidget* currentWidget = this->GetWidget(this->GetCurrentDeviceName());
if (currentWidget == nullptr)
{
return;
}
currentWidget->AddOutput(s);
currentWidget->repaint();
}
mitk::TrackingDevice::Pointer QmitkTrackingDeviceConfigurationWidget::ConstructTrackingDevice()
{
QmitkAbstractTrackingDeviceWidget* currentWidget = this->GetWidget(this->GetCurrentDeviceName());
if (currentWidget == nullptr)
{
return nullptr;
}
return currentWidget->ConstructTrackingDevice();
}
mitk::TrackingDevice::Pointer QmitkTrackingDeviceConfigurationWidget::GetTrackingDevice()
{
m_TrackingDevice = ConstructTrackingDevice();
if (m_TrackingDevice.IsNull() || !m_TrackingDevice->IsDeviceInstalled()) return nullptr;
else return this->m_TrackingDevice;
}
void QmitkTrackingDeviceConfigurationWidget::StoreUISettings()
{
std::string id = "org.mitk.modules.igt.ui.trackingdeviceconfigurationwidget";
std::string selectedDevice = this->GetCurrentDeviceName();
//Save settings for every widget
//Don't use m_DeviceTypeCollection here, it's already unregistered, when deconstructor is called...
for (int index = 0; index < m_Controls->m_TrackingSystemWidget->count(); index++)
{
QmitkAbstractTrackingDeviceWidget* widget = dynamic_cast<QmitkAbstractTrackingDeviceWidget*>(m_Controls->m_TrackingSystemWidget->widget(index));
if (widget != nullptr)
{
widget->StoreUISettings();
}
}
if (this->GetPersistenceService()) // now save the settings using the persistence service
{
mitk::PropertyList::Pointer propList = this->GetPersistenceService()->GetPropertyList(id);
propList->Set("SelectedDevice", selectedDevice);
}
else // QSettings as a fallback if the persistence service is not available
{
QSettings settings;
settings.beginGroup(QString::fromStdString(id));
settings.setValue("trackingDeviceChooser", QVariant(QString::fromStdString(selectedDevice)));
settings.endGroup();
}
}
/**
* @brief QmitkTrackingDeviceConfigurationWidget::LoadUISettings
*
* Precondition:
* Make sure that QStackedWidget is already initialized,
* e.g. by calling RefreshTrackingDeviceCollection() before.
*/
void QmitkTrackingDeviceConfigurationWidget::LoadUISettings()
{
//Load settings for every widget
for (int index = 0; index < m_Controls->m_TrackingSystemWidget->count(); index++)
{
QmitkAbstractTrackingDeviceWidget* widget = dynamic_cast<QmitkAbstractTrackingDeviceWidget*>(m_Controls->m_TrackingSystemWidget->widget(index));
if (widget != nullptr)
{
widget->LoadUISettings();
}
}
std::string id = "org.mitk.modules.igt.ui.trackingdeviceconfigurationwidget";
std::string selectedDevice;
if (this->GetPersistenceService())
{
mitk::PropertyList::Pointer propList = this->GetPersistenceService()->GetPropertyList(id);
if (propList.IsNull())
{
MITK_ERROR << "Property list for this UI (" << id << ") is not available, could not load UI settings!"; return;
}
propList->Get("SelectedDevice", selectedDevice);
if (selectedDevice.empty())
{
MITK_ERROR << "Loaded data from persistence service is invalid (SelectedDevice:" << selectedDevice << "): aborted to restore data!";
return;
}
MITK_INFO << "Successfully restored UI settings";
}
else
{
// QSettings as a fallback if the persistence service is not available
QSettings settings;
settings.beginGroup(QString::fromStdString(id));
selectedDevice = settings.value("trackingDeviceChooser", "").toString().toStdString();
settings.endGroup();
}
// The selected device requires some checks because a device that is not installed should not be restored to avoid bugs.
// Use NDI Polaris as default if there's no widget registered for selected device or there's a widget for it but no device installed.
const auto& deviceIterator = m_DeviceToWidgetIndexMap.find(selectedDevice);
if (deviceIterator != m_DeviceToWidgetIndexMap.end())
{
QmitkAbstractTrackingDeviceWidget* widget =
dynamic_cast<QmitkAbstractTrackingDeviceWidget*>(m_Controls->m_TrackingSystemWidget->widget(deviceIterator->second));
if (widget == nullptr || (widget != nullptr && !widget->IsDeviceInstalled()))
{
selectedDevice = mitk::NDIPolarisTypeInformation::GetTrackingDeviceName();
}
}
else
{
selectedDevice = mitk::NDIPolarisTypeInformation::GetTrackingDeviceName();
}
const int index = m_Controls->m_TrackingDeviceChooser->findText(QString::fromStdString(selectedDevice));
if (index >= 0)
{
m_Controls->m_TrackingDeviceChooser->setCurrentIndex(index);
}
else
{
MITK_ERROR << "Failed to load UI setting for tracking device configuration";
return;
}
m_Controls->m_TrackingSystemWidget->setCurrentIndex(m_DeviceToWidgetIndexMap[selectedDevice]);
}
std::string QmitkTrackingDeviceConfigurationWidget::GetCurrentDeviceName(void) const
{
return m_Controls->m_TrackingDeviceChooser->currentText().toStdString();
}
QmitkAbstractTrackingDeviceWidget* QmitkTrackingDeviceConfigurationWidget::GetWidget(const std::string& deviceName) const
{
const auto& deviceIterator = m_DeviceToWidgetIndexMap.find(deviceName);
if (deviceIterator != m_DeviceToWidgetIndexMap.end())
{
QWidget* widget = m_Controls->m_TrackingSystemWidget->widget(deviceIterator->second);
return dynamic_cast<QmitkAbstractTrackingDeviceWidget*>(widget);
}
return nullptr;
}
<commit_msg>Only construct TrackingDevices if necessary!<commit_after>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "QmitkTrackingDeviceConfigurationWidget.h"
#include "mitkNDIPolarisTypeInformation.h"
#include <QSettings>
const std::string QmitkTrackingDeviceConfigurationWidget::VIEW_ID = "org.mitk.views.trackingdeviceconfigurationwidget";
QmitkTrackingDeviceConfigurationWidget::QmitkTrackingDeviceConfigurationWidget(QWidget* parent, Qt::WindowFlags f)
: QWidget(parent, f)
, m_Controls(nullptr)
, m_TrackingDevice(nullptr)
, m_DeviceToWidgetIndexMap()
{
//initializations
CreateQtPartControl(this);
CreateConnections();
RefreshTrackingDeviceCollection();
//initialize a few UI elements
AddOutput("<br>First Element selected"); //Order from Collection List
//reset a few things
ResetOutput();
//restore old UI settings
LoadUISettings();
}
QmitkTrackingDeviceConfigurationWidget::~QmitkTrackingDeviceConfigurationWidget()
{
StoreUISettings();
delete m_Controls;
m_TrackingDevice = nullptr;
}
void QmitkTrackingDeviceConfigurationWidget::CreateQtPartControl(QWidget *parent)
{
if (!m_Controls)
{
// create GUI widgets
m_Controls = new Ui::QmitkTrackingDeviceConfigurationWidgetControls;
m_Controls->setupUi(parent);
}
}
void QmitkTrackingDeviceConfigurationWidget::CreateConnections()
{
if (m_Controls)
{
connect((QObject*)(m_Controls->m_TrackingDeviceChooser), SIGNAL(currentIndexChanged(int)), this, SLOT(TrackingDeviceChanged()));
}
}
void QmitkTrackingDeviceConfigurationWidget::TrackingDeviceChanged()
{
const std::string currentDevice = this->GetCurrentDeviceName();
//show the correspondig widget
m_Controls->m_TrackingSystemWidget->setCurrentIndex(m_DeviceToWidgetIndexMap[currentDevice]);
//reset output
ResetOutput();
AddOutput("<br>");
AddOutput(currentDevice);
AddOutput(" selected");
QmitkAbstractTrackingDeviceWidget* widget = GetWidget(currentDevice);
if (widget == nullptr || !widget->IsDeviceInstalled())
{
AddOutput("<br>ERROR: not installed!");
}
emit TrackingDeviceSelectionChanged();
}
void QmitkTrackingDeviceConfigurationWidget::RefreshTrackingDeviceCollection()
{
// clean-up of stacked widget, drop-down box and map
for (auto& item : m_DeviceToWidgetIndexMap)
{
m_Controls->m_TrackingSystemWidget->removeWidget(m_Controls->m_TrackingSystemWidget->widget(item.second));
MITK_INFO << "removing widget for device '" << item.first << "'";
}
m_Controls->m_TrackingDeviceChooser->clear();
m_DeviceToWidgetIndexMap.clear();
// get tracking device type service references
us::ModuleContext* context = us::GetModuleContext();
std::vector<us::ServiceReference<mitk::TrackingDeviceTypeCollection> > deviceRefs =
context->GetServiceReferences<mitk::TrackingDeviceTypeCollection>();
if (deviceRefs.empty())
{
MITK_ERROR << "No tracking device type service found!";
return;
}
// get tracking device configuration widget service references
std::vector<us::ServiceReference<mitk::TrackingDeviceWidgetCollection> > widgetRefs =
context->GetServiceReferences<mitk::TrackingDeviceWidgetCollection>();
if (widgetRefs.empty())
{
MITK_ERROR << "No tracking device configuration widget service found!";
return;
}
const us::ServiceReference<mitk::TrackingDeviceTypeCollection>& deviceServiceReference = deviceRefs.front();
const us::ServiceReference<mitk::TrackingDeviceWidgetCollection>& widgetServiceReference = widgetRefs.front();
mitk::TrackingDeviceTypeCollection* deviceTypeCollection =
context->GetService<mitk::TrackingDeviceTypeCollection>(deviceServiceReference);
mitk::TrackingDeviceWidgetCollection* deviceWidgetCollection =
context->GetService<mitk::TrackingDeviceWidgetCollection>(widgetServiceReference);
for (auto name : deviceTypeCollection->GetTrackingDeviceTypeNames())
{
// if the device is not included yet, add name to comboBox and widget to stackedWidget
if (m_Controls->m_TrackingDeviceChooser->findText(QString::fromStdString(name)) == -1)
{
m_Controls->m_TrackingDeviceChooser->addItem(QString::fromStdString(name));
QWidget* current = deviceWidgetCollection->GetTrackingDeviceWidgetClone(name);
if (current == nullptr)
{
MITK_WARN << "No widget for tracking device type " << name << " available. Please implement and register it!";
current = new QWidget();
}
m_DeviceToWidgetIndexMap[name] = m_Controls->m_TrackingSystemWidget->addWidget(current);
}
}
if (!m_DeviceToWidgetIndexMap.empty())
{
m_Controls->m_TrackingDeviceChooser->setCurrentIndex(0);
m_Controls->m_TrackingSystemWidget->setCurrentIndex(0);
}
context->UngetService(deviceServiceReference);
context->UngetService(widgetServiceReference);
}
//######################### internal help methods #######################################
void QmitkTrackingDeviceConfigurationWidget::ResetOutput()
{
QmitkAbstractTrackingDeviceWidget* currentWidget = this->GetWidget(this->GetCurrentDeviceName());
if (currentWidget == nullptr)
{
return;
}
currentWidget->ResetOutput();
currentWidget->repaint();
}
void QmitkTrackingDeviceConfigurationWidget::AddOutput(std::string s)
{
QmitkAbstractTrackingDeviceWidget* currentWidget = this->GetWidget(this->GetCurrentDeviceName());
if (currentWidget == nullptr)
{
return;
}
currentWidget->AddOutput(s);
currentWidget->repaint();
}
mitk::TrackingDevice::Pointer QmitkTrackingDeviceConfigurationWidget::ConstructTrackingDevice()
{
QmitkAbstractTrackingDeviceWidget* currentWidget = this->GetWidget(this->GetCurrentDeviceName());
if (currentWidget == nullptr)
{
return nullptr;
}
return currentWidget->ConstructTrackingDevice();
}
mitk::TrackingDevice::Pointer QmitkTrackingDeviceConfigurationWidget::GetTrackingDevice()
{
//Only create a new device, if we don't have one yet or if the device selection in the widget has changed.
//otherwise, hundered of devices will be created each time someone calls Get...
if (m_TrackingDevice.IsNull() || m_TrackingDevice->GetTrackingDeviceName() != this->GetCurrentDeviceName())
m_TrackingDevice = ConstructTrackingDevice();
if (m_TrackingDevice.IsNull() || !m_TrackingDevice->IsDeviceInstalled()) return nullptr;
else return this->m_TrackingDevice;
}
void QmitkTrackingDeviceConfigurationWidget::StoreUISettings()
{
std::string id = "org.mitk.modules.igt.ui.trackingdeviceconfigurationwidget";
std::string selectedDevice = this->GetCurrentDeviceName();
//Save settings for every widget
//Don't use m_DeviceTypeCollection here, it's already unregistered, when deconstructor is called...
for (int index = 0; index < m_Controls->m_TrackingSystemWidget->count(); index++)
{
QmitkAbstractTrackingDeviceWidget* widget = dynamic_cast<QmitkAbstractTrackingDeviceWidget*>(m_Controls->m_TrackingSystemWidget->widget(index));
if (widget != nullptr)
{
widget->StoreUISettings();
}
}
if (this->GetPersistenceService()) // now save the settings using the persistence service
{
mitk::PropertyList::Pointer propList = this->GetPersistenceService()->GetPropertyList(id);
propList->Set("SelectedDevice", selectedDevice);
}
else // QSettings as a fallback if the persistence service is not available
{
QSettings settings;
settings.beginGroup(QString::fromStdString(id));
settings.setValue("trackingDeviceChooser", QVariant(QString::fromStdString(selectedDevice)));
settings.endGroup();
}
}
/**
* @brief QmitkTrackingDeviceConfigurationWidget::LoadUISettings
*
* Precondition:
* Make sure that QStackedWidget is already initialized,
* e.g. by calling RefreshTrackingDeviceCollection() before.
*/
void QmitkTrackingDeviceConfigurationWidget::LoadUISettings()
{
//Load settings for every widget
for (int index = 0; index < m_Controls->m_TrackingSystemWidget->count(); index++)
{
QmitkAbstractTrackingDeviceWidget* widget = dynamic_cast<QmitkAbstractTrackingDeviceWidget*>(m_Controls->m_TrackingSystemWidget->widget(index));
if (widget != nullptr)
{
widget->LoadUISettings();
}
}
std::string id = "org.mitk.modules.igt.ui.trackingdeviceconfigurationwidget";
std::string selectedDevice;
if (this->GetPersistenceService())
{
mitk::PropertyList::Pointer propList = this->GetPersistenceService()->GetPropertyList(id);
if (propList.IsNull())
{
MITK_ERROR << "Property list for this UI (" << id << ") is not available, could not load UI settings!"; return;
}
propList->Get("SelectedDevice", selectedDevice);
if (selectedDevice.empty())
{
MITK_ERROR << "Loaded data from persistence service is invalid (SelectedDevice:" << selectedDevice << "): aborted to restore data!";
return;
}
MITK_INFO << "Successfully restored UI settings";
}
else
{
// QSettings as a fallback if the persistence service is not available
QSettings settings;
settings.beginGroup(QString::fromStdString(id));
selectedDevice = settings.value("trackingDeviceChooser", "").toString().toStdString();
settings.endGroup();
}
// The selected device requires some checks because a device that is not installed should not be restored to avoid bugs.
// Use NDI Polaris as default if there's no widget registered for selected device or there's a widget for it but no device installed.
const auto& deviceIterator = m_DeviceToWidgetIndexMap.find(selectedDevice);
if (deviceIterator != m_DeviceToWidgetIndexMap.end())
{
QmitkAbstractTrackingDeviceWidget* widget =
dynamic_cast<QmitkAbstractTrackingDeviceWidget*>(m_Controls->m_TrackingSystemWidget->widget(deviceIterator->second));
if (widget == nullptr || (widget != nullptr && !widget->IsDeviceInstalled()))
{
selectedDevice = mitk::NDIPolarisTypeInformation::GetTrackingDeviceName();
}
}
else
{
selectedDevice = mitk::NDIPolarisTypeInformation::GetTrackingDeviceName();
}
const int index = m_Controls->m_TrackingDeviceChooser->findText(QString::fromStdString(selectedDevice));
if (index >= 0)
{
m_Controls->m_TrackingDeviceChooser->setCurrentIndex(index);
}
else
{
MITK_ERROR << "Failed to load UI setting for tracking device configuration";
return;
}
m_Controls->m_TrackingSystemWidget->setCurrentIndex(m_DeviceToWidgetIndexMap[selectedDevice]);
}
std::string QmitkTrackingDeviceConfigurationWidget::GetCurrentDeviceName(void) const
{
return m_Controls->m_TrackingDeviceChooser->currentText().toStdString();
}
QmitkAbstractTrackingDeviceWidget* QmitkTrackingDeviceConfigurationWidget::GetWidget(const std::string& deviceName) const
{
const auto& deviceIterator = m_DeviceToWidgetIndexMap.find(deviceName);
if (deviceIterator != m_DeviceToWidgetIndexMap.end())
{
QWidget* widget = m_Controls->m_TrackingSystemWidget->widget(deviceIterator->second);
return dynamic_cast<QmitkAbstractTrackingDeviceWidget*>(widget);
}
return nullptr;
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde
* 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 <organization> 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 EARLIER MENTIONED AUTHORS ``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 <copyright holder> 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 "CppUTest/TestHarness.h"
#include "CppUTest/TestOutput.h"
#include "CppUTest/TestTestingFixture.h"
#include "CppUTest/PlatformSpecificFunctions.h"
TEST_GROUP(UtestShell)
{
TestTestingFixture fixture;
};
static void _failMethod()
{
FAIL("This test fails");
}
static void _passingTestMethod()
{
CHECK(true);
}
static void _passingCheckEqualTestMethod()
{
CHECK_EQUAL(1, 1);
}
static void _exitTestMethod()
{
TEST_EXIT;
FAIL("Should not get here");
}
static volatile double zero = 0.0;
TEST(UtestShell, compareDoubles)
{
double not_a_number = zero / zero;
double infinity = 1 / zero;
CHECK(doubles_equal(1.0, 1.001, 0.01));
CHECK(!doubles_equal(not_a_number, 1.001, 0.01));
CHECK(!doubles_equal(1.0, not_a_number, 0.01));
CHECK(!doubles_equal(1.0, 1.001, not_a_number));
CHECK(!doubles_equal(1.0, 1.1, 0.05));
CHECK(!doubles_equal(infinity, 1.0, 0.01));
CHECK(!doubles_equal(1.0, infinity, 0.01));
CHECK(doubles_equal(1.0, -1.0, infinity));
CHECK(doubles_equal(infinity, infinity, 0.01));
CHECK(doubles_equal(infinity, infinity, infinity));
double a = 1.2345678;
CHECK(doubles_equal(a, a, 0.000000001));
}
TEST(UtestShell, FailWillIncreaseTheAmountOfChecks)
{
fixture.setTestFunction(_failMethod);
fixture.runAllTests();
LONGS_EQUAL(1, fixture.getCheckCount());
}
TEST(UtestShell, PassedCheckEqualWillIncreaseTheAmountOfChecks)
{
fixture.setTestFunction(_passingCheckEqualTestMethod);
fixture.runAllTests();
LONGS_EQUAL(1, fixture.getCheckCount());
}
IGNORE_TEST(UtestShell, IgnoreTestAccessingFixture)
{
CHECK(&fixture != NULLPTR);
}
TEST(UtestShell, MacrosUsedInSetup)
{
IGNORE_ALL_LEAKS_IN_TEST();
fixture.setSetup(_failMethod);
fixture.setTestFunction(_passingTestMethod);
fixture.runAllTests();
LONGS_EQUAL(1, fixture.getFailureCount());
}
TEST(UtestShell, MacrosUsedInTearDown)
{
IGNORE_ALL_LEAKS_IN_TEST();
fixture.setTeardown(_failMethod);
fixture.setTestFunction(_passingTestMethod);
fixture.runAllTests();
LONGS_EQUAL(1, fixture.getFailureCount());
}
TEST(UtestShell, ExitLeavesQuietly)
{
fixture.setTestFunction(_exitTestMethod);
fixture.runAllTests();
LONGS_EQUAL(0, fixture.getFailureCount());
}
static int teardownCalled = 0;
static void _teardownMethod()
{
teardownCalled++;
}
TEST(UtestShell, TeardownCalledAfterTestFailure)
{
teardownCalled = 0;
IGNORE_ALL_LEAKS_IN_TEST();
fixture.setTeardown(_teardownMethod);
fixture.setTestFunction(_failMethod);
fixture.runAllTests();
LONGS_EQUAL(1, fixture.getFailureCount());
LONGS_EQUAL(1, teardownCalled);
}
static int stopAfterFailure = 0;
static void _stopAfterFailureMethod()
{
FAIL("fail");
stopAfterFailure++;
}
TEST(UtestShell, TestStopsAfterTestFailure)
{
IGNORE_ALL_LEAKS_IN_TEST();
stopAfterFailure = 0;
fixture.setTestFunction(_stopAfterFailureMethod);
fixture.runAllTests();
CHECK(fixture.hasTestFailed());
LONGS_EQUAL(1, fixture.getFailureCount());
LONGS_EQUAL(0, stopAfterFailure);
}
TEST(UtestShell, TestStopsAfterSetupFailure)
{
stopAfterFailure = 0;
fixture.setSetup(_stopAfterFailureMethod);
fixture.setTeardown(_stopAfterFailureMethod);
fixture.setTestFunction(_failMethod);
fixture.runAllTests();
LONGS_EQUAL(2, fixture.getFailureCount());
LONGS_EQUAL(0, stopAfterFailure);
}
class defaultUtestShell: public UtestShell
{
};
TEST(UtestShell, this_test_covers_the_UtestShell_createTest_and_Utest_testBody_methods)
{
defaultUtestShell shell;
fixture.addTest(&shell);
fixture.runAllTests();
LONGS_EQUAL(2, fixture.result_->getTestCount());
}
static void StubPlatformSpecificRunTestInASeperateProcess(UtestShell* shell, TestPlugin*, TestResult* result)
{
result->addFailure(TestFailure(shell, "Failed in separate process"));
}
TEST(UtestShell, RunInSeparateProcessTest)
{
UT_PTR_SET(PlatformSpecificRunTestInASeperateProcess, StubPlatformSpecificRunTestInASeperateProcess);
fixture.registry_->setRunTestsInSeperateProcess();
fixture.runAllTests();
fixture.assertPrintContains("Failed in separate process");
}
#ifndef CPPUTEST_HAVE_FORK
IGNORE_TEST(UtestShell, TestDefaultCrashMethodInSeparateProcessTest) {}
#else
TEST(UtestShell, TestDefaultCrashMethodInSeparateProcessTest)
{
fixture.setTestFunction(UtestShell::crash);
fixture.registry_->setRunTestsInSeperateProcess();
fixture.runAllTests();
fixture.assertPrintContains("Failed in separate process - killed by signal");
/* Signal 11 usually happens, but with clang3.7 on Linux, it produced signal 4 */
CHECK(fixture.getOutput().contains("signal 11") || fixture.getOutput().contains("signal 4"));
}
#endif
#if CPPUTEST_USE_STD_CPP_LIB
static bool destructorWasCalledOnFailedTest = false;
static void _destructorCalledForLocalObjects()
{
SetBooleanOnDestructorCall pleaseCallTheDestructor(destructorWasCalledOnFailedTest);
destructorWasCalledOnFailedTest = false;
FAIL("fail");
}
TEST(UtestShell, DestructorIsCalledForLocalObjectsWhenTheTestFails)
{
fixture.setTestFunction(_destructorCalledForLocalObjects);
fixture.runAllTests();
CHECK(destructorWasCalledOnFailedTest);
}
#endif
TEST_GROUP(IgnoredUtestShell)
{
TestTestingFixture fixture;
IgnoredUtestShell ignoredTest;
ExecFunctionTestShell normalUtestShell;
void setup() _override
{
fixture.addTest(&ignoredTest);
fixture.addTest(&normalUtestShell);
}
};
TEST(IgnoredUtestShell, doesIgnoreCount)
{
fixture.runAllTests();
LONGS_EQUAL(1, fixture.getIgnoreCount());
}
TEST(IgnoredUtestShell, printsIGNORE_TESTwhenVerbose)
{
fixture.output_->verbose();
fixture.runAllTests();
fixture.assertPrintContains("IGNORE_TEST");
}
TEST(IgnoredUtestShell, runIgnoredOptionSpecifiedThenIncreaseRunCount)
{
ignoredTest.setRunIgnored();
fixture.runAllTests();
LONGS_EQUAL(3, fixture.getRunCount());
LONGS_EQUAL(0, fixture.getIgnoreCount());
}
TEST(IgnoredUtestShell, runIgnoredOptionNotSpecifiedThenIncreaseIgnoredCount)
{
fixture.runAllTests();
LONGS_EQUAL(2, fixture.getRunCount());
LONGS_EQUAL(1, fixture.getIgnoreCount());
}
TEST(IgnoredUtestShell, runIgnoredOptionSpecifiedWillNotInfluenceNormalTestCount)
{
normalUtestShell.setRunIgnored();
fixture.runAllTests();
LONGS_EQUAL(2, fixture.getRunCount());
LONGS_EQUAL(1, fixture.getIgnoreCount());
}
TEST(IgnoredUtestShell, runIgnoredOptionSpecifiedThenReturnTESTInFormattedName)
{
ignoredTest.setGroupName("TestGroup");
ignoredTest.setTestName("TestName");
ignoredTest.setRunIgnored();
fixture.runAllTests();
STRCMP_EQUAL("TEST(TestGroup, TestName)", ignoredTest.getFormattedName().asCharString());
}
TEST(IgnoredUtestShell, runIgnoredOptionNotSpecifiedThenReturnIGNORETESTInFormattedName)
{
ignoredTest.setGroupName("TestGroup");
ignoredTest.setTestName("TestName");
fixture.runAllTests();
STRCMP_EQUAL("IGNORE_TEST(TestGroup, TestName)", ignoredTest.getFormattedName().asCharString());
}
TEST(IgnoredUtestShell, runIgnoredOptionNotSpecifiedThenWillRunReturnFalse)
{
CHECK_FALSE(ignoredTest.willRun());
}
TEST(IgnoredUtestShell, runIgnoredOptionSpecifiedThenWillRunReturnTrue)
{
ignoredTest.setRunIgnored();
CHECK_TRUE(ignoredTest.willRun());
}
TEST_BASE(MyOwnTest)
{
MyOwnTest() :
inTest(false)
{
}
bool inTest;
void setup()
{
CHECK(!inTest);
inTest = true;
}
void teardown()
{
CHECK(inTest);
inTest = false;
}
};
TEST_GROUP_BASE(UtestMyOwn, MyOwnTest)
{
};
TEST(UtestMyOwn, test)
{
CHECK(inTest);
}
class NullParameterTest: public UtestShell
{
};
TEST(UtestMyOwn, NullParameters)
{
NullParameterTest nullTest; /* Bug fix tests for creating a test without a name, fix in SimpleString */
TestFilter emptyFilter;
CHECK(nullTest.shouldRun(&emptyFilter, &emptyFilter));
}
class AllocateAndDeallocateInConstructorAndDestructor
{
char* memory_;
char* morememory_;
public:
AllocateAndDeallocateInConstructorAndDestructor()
{
memory_ = new char[100];
morememory_ = NULLPTR;
}
void allocateMoreMemory()
{
morememory_ = new char[123];
}
~AllocateAndDeallocateInConstructorAndDestructor()
{
delete [] memory_;
delete [] morememory_;
}
};
TEST_GROUP(CanHaveMemberVariablesInTestGroupThatAllocateMemoryWithoutCausingMemoryLeaks)
{
AllocateAndDeallocateInConstructorAndDestructor dummy;
};
TEST(CanHaveMemberVariablesInTestGroupThatAllocateMemoryWithoutCausingMemoryLeaks, testInTestGroupName)
{
dummy.allocateMoreMemory();
}
static int getZero()
{
return 0;
}
static int getOne()
{
return 1;
}
TEST_GROUP(UtestShellPointerArrayTest)
{
UtestShell* test0;
UtestShell* test1;
UtestShell* test2;
void setup()
{
test0 = new IgnoredUtestShell();
test1 = new IgnoredUtestShell();
test2 = new IgnoredUtestShell();
test0->addTest(test1);
test1->addTest(test2);
}
void teardown()
{
delete test0;
delete test1;
delete test2;
}
};
TEST(UtestShellPointerArrayTest, empty)
{
UtestShellPointerArray tests(NULLPTR);
tests.shuffle(0);
CHECK(NULL == tests.getFirstTest());
}
TEST(UtestShellPointerArrayTest, testsAreInOrder)
{
UtestShellPointerArray tests(test0);
CHECK(tests.get(0) == test0);
CHECK(tests.get(1) == test1);
CHECK(tests.get(2) == test2);
}
TEST(UtestShellPointerArrayTest, relinkingTestsWillKeepThemTheSameWhenNothingWasDone)
{
UtestShellPointerArray tests(test0);
tests.relinkTestsInOrder();
CHECK(tests.get(0) == test0);
CHECK(tests.get(1) == test1);
CHECK(tests.get(2) == test2);
}
TEST(UtestShellPointerArrayTest, firstTestisNotTheFirstTestWithSeed1234)
{
UtestShellPointerArray tests(test0);
tests.shuffle(1234);
CHECK(tests.getFirstTest() != test0);
}
TEST(UtestShellPointerArrayTest, ShuffleListTestWithRandomAlwaysReturningZero)
{
UT_PTR_SET(PlatformSpecificRand, getZero);
UtestShellPointerArray tests(test0);
tests.shuffle(3);
CHECK(tests.get(0) == test1);
CHECK(tests.get(1) == test2);
CHECK(tests.get(2) == test0);
}
// swaps with 4 mod 3 (1) then 4 mod 2 (0): 1, [2], [0] --> [1], [0], 2 --> 0, 1, 2
TEST(UtestShellPointerArrayTest, ShuffleListTestWithRandomAlwaysReturningOne)
{
UT_PTR_SET(PlatformSpecificRand, getOne);
UtestShellPointerArray tests(test0);
tests.shuffle(3);
CHECK(tests.get(0) == test0);
CHECK(tests.get(1) == test2);
CHECK(tests.get(2) == test1);
}
TEST(UtestShellPointerArrayTest, reverse)
{
UT_PTR_SET(PlatformSpecificRand, getOne);
UtestShellPointerArray tests(test0);
tests.reverse();
CHECK(tests.get(0) == test2);
CHECK(tests.get(1) == test1);
CHECK(tests.get(2) == test0);
}
<commit_msg>Not use ifndef but use if<commit_after>/*
* Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde
* 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 <organization> 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 EARLIER MENTIONED AUTHORS ``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 <copyright holder> 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 "CppUTest/TestHarness.h"
#include "CppUTest/TestOutput.h"
#include "CppUTest/TestTestingFixture.h"
#include "CppUTest/PlatformSpecificFunctions.h"
TEST_GROUP(UtestShell)
{
TestTestingFixture fixture;
};
static void _failMethod()
{
FAIL("This test fails");
}
static void _passingTestMethod()
{
CHECK(true);
}
static void _passingCheckEqualTestMethod()
{
CHECK_EQUAL(1, 1);
}
static void _exitTestMethod()
{
TEST_EXIT;
FAIL("Should not get here");
}
static volatile double zero = 0.0;
TEST(UtestShell, compareDoubles)
{
double not_a_number = zero / zero;
double infinity = 1 / zero;
CHECK(doubles_equal(1.0, 1.001, 0.01));
CHECK(!doubles_equal(not_a_number, 1.001, 0.01));
CHECK(!doubles_equal(1.0, not_a_number, 0.01));
CHECK(!doubles_equal(1.0, 1.001, not_a_number));
CHECK(!doubles_equal(1.0, 1.1, 0.05));
CHECK(!doubles_equal(infinity, 1.0, 0.01));
CHECK(!doubles_equal(1.0, infinity, 0.01));
CHECK(doubles_equal(1.0, -1.0, infinity));
CHECK(doubles_equal(infinity, infinity, 0.01));
CHECK(doubles_equal(infinity, infinity, infinity));
double a = 1.2345678;
CHECK(doubles_equal(a, a, 0.000000001));
}
TEST(UtestShell, FailWillIncreaseTheAmountOfChecks)
{
fixture.setTestFunction(_failMethod);
fixture.runAllTests();
LONGS_EQUAL(1, fixture.getCheckCount());
}
TEST(UtestShell, PassedCheckEqualWillIncreaseTheAmountOfChecks)
{
fixture.setTestFunction(_passingCheckEqualTestMethod);
fixture.runAllTests();
LONGS_EQUAL(1, fixture.getCheckCount());
}
IGNORE_TEST(UtestShell, IgnoreTestAccessingFixture)
{
CHECK(&fixture != NULLPTR);
}
TEST(UtestShell, MacrosUsedInSetup)
{
IGNORE_ALL_LEAKS_IN_TEST();
fixture.setSetup(_failMethod);
fixture.setTestFunction(_passingTestMethod);
fixture.runAllTests();
LONGS_EQUAL(1, fixture.getFailureCount());
}
TEST(UtestShell, MacrosUsedInTearDown)
{
IGNORE_ALL_LEAKS_IN_TEST();
fixture.setTeardown(_failMethod);
fixture.setTestFunction(_passingTestMethod);
fixture.runAllTests();
LONGS_EQUAL(1, fixture.getFailureCount());
}
TEST(UtestShell, ExitLeavesQuietly)
{
fixture.setTestFunction(_exitTestMethod);
fixture.runAllTests();
LONGS_EQUAL(0, fixture.getFailureCount());
}
static int teardownCalled = 0;
static void _teardownMethod()
{
teardownCalled++;
}
TEST(UtestShell, TeardownCalledAfterTestFailure)
{
teardownCalled = 0;
IGNORE_ALL_LEAKS_IN_TEST();
fixture.setTeardown(_teardownMethod);
fixture.setTestFunction(_failMethod);
fixture.runAllTests();
LONGS_EQUAL(1, fixture.getFailureCount());
LONGS_EQUAL(1, teardownCalled);
}
static int stopAfterFailure = 0;
static void _stopAfterFailureMethod()
{
FAIL("fail");
stopAfterFailure++;
}
TEST(UtestShell, TestStopsAfterTestFailure)
{
IGNORE_ALL_LEAKS_IN_TEST();
stopAfterFailure = 0;
fixture.setTestFunction(_stopAfterFailureMethod);
fixture.runAllTests();
CHECK(fixture.hasTestFailed());
LONGS_EQUAL(1, fixture.getFailureCount());
LONGS_EQUAL(0, stopAfterFailure);
}
TEST(UtestShell, TestStopsAfterSetupFailure)
{
stopAfterFailure = 0;
fixture.setSetup(_stopAfterFailureMethod);
fixture.setTeardown(_stopAfterFailureMethod);
fixture.setTestFunction(_failMethod);
fixture.runAllTests();
LONGS_EQUAL(2, fixture.getFailureCount());
LONGS_EQUAL(0, stopAfterFailure);
}
class defaultUtestShell: public UtestShell
{
};
TEST(UtestShell, this_test_covers_the_UtestShell_createTest_and_Utest_testBody_methods)
{
defaultUtestShell shell;
fixture.addTest(&shell);
fixture.runAllTests();
LONGS_EQUAL(2, fixture.result_->getTestCount());
}
static void StubPlatformSpecificRunTestInASeperateProcess(UtestShell* shell, TestPlugin*, TestResult* result)
{
result->addFailure(TestFailure(shell, "Failed in separate process"));
}
TEST(UtestShell, RunInSeparateProcessTest)
{
UT_PTR_SET(PlatformSpecificRunTestInASeperateProcess, StubPlatformSpecificRunTestInASeperateProcess);
fixture.registry_->setRunTestsInSeperateProcess();
fixture.runAllTests();
fixture.assertPrintContains("Failed in separate process");
}
#if !CPPUTEST_HAVE_FORK
IGNORE_TEST(UtestShell, TestDefaultCrashMethodInSeparateProcessTest) {}
#else
TEST(UtestShell, TestDefaultCrashMethodInSeparateProcessTest)
{
fixture.setTestFunction(UtestShell::crash);
fixture.registry_->setRunTestsInSeperateProcess();
fixture.runAllTests();
fixture.assertPrintContains("Failed in separate process - killed by signal");
/* Signal 11 usually happens, but with clang3.7 on Linux, it produced signal 4 */
CHECK(fixture.getOutput().contains("signal 11") || fixture.getOutput().contains("signal 4"));
}
#endif
#if CPPUTEST_USE_STD_CPP_LIB
static bool destructorWasCalledOnFailedTest = false;
static void _destructorCalledForLocalObjects()
{
SetBooleanOnDestructorCall pleaseCallTheDestructor(destructorWasCalledOnFailedTest);
destructorWasCalledOnFailedTest = false;
FAIL("fail");
}
TEST(UtestShell, DestructorIsCalledForLocalObjectsWhenTheTestFails)
{
fixture.setTestFunction(_destructorCalledForLocalObjects);
fixture.runAllTests();
CHECK(destructorWasCalledOnFailedTest);
}
#endif
TEST_GROUP(IgnoredUtestShell)
{
TestTestingFixture fixture;
IgnoredUtestShell ignoredTest;
ExecFunctionTestShell normalUtestShell;
void setup() _override
{
fixture.addTest(&ignoredTest);
fixture.addTest(&normalUtestShell);
}
};
TEST(IgnoredUtestShell, doesIgnoreCount)
{
fixture.runAllTests();
LONGS_EQUAL(1, fixture.getIgnoreCount());
}
TEST(IgnoredUtestShell, printsIGNORE_TESTwhenVerbose)
{
fixture.output_->verbose();
fixture.runAllTests();
fixture.assertPrintContains("IGNORE_TEST");
}
TEST(IgnoredUtestShell, runIgnoredOptionSpecifiedThenIncreaseRunCount)
{
ignoredTest.setRunIgnored();
fixture.runAllTests();
LONGS_EQUAL(3, fixture.getRunCount());
LONGS_EQUAL(0, fixture.getIgnoreCount());
}
TEST(IgnoredUtestShell, runIgnoredOptionNotSpecifiedThenIncreaseIgnoredCount)
{
fixture.runAllTests();
LONGS_EQUAL(2, fixture.getRunCount());
LONGS_EQUAL(1, fixture.getIgnoreCount());
}
TEST(IgnoredUtestShell, runIgnoredOptionSpecifiedWillNotInfluenceNormalTestCount)
{
normalUtestShell.setRunIgnored();
fixture.runAllTests();
LONGS_EQUAL(2, fixture.getRunCount());
LONGS_EQUAL(1, fixture.getIgnoreCount());
}
TEST(IgnoredUtestShell, runIgnoredOptionSpecifiedThenReturnTESTInFormattedName)
{
ignoredTest.setGroupName("TestGroup");
ignoredTest.setTestName("TestName");
ignoredTest.setRunIgnored();
fixture.runAllTests();
STRCMP_EQUAL("TEST(TestGroup, TestName)", ignoredTest.getFormattedName().asCharString());
}
TEST(IgnoredUtestShell, runIgnoredOptionNotSpecifiedThenReturnIGNORETESTInFormattedName)
{
ignoredTest.setGroupName("TestGroup");
ignoredTest.setTestName("TestName");
fixture.runAllTests();
STRCMP_EQUAL("IGNORE_TEST(TestGroup, TestName)", ignoredTest.getFormattedName().asCharString());
}
TEST(IgnoredUtestShell, runIgnoredOptionNotSpecifiedThenWillRunReturnFalse)
{
CHECK_FALSE(ignoredTest.willRun());
}
TEST(IgnoredUtestShell, runIgnoredOptionSpecifiedThenWillRunReturnTrue)
{
ignoredTest.setRunIgnored();
CHECK_TRUE(ignoredTest.willRun());
}
TEST_BASE(MyOwnTest)
{
MyOwnTest() :
inTest(false)
{
}
bool inTest;
void setup()
{
CHECK(!inTest);
inTest = true;
}
void teardown()
{
CHECK(inTest);
inTest = false;
}
};
TEST_GROUP_BASE(UtestMyOwn, MyOwnTest)
{
};
TEST(UtestMyOwn, test)
{
CHECK(inTest);
}
class NullParameterTest: public UtestShell
{
};
TEST(UtestMyOwn, NullParameters)
{
NullParameterTest nullTest; /* Bug fix tests for creating a test without a name, fix in SimpleString */
TestFilter emptyFilter;
CHECK(nullTest.shouldRun(&emptyFilter, &emptyFilter));
}
class AllocateAndDeallocateInConstructorAndDestructor
{
char* memory_;
char* morememory_;
public:
AllocateAndDeallocateInConstructorAndDestructor()
{
memory_ = new char[100];
morememory_ = NULLPTR;
}
void allocateMoreMemory()
{
morememory_ = new char[123];
}
~AllocateAndDeallocateInConstructorAndDestructor()
{
delete [] memory_;
delete [] morememory_;
}
};
TEST_GROUP(CanHaveMemberVariablesInTestGroupThatAllocateMemoryWithoutCausingMemoryLeaks)
{
AllocateAndDeallocateInConstructorAndDestructor dummy;
};
TEST(CanHaveMemberVariablesInTestGroupThatAllocateMemoryWithoutCausingMemoryLeaks, testInTestGroupName)
{
dummy.allocateMoreMemory();
}
static int getZero()
{
return 0;
}
static int getOne()
{
return 1;
}
TEST_GROUP(UtestShellPointerArrayTest)
{
UtestShell* test0;
UtestShell* test1;
UtestShell* test2;
void setup()
{
test0 = new IgnoredUtestShell();
test1 = new IgnoredUtestShell();
test2 = new IgnoredUtestShell();
test0->addTest(test1);
test1->addTest(test2);
}
void teardown()
{
delete test0;
delete test1;
delete test2;
}
};
TEST(UtestShellPointerArrayTest, empty)
{
UtestShellPointerArray tests(NULLPTR);
tests.shuffle(0);
CHECK(NULL == tests.getFirstTest());
}
TEST(UtestShellPointerArrayTest, testsAreInOrder)
{
UtestShellPointerArray tests(test0);
CHECK(tests.get(0) == test0);
CHECK(tests.get(1) == test1);
CHECK(tests.get(2) == test2);
}
TEST(UtestShellPointerArrayTest, relinkingTestsWillKeepThemTheSameWhenNothingWasDone)
{
UtestShellPointerArray tests(test0);
tests.relinkTestsInOrder();
CHECK(tests.get(0) == test0);
CHECK(tests.get(1) == test1);
CHECK(tests.get(2) == test2);
}
TEST(UtestShellPointerArrayTest, firstTestisNotTheFirstTestWithSeed1234)
{
UtestShellPointerArray tests(test0);
tests.shuffle(1234);
CHECK(tests.getFirstTest() != test0);
}
TEST(UtestShellPointerArrayTest, ShuffleListTestWithRandomAlwaysReturningZero)
{
UT_PTR_SET(PlatformSpecificRand, getZero);
UtestShellPointerArray tests(test0);
tests.shuffle(3);
CHECK(tests.get(0) == test1);
CHECK(tests.get(1) == test2);
CHECK(tests.get(2) == test0);
}
// swaps with 4 mod 3 (1) then 4 mod 2 (0): 1, [2], [0] --> [1], [0], 2 --> 0, 1, 2
TEST(UtestShellPointerArrayTest, ShuffleListTestWithRandomAlwaysReturningOne)
{
UT_PTR_SET(PlatformSpecificRand, getOne);
UtestShellPointerArray tests(test0);
tests.shuffle(3);
CHECK(tests.get(0) == test0);
CHECK(tests.get(1) == test2);
CHECK(tests.get(2) == test1);
}
TEST(UtestShellPointerArrayTest, reverse)
{
UT_PTR_SET(PlatformSpecificRand, getOne);
UtestShellPointerArray tests(test0);
tests.reverse();
CHECK(tests.get(0) == test2);
CHECK(tests.get(1) == test1);
CHECK(tests.get(2) == test0);
}
<|endoftext|> |
<commit_before>/*===================================================================
APM_PLANNER Open Source Ground Control Station
(c) 2014 APM_PLANNER PROJECT <http://www.diydrones.com>
This file is part of the APM_PLANNER project
APM_PLANNER is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
APM_PLANNER 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 APM_PLANNER. If not, see <http://www.gnu.org/licenses/>.
======================================================================*/
/**
* @file
* @brief MAVLinkProtocol
* This class handles incoming mavlink_message_t packets.
* It will create a UAS class if one does not exist for a particular heartbeat systemid
* It will pass mavlink_message_t on to the UAS class for further parsing
*
* @author Michael Carpenter <[email protected]>
* @author QGROUNDCONTROL PROJECT - This code has GPLv3+ snippets from QGROUNDCONTROL, (c) 2009, 2010 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
*
*/
#include "MAVLinkProtocol.h"
#include "LinkManager.h"
MAVLinkProtocol::MAVLinkProtocol():
m_loggingEnabled(false),
m_logfile(NULL),
m_connectionManager(NULL),
m_isOnline(true)
{
}
MAVLinkProtocol::~MAVLinkProtocol()
{
stopLogging();
m_connectionManager = NULL;
}
void MAVLinkProtocol::sendMessage(mavlink_message_t msg)
{
Q_UNUSED(msg);
}
void MAVLinkProtocol::receiveBytes(LinkInterface* link, QByteArray b)
{
mavlink_message_t message;
mavlink_status_t status;
// Cache the link ID for common use.
int linkId = link->getId();
static int mavlink09Count = 0;
static int nonmavlinkCount = 0;
static bool decodedFirstPacket = false;
static bool warnedUser = false;
static bool checkedUserNonMavlink = false;
static bool warnedUserNonMavlink = false;
// FIXME: Add check for if link->getId() >= MAVLINK_COMM_NUM_BUFFERS
for (int position = 0; position < b.size(); position++) {
unsigned int decodeState = mavlink_parse_char(linkId, (uint8_t)(b[position]), &message, &status);
if ((uint8_t)b[position] == 0x55) mavlink09Count++;
if ((mavlink09Count > 100) && !decodedFirstPacket && !warnedUser)
{
warnedUser = true;
// Obviously the user tries to use a 0.9 autopilot
// with QGroundControl built for version 1.0
emit protocolStatusMessage("MAVLink Version or Baud Rate Mismatch", "Your MAVLink device seems to use the deprecated version 0.9, while APM Planner only supports version 1.0+. Please upgrade the MAVLink version of your autopilot. If your autopilot is using version 1.0, check if the baud rates of APM Planner and your autopilot are the same.");
}
if (decodeState == 0 && !decodedFirstPacket)
{
nonmavlinkCount++;
if (nonmavlinkCount > 2000 && !warnedUserNonMavlink)
{
//500 bytes with no mavlink message. Are we connected to a mavlink capable device?
if (!checkedUserNonMavlink)
{
link->requestReset();
nonmavlinkCount=0;
checkedUserNonMavlink = true;
}
else
{
warnedUserNonMavlink = true;
emit protocolStatusMessage("MAVLink Baud Rate Mismatch", "Please check if the baud rates of APM Planner and your autopilot are the same.");
}
}
}
if (decodeState == 1)
{
decodedFirstPacket = true;
if(message.msgid == MAVLINK_MSG_ID_PING)
{
// process ping requests (tgt_system and tgt_comp must be zero)
mavlink_ping_t ping;
mavlink_msg_ping_decode(&message, &ping);
if(!ping.target_system && !ping.target_component && m_isOnline)
{
mavlink_message_t msg;
mavlink_msg_ping_pack(getSystemId(), getComponentId(), &msg, ping.time_usec, ping.seq, message.sysid, message.compid);
sendMessage(msg);
}
}
#if defined(QGC_PROTOBUF_ENABLED)
if (message.msgid == MAVLINK_MSG_ID_EXTENDED_MESSAGE)
{
mavlink_extended_message_t extended_message;
extended_message.base_msg = message;
// read extended header
uint8_t* payload = reinterpret_cast<uint8_t*>(message.payload64);
memcpy(&extended_message.extended_payload_len, payload + 3, 4);
// Check if message is valid
if
(b.size() != MAVLINK_NUM_NON_PAYLOAD_BYTES+MAVLINK_EXTENDED_HEADER_LEN+ extended_message.extended_payload_len)
{
//invalid message
QLOG_DEBUG() << "GOT INVALID EXTENDED MESSAGE, ABORTING";
return;
}
const uint8_t* extended_payload = reinterpret_cast<const uint8_t*>(b.constData()) + MAVLINK_NUM_NON_PAYLOAD_BYTES + MAVLINK_EXTENDED_HEADER_LEN;
// copy extended payload data
memcpy(extended_message.extended_payload, extended_payload, extended_message.extended_payload_len);
#if defined(QGC_USE_PIXHAWK_MESSAGES)
if (protobufManager.cacheFragment(extended_message))
{
std::tr1::shared_ptr<google::protobuf::Message> protobuf_msg;
if (protobufManager.getMessage(protobuf_msg))
{
const google::protobuf::Descriptor* descriptor = protobuf_msg->GetDescriptor();
if (!descriptor)
{
continue;
}
const google::protobuf::FieldDescriptor* headerField = descriptor->FindFieldByName("header");
if (!headerField)
{
continue;
}
const google::protobuf::Descriptor* headerDescriptor = headerField->message_type();
if (!headerDescriptor)
{
continue;
}
const google::protobuf::FieldDescriptor* sourceSysIdField = headerDescriptor->FindFieldByName("source_sysid");
if (!sourceSysIdField)
{
continue;
}
const google::protobuf::Reflection* reflection = protobuf_msg->GetReflection();
const google::protobuf::Message& headerMsg = reflection->GetMessage(*protobuf_msg, headerField);
const google::protobuf::Reflection* headerReflection = headerMsg.GetReflection();
int source_sysid = headerReflection->GetInt32(headerMsg, sourceSysIdField);
UASInterface* uas = UASManager::instance()->getUASForId(source_sysid);
if (uas != NULL)
{
emit extendedMessageReceived(link, protobuf_msg);
}
}
}
#endif
position += extended_message.extended_payload_len;
continue;
}
#endif
// Log data
if (m_loggingEnabled && m_logfile)
{
quint64 time = QGC::groundTimeUsecs();
QDataStream outStream(m_logfile);
outStream.setByteOrder(QDataStream::BigEndian);
outStream << time; // write time stamp
// write headers, payload (incs CRC)
int bytesWritten = outStream.writeRawData((const char*)&message.magic,
static_cast<uint>(MAVLINK_NUM_NON_PAYLOAD_BYTES + message.len));
if(bytesWritten != (MAVLINK_NUM_NON_PAYLOAD_BYTES + message.len))
{
emit protocolStatusMessage(tr("MAVLink Logging failed"),
tr("Could not write to file %1, disabling logging.")
.arg(m_logfile->fileName()));
// Stop logging
stopLogging();
}
}
quint64 time = QGC::groundTimeUsecs();
m_mavlinkMsgBuffer[time] = message;
if (m_isOnline)
{
handleMessage(time,link);
}
}
}
}
void MAVLinkProtocol::handleMessage(quint64 timeid,LinkInterface *link)
{
mavlink_message_t message = m_mavlinkMsgBuffer.value(timeid);
unsigned int linkId = link->getId();
// ORDER MATTERS HERE!
// If the matching UAS object does not yet exist, it has to be created
// before emitting the packetReceived signal
//UASInterface* uas = UASManager::instance()->getUASForId(message.sysid);
Q_ASSERT_X(m_connectionManager != NULL, "MAVLinkProtocol::receiveBytes", " error:m_connectionManager == NULL");
UASInterface* uas = m_connectionManager->getUas(message.sysid);
//qDebug() << "MAVLinkProtocol::receiveBytes" << uas;
// Check and (if necessary) create UAS object
if (uas == NULL && message.msgid == MAVLINK_MSG_ID_HEARTBEAT)
{
// ORDER MATTERS HERE!
// The UAS object has first to be created and connected,
// only then the rest of the application can be made aware
// of its existence, as it only then can send and receive
// it's first messages.
// Check if the UAS has the same id like this system
if (message.sysid == getSystemId())
{
if (m_throwAwayGCSPackets)
{
//If replaying, we have to assume that it's just hearing ground control traffic
return;
}
emit protocolStatusMessage(tr("SYSTEM ID CONFLICT!"), tr("Warning: A second system is using the same system id (%1)").arg(getSystemId()));
}
// Create a new UAS based on the heartbeat received
// Todo dynamically load plugin at run-time for MAV
// WIKISEARCH:AUTOPILOT_TYPE_INSTANTIATION
// First create new UAS object
// Decode heartbeat message
mavlink_heartbeat_t heartbeat;
// Reset version field to 0
heartbeat.mavlink_version = 0;
mavlink_msg_heartbeat_decode(&message, &heartbeat);
// Check if the UAS has a different protocol version
if (m_enable_version_check && (heartbeat.mavlink_version != MAVLINK_VERSION))
{
// Bring up dialog to inform user
if (!versionMismatchIgnore)
{
emit protocolStatusMessage(tr("The MAVLink protocol version on the MAV and APM Planner mismatch!"),
tr("It is unsafe to use different MAVLink versions. APM Planner therefore refuses to connect to system %1, which sends MAVLink version %2 (APM Planner uses version %3).").arg(message.sysid).arg(heartbeat.mavlink_version).arg(MAVLINK_VERSION));
versionMismatchIgnore = true;
}
// Ignore this message and continue gracefully
return;
}
// Create a new UAS object
uas = m_connectionManager->createUAS(this,link,message.sysid,&heartbeat); //QGCMAVLinkUASFactory::createUAS(this, link, message.sysid, &heartbeat);
}
// Only count message if UAS exists for this message
if (uas != NULL)
{
// Increase receive counter
totalReceiveCounter[linkId]++;
currReceiveCounter[linkId]++;
// Update last message sequence ID
uint8_t expectedIndex;
if (lastIndex.contains(message.sysid))
{
if (lastIndex.value(message.sysid).contains(message.compid))
{
if (lastIndex.value(message.sysid).value(message.compid) == -1)
{
lastIndex[message.sysid][message.compid] = message.seq;
expectedIndex = message.seq;
}
else
{
expectedIndex = lastIndex[message.sysid][message.compid] + 1;
}
}
else
{
lastIndex[message.sysid].insert(message.compid,message.seq);
expectedIndex = message.seq;
}
}
else
{
lastIndex.insert(message.sysid,QMap<int,uint8_t>());
lastIndex[message.sysid].insert(message.compid,message.seq);
expectedIndex = message.seq;
}
// Make some noise if a message was skipped
//QLOG_DEBUG() << "SYSID" << message.sysid << "COMPID" << message.compid << "MSGID" << message.msgid << "EXPECTED INDEX:" << expectedIndex << "SEQ" << message.seq;
if (message.seq != expectedIndex)
{
// Determine how many messages were skipped accounting for 0-wraparound
int16_t lostMessages = message.seq - expectedIndex;
if (lostMessages < 0)
{
// Usually, this happens in the case of an out-of order packet
lostMessages = 0;
}
else
{
// Console generates excessive load at high loss rates, needs better GUI visualization
//QLOG_DEBUG() << QString("Lost %1 messages for comp %4: expected sequence ID %2 but received %3.").arg(lostMessages).arg(expectedIndex).arg(message.seq).arg(message.compid);
}
totalLossCounter[linkId] += lostMessages;
currLossCounter[linkId] += lostMessages;
}
// Update the last sequence ID
lastIndex[message.sysid][message.compid] = message.seq;
// Update on every 32th packet
if (totalReceiveCounter[linkId] % 32 == 0)
{
// Calculate new loss ratio
// Receive loss
float receiveLoss = (double)currLossCounter[linkId]/(double)(currReceiveCounter[linkId]+currLossCounter[linkId]);
receiveLoss *= 100.0f;
currLossCounter[linkId] = 0;
currReceiveCounter[linkId] = 0;
emit receiveLossChanged(message.sysid, receiveLoss);
}
// The packet is emitted as a whole, as it is only 255 - 261 bytes short
// kind of inefficient, but no issue for a groundstation pc.
// It buys as reentrancy for the whole code over all threads
emit messageReceived(link, message);
// Multiplex message if enabled
//if (m_multiplexingEnabled)
//{
// Get all links connected to this unit
//QList<LinkInterface*> links = LinkManager::instance()->getLinksForProtocol(this);
// Emit message on all links that are currently connected
//foreach (LinkInterface* currLink, links)
//{
// Only forward this message to the other links,
// not the link the message was received on
// if (currLink != link) sendMessage(currLink, message, message.sysid, message.compid);
//}
//}
}
}
void MAVLinkProtocol::stopLogging()
{
if (m_logfile && m_logfile->isOpen()){
QLOG_DEBUG() << "Stop MAVLink logging" << m_logfile->fileName();
// Close the current open file
m_logfile->close();
delete m_logfile;
m_logfile = NULL;
}
m_loggingEnabled = false;
}
bool MAVLinkProtocol::startLogging(const QString& filename)
{
if (m_logfile && m_logfile->isOpen())
{
return true;
}
stopLogging();
QLOG_DEBUG() << "Start MAVLink logging" << filename;
Q_ASSERT_X(m_logfile == NULL, "startLogging", "m_logFile == NULL");
m_logfile = new QFile(filename);
if (m_logfile->open(QIODevice::WriteOnly | QIODevice::Append)){
m_loggingEnabled = true;
} else {
emit protocolStatusMessage(tr("Started MAVLink logging"),
tr("FAILED: MAVLink cannot start logging to.").arg(m_logfile->fileName()));
m_loggingEnabled = false;
delete m_logfile;
m_logfile = NULL;
}
//emit loggingChanged(m_loggingEnabled);
return m_loggingEnabled; // reflects if logging started or not.
}
<commit_msg>MAVLink: Fix comparison to use correct type.<commit_after>/*===================================================================
APM_PLANNER Open Source Ground Control Station
(c) 2014 APM_PLANNER PROJECT <http://www.diydrones.com>
This file is part of the APM_PLANNER project
APM_PLANNER is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
APM_PLANNER 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 APM_PLANNER. If not, see <http://www.gnu.org/licenses/>.
======================================================================*/
/**
* @file
* @brief MAVLinkProtocol
* This class handles incoming mavlink_message_t packets.
* It will create a UAS class if one does not exist for a particular heartbeat systemid
* It will pass mavlink_message_t on to the UAS class for further parsing
*
* @author Michael Carpenter <[email protected]>
* @author QGROUNDCONTROL PROJECT - This code has GPLv3+ snippets from QGROUNDCONTROL, (c) 2009, 2010 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
*
*/
#include "MAVLinkProtocol.h"
#include "LinkManager.h"
MAVLinkProtocol::MAVLinkProtocol():
m_isOnline(true),
m_loggingEnabled(false),
m_logfile(NULL),
m_connectionManager(NULL)
{
}
MAVLinkProtocol::~MAVLinkProtocol()
{
stopLogging();
m_connectionManager = NULL;
}
void MAVLinkProtocol::sendMessage(mavlink_message_t msg)
{
Q_UNUSED(msg);
}
void MAVLinkProtocol::receiveBytes(LinkInterface* link, QByteArray b)
{
mavlink_message_t message;
mavlink_status_t status;
// Cache the link ID for common use.
int linkId = link->getId();
static int mavlink09Count = 0;
static int nonmavlinkCount = 0;
static bool decodedFirstPacket = false;
static bool warnedUser = false;
static bool checkedUserNonMavlink = false;
static bool warnedUserNonMavlink = false;
// FIXME: Add check for if link->getId() >= MAVLINK_COMM_NUM_BUFFERS
for (int position = 0; position < b.size(); position++) {
unsigned int decodeState = mavlink_parse_char(linkId, (uint8_t)(b[position]), &message, &status);
if ((uint8_t)b[position] == 0x55) mavlink09Count++;
if ((mavlink09Count > 100) && !decodedFirstPacket && !warnedUser)
{
warnedUser = true;
// Obviously the user tries to use a 0.9 autopilot
// with QGroundControl built for version 1.0
emit protocolStatusMessage("MAVLink Version or Baud Rate Mismatch", "Your MAVLink device seems to use the deprecated version 0.9, while APM Planner only supports version 1.0+. Please upgrade the MAVLink version of your autopilot. If your autopilot is using version 1.0, check if the baud rates of APM Planner and your autopilot are the same.");
}
if (decodeState == 0 && !decodedFirstPacket)
{
nonmavlinkCount++;
if (nonmavlinkCount > 2000 && !warnedUserNonMavlink)
{
//500 bytes with no mavlink message. Are we connected to a mavlink capable device?
if (!checkedUserNonMavlink)
{
link->requestReset();
nonmavlinkCount=0;
checkedUserNonMavlink = true;
}
else
{
warnedUserNonMavlink = true;
emit protocolStatusMessage("MAVLink Baud Rate Mismatch", "Please check if the baud rates of APM Planner and your autopilot are the same.");
}
}
}
if (decodeState == 1)
{
decodedFirstPacket = true;
if(message.msgid == MAVLINK_MSG_ID_PING)
{
// process ping requests (tgt_system and tgt_comp must be zero)
mavlink_ping_t ping;
mavlink_msg_ping_decode(&message, &ping);
if(!ping.target_system && !ping.target_component && m_isOnline)
{
mavlink_message_t msg;
mavlink_msg_ping_pack(getSystemId(), getComponentId(), &msg, ping.time_usec, ping.seq, message.sysid, message.compid);
sendMessage(msg);
}
}
#if defined(QGC_PROTOBUF_ENABLED)
if (message.msgid == MAVLINK_MSG_ID_EXTENDED_MESSAGE)
{
mavlink_extended_message_t extended_message;
extended_message.base_msg = message;
// read extended header
uint8_t* payload = reinterpret_cast<uint8_t*>(message.payload64);
memcpy(&extended_message.extended_payload_len, payload + 3, 4);
// Check if message is valid
if
(b.size() != MAVLINK_NUM_NON_PAYLOAD_BYTES+MAVLINK_EXTENDED_HEADER_LEN+ extended_message.extended_payload_len)
{
//invalid message
QLOG_DEBUG() << "GOT INVALID EXTENDED MESSAGE, ABORTING";
return;
}
const uint8_t* extended_payload = reinterpret_cast<const uint8_t*>(b.constData()) + MAVLINK_NUM_NON_PAYLOAD_BYTES + MAVLINK_EXTENDED_HEADER_LEN;
// copy extended payload data
memcpy(extended_message.extended_payload, extended_payload, extended_message.extended_payload_len);
#if defined(QGC_USE_PIXHAWK_MESSAGES)
if (protobufManager.cacheFragment(extended_message))
{
std::tr1::shared_ptr<google::protobuf::Message> protobuf_msg;
if (protobufManager.getMessage(protobuf_msg))
{
const google::protobuf::Descriptor* descriptor = protobuf_msg->GetDescriptor();
if (!descriptor)
{
continue;
}
const google::protobuf::FieldDescriptor* headerField = descriptor->FindFieldByName("header");
if (!headerField)
{
continue;
}
const google::protobuf::Descriptor* headerDescriptor = headerField->message_type();
if (!headerDescriptor)
{
continue;
}
const google::protobuf::FieldDescriptor* sourceSysIdField = headerDescriptor->FindFieldByName("source_sysid");
if (!sourceSysIdField)
{
continue;
}
const google::protobuf::Reflection* reflection = protobuf_msg->GetReflection();
const google::protobuf::Message& headerMsg = reflection->GetMessage(*protobuf_msg, headerField);
const google::protobuf::Reflection* headerReflection = headerMsg.GetReflection();
int source_sysid = headerReflection->GetInt32(headerMsg, sourceSysIdField);
UASInterface* uas = UASManager::instance()->getUASForId(source_sysid);
if (uas != NULL)
{
emit extendedMessageReceived(link, protobuf_msg);
}
}
}
#endif
position += extended_message.extended_payload_len;
continue;
}
#endif
// Log data
if (m_loggingEnabled && m_logfile)
{
quint64 time = QGC::groundTimeUsecs();
QDataStream outStream(m_logfile);
outStream.setByteOrder(QDataStream::BigEndian);
outStream << time; // write time stamp
// write headers, payload (incs CRC)
int bytesWritten = outStream.writeRawData((const char*)&message.magic,
static_cast<uint>(MAVLINK_NUM_NON_PAYLOAD_BYTES + message.len));
if(bytesWritten != (MAVLINK_NUM_NON_PAYLOAD_BYTES + message.len))
{
emit protocolStatusMessage(tr("MAVLink Logging failed"),
tr("Could not write to file %1, disabling logging.")
.arg(m_logfile->fileName()));
// Stop logging
stopLogging();
}
}
quint64 time = QGC::groundTimeUsecs();
m_mavlinkMsgBuffer[time] = message;
if (m_isOnline)
{
handleMessage(time,link);
}
}
}
}
void MAVLinkProtocol::handleMessage(quint64 timeid,LinkInterface *link)
{
mavlink_message_t message = m_mavlinkMsgBuffer.value(timeid);
unsigned int linkId = link->getId();
// ORDER MATTERS HERE!
// If the matching UAS object does not yet exist, it has to be created
// before emitting the packetReceived signal
//UASInterface* uas = UASManager::instance()->getUASForId(message.sysid);
Q_ASSERT_X(m_connectionManager != NULL, "MAVLinkProtocol::receiveBytes", " error:m_connectionManager == NULL");
UASInterface* uas = m_connectionManager->getUas(message.sysid);
//qDebug() << "MAVLinkProtocol::receiveBytes" << uas;
// Check and (if necessary) create UAS object
if (uas == NULL && message.msgid == MAVLINK_MSG_ID_HEARTBEAT)
{
// ORDER MATTERS HERE!
// The UAS object has first to be created and connected,
// only then the rest of the application can be made aware
// of its existence, as it only then can send and receive
// it's first messages.
// Check if the UAS has the same id like this system
if (message.sysid == getSystemId())
{
if (m_throwAwayGCSPackets)
{
//If replaying, we have to assume that it's just hearing ground control traffic
return;
}
emit protocolStatusMessage(tr("SYSTEM ID CONFLICT!"), tr("Warning: A second system is using the same system id (%1)").arg(getSystemId()));
}
// Create a new UAS based on the heartbeat received
// Todo dynamically load plugin at run-time for MAV
// WIKISEARCH:AUTOPILOT_TYPE_INSTANTIATION
// First create new UAS object
// Decode heartbeat message
mavlink_heartbeat_t heartbeat;
// Reset version field to 0
heartbeat.mavlink_version = 0;
mavlink_msg_heartbeat_decode(&message, &heartbeat);
// Check if the UAS has a different protocol version
if (m_enable_version_check && (heartbeat.mavlink_version != MAVLINK_VERSION))
{
// Bring up dialog to inform user
if (!versionMismatchIgnore)
{
emit protocolStatusMessage(tr("The MAVLink protocol version on the MAV and APM Planner mismatch!"),
tr("It is unsafe to use different MAVLink versions. APM Planner therefore refuses to connect to system %1, which sends MAVLink version %2 (APM Planner uses version %3).").arg(message.sysid).arg(heartbeat.mavlink_version).arg(MAVLINK_VERSION));
versionMismatchIgnore = true;
}
// Ignore this message and continue gracefully
return;
}
// Create a new UAS object
uas = m_connectionManager->createUAS(this,link,message.sysid,&heartbeat); //QGCMAVLinkUASFactory::createUAS(this, link, message.sysid, &heartbeat);
}
// Only count message if UAS exists for this message
if (uas != NULL)
{
// Increase receive counter
totalReceiveCounter[linkId]++;
currReceiveCounter[linkId]++;
// Update last message sequence ID
uint8_t expectedIndex;
if (lastIndex.contains(message.sysid))
{
if (lastIndex.value(message.sysid).contains(message.compid))
{
if (lastIndex.value(message.sysid).value(message.compid) == static_cast<uint8_t>(-1))
{
lastIndex[message.sysid][message.compid] = message.seq;
expectedIndex = message.seq;
}
else
{
expectedIndex = lastIndex[message.sysid][message.compid] + 1;
}
}
else
{
lastIndex[message.sysid].insert(message.compid,message.seq);
expectedIndex = message.seq;
}
}
else
{
lastIndex.insert(message.sysid,QMap<int,uint8_t>());
lastIndex[message.sysid].insert(message.compid,message.seq);
expectedIndex = message.seq;
}
// Make some noise if a message was skipped
//QLOG_DEBUG() << "SYSID" << message.sysid << "COMPID" << message.compid << "MSGID" << message.msgid << "EXPECTED INDEX:" << expectedIndex << "SEQ" << message.seq;
if (message.seq != expectedIndex)
{
// Determine how many messages were skipped accounting for 0-wraparound
int16_t lostMessages = message.seq - expectedIndex;
if (lostMessages < 0)
{
// Usually, this happens in the case of an out-of order packet
lostMessages = 0;
}
else
{
// Console generates excessive load at high loss rates, needs better GUI visualization
//QLOG_DEBUG() << QString("Lost %1 messages for comp %4: expected sequence ID %2 but received %3.").arg(lostMessages).arg(expectedIndex).arg(message.seq).arg(message.compid);
}
totalLossCounter[linkId] += lostMessages;
currLossCounter[linkId] += lostMessages;
}
// Update the last sequence ID
lastIndex[message.sysid][message.compid] = message.seq;
// Update on every 32th packet
if (totalReceiveCounter[linkId] % 32 == 0)
{
// Calculate new loss ratio
// Receive loss
float receiveLoss = (double)currLossCounter[linkId]/(double)(currReceiveCounter[linkId]+currLossCounter[linkId]);
receiveLoss *= 100.0f;
currLossCounter[linkId] = 0;
currReceiveCounter[linkId] = 0;
emit receiveLossChanged(message.sysid, receiveLoss);
}
// The packet is emitted as a whole, as it is only 255 - 261 bytes short
// kind of inefficient, but no issue for a groundstation pc.
// It buys as reentrancy for the whole code over all threads
emit messageReceived(link, message);
// Multiplex message if enabled
//if (m_multiplexingEnabled)
//{
// Get all links connected to this unit
//QList<LinkInterface*> links = LinkManager::instance()->getLinksForProtocol(this);
// Emit message on all links that are currently connected
//foreach (LinkInterface* currLink, links)
//{
// Only forward this message to the other links,
// not the link the message was received on
// if (currLink != link) sendMessage(currLink, message, message.sysid, message.compid);
//}
//}
}
}
void MAVLinkProtocol::stopLogging()
{
if (m_logfile && m_logfile->isOpen()){
QLOG_DEBUG() << "Stop MAVLink logging" << m_logfile->fileName();
// Close the current open file
m_logfile->close();
delete m_logfile;
m_logfile = NULL;
}
m_loggingEnabled = false;
}
bool MAVLinkProtocol::startLogging(const QString& filename)
{
if (m_logfile && m_logfile->isOpen())
{
return true;
}
stopLogging();
QLOG_DEBUG() << "Start MAVLink logging" << filename;
Q_ASSERT_X(m_logfile == NULL, "startLogging", "m_logFile == NULL");
m_logfile = new QFile(filename);
if (m_logfile->open(QIODevice::WriteOnly | QIODevice::Append)){
m_loggingEnabled = true;
} else {
emit protocolStatusMessage(tr("Started MAVLink logging"),
tr("FAILED: MAVLink cannot start logging to.").arg(m_logfile->fileName()));
m_loggingEnabled = false;
delete m_logfile;
m_logfile = NULL;
}
//emit loggingChanged(m_loggingEnabled);
return m_loggingEnabled; // reflects if logging started or not.
}
<|endoftext|> |
<commit_before>/*===================================================================
APM_PLANNER Open Source Ground Control Station
(c) 2014 APM_PLANNER PROJECT <http://www.diydrones.com>
This file is part of the APM_PLANNER project
APM_PLANNER is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
APM_PLANNER 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 APM_PLANNER. If not, see <http://www.gnu.org/licenses/>.
======================================================================*/
/**
* @file
* @brief MAVLinkProtocol
* This class handles incoming mavlink_message_t packets.
* It will create a UAS class if one does not exist for a particular heartbeat systemid
* It will pass mavlink_message_t on to the UAS class for further parsing
*
* @author Michael Carpenter <[email protected]>
* @author QGROUNDCONTROL PROJECT - This code has GPLv3+ snippets from QGROUNDCONTROL, (c) 2009, 2010 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
*
*/
#include "MAVLinkProtocol.h"
#include "LinkManager.h"
MAVLinkProtocol::MAVLinkProtocol(QObject *parent)
{
m_loggingEnabled = false;
m_logfile=NULL;
}
void MAVLinkProtocol::receiveBytes(LinkInterface* link, QByteArray b)
{
mavlink_message_t message;
mavlink_status_t status;
// Cache the link ID for common use.
int linkId = link->getId();
static int mavlink09Count = 0;
static int nonmavlinkCount = 0;
static bool decodedFirstPacket = false;
static bool warnedUser = false;
static bool checkedUserNonMavlink = false;
static bool warnedUserNonMavlink = false;
// FIXME: Add check for if link->getId() >= MAVLINK_COMM_NUM_BUFFERS
for (int position = 0; position < b.size(); position++) {
unsigned int decodeState = mavlink_parse_char(linkId, (uint8_t)(b[position]), &message, &status);
if ((uint8_t)b[position] == 0x55) mavlink09Count++;
if ((mavlink09Count > 100) && !decodedFirstPacket && !warnedUser)
{
warnedUser = true;
// Obviously the user tries to use a 0.9 autopilot
// with QGroundControl built for version 1.0
emit protocolStatusMessage("MAVLink Version or Baud Rate Mismatch", "Your MAVLink device seems to use the deprecated version 0.9, while APM Planner only supports version 1.0+. Please upgrade the MAVLink version of your autopilot. If your autopilot is using version 1.0, check if the baud rates of APM Planner and your autopilot are the same.");
}
if (decodeState == 0 && !decodedFirstPacket)
{
nonmavlinkCount++;
if (nonmavlinkCount > 2000 && !warnedUserNonMavlink)
{
//500 bytes with no mavlink message. Are we connected to a mavlink capable device?
if (!checkedUserNonMavlink)
{
link->requestReset();
nonmavlinkCount=0;
checkedUserNonMavlink = true;
}
else
{
warnedUserNonMavlink = true;
emit protocolStatusMessage("MAVLink Baud Rate Mismatch", "Please check if the baud rates of APM Planner and your autopilot are the same.");
}
}
}
if (decodeState == 1)
{
decodedFirstPacket = true;
if(message.msgid == MAVLINK_MSG_ID_PING)
{
// process ping requests (tgt_system and tgt_comp must be zero)
mavlink_ping_t ping;
mavlink_msg_ping_decode(&message, &ping);
if(!ping.target_system && !ping.target_component)
{
mavlink_message_t msg;
mavlink_msg_ping_pack(getSystemId(), getComponentId(), &msg, ping.time_usec, ping.seq, message.sysid, message.compid);
sendMessage(msg);
}
}
#if defined(QGC_PROTOBUF_ENABLED)
if (message.msgid == MAVLINK_MSG_ID_EXTENDED_MESSAGE)
{
mavlink_extended_message_t extended_message;
extended_message.base_msg = message;
// read extended header
uint8_t* payload = reinterpret_cast<uint8_t*>(message.payload64);
memcpy(&extended_message.extended_payload_len, payload + 3, 4);
// Check if message is valid
if
(b.size() != MAVLINK_NUM_NON_PAYLOAD_BYTES+MAVLINK_EXTENDED_HEADER_LEN+ extended_message.extended_payload_len)
{
//invalid message
QLOG_DEBUG() << "GOT INVALID EXTENDED MESSAGE, ABORTING";
return;
}
const uint8_t* extended_payload = reinterpret_cast<const uint8_t*>(b.constData()) + MAVLINK_NUM_NON_PAYLOAD_BYTES + MAVLINK_EXTENDED_HEADER_LEN;
// copy extended payload data
memcpy(extended_message.extended_payload, extended_payload, extended_message.extended_payload_len);
#if defined(QGC_USE_PIXHAWK_MESSAGES)
if (protobufManager.cacheFragment(extended_message))
{
std::tr1::shared_ptr<google::protobuf::Message> protobuf_msg;
if (protobufManager.getMessage(protobuf_msg))
{
const google::protobuf::Descriptor* descriptor = protobuf_msg->GetDescriptor();
if (!descriptor)
{
continue;
}
const google::protobuf::FieldDescriptor* headerField = descriptor->FindFieldByName("header");
if (!headerField)
{
continue;
}
const google::protobuf::Descriptor* headerDescriptor = headerField->message_type();
if (!headerDescriptor)
{
continue;
}
const google::protobuf::FieldDescriptor* sourceSysIdField = headerDescriptor->FindFieldByName("source_sysid");
if (!sourceSysIdField)
{
continue;
}
const google::protobuf::Reflection* reflection = protobuf_msg->GetReflection();
const google::protobuf::Message& headerMsg = reflection->GetMessage(*protobuf_msg, headerField);
const google::protobuf::Reflection* headerReflection = headerMsg.GetReflection();
int source_sysid = headerReflection->GetInt32(headerMsg, sourceSysIdField);
UASInterface* uas = UASManager::instance()->getUASForId(source_sysid);
if (uas != NULL)
{
emit extendedMessageReceived(link, protobuf_msg);
}
}
}
#endif
position += extended_message.extended_payload_len;
continue;
}
#endif
// Log data
if (m_loggingEnabled && m_logfile)
{
quint64 time = QGC::groundTimeUsecs();
QDataStream outStream(m_logfile);
outStream.setByteOrder(QDataStream::BigEndian);
outStream << time; // write time stamp
// write headers, payload (incs CRC)
int bytesWritten = outStream.writeRawData((const char*)&message.magic,
static_cast<uint>(MAVLINK_NUM_NON_PAYLOAD_BYTES + message.len));
if(bytesWritten != (MAVLINK_NUM_NON_PAYLOAD_BYTES + message.len))
{
emit protocolStatusMessage(tr("MAVLink Logging failed"),
tr("Could not write to file %1, disabling logging.")
.arg(m_logfile->fileName()));
// Stop logging
stopLogging();
}
}
// ORDER MATTERS HERE!
// If the matching UAS object does not yet exist, it has to be created
// before emitting the packetReceived signal
//UASInterface* uas = UASManager::instance()->getUASForId(message.sysid);
UASInterface* uas = m_connectionManager->getUas(message.sysid);
//qDebug() << "MAVLinkProtocol::receiveBytes" << uas;
// Check and (if necessary) create UAS object
if (uas == NULL && message.msgid == MAVLINK_MSG_ID_HEARTBEAT)
{
// ORDER MATTERS HERE!
// The UAS object has first to be created and connected,
// only then the rest of the application can be made aware
// of its existence, as it only then can send and receive
// it's first messages.
// Check if the UAS has the same id like this system
if (message.sysid == getSystemId())
{
if (m_throwAwayGCSPackets)
{
//If replaying, we have to assume that it's just hearing ground control traffic
return;
}
emit protocolStatusMessage(tr("SYSTEM ID CONFLICT!"), tr("Warning: A second system is using the same system id (%1)").arg(getSystemId()));
}
// Create a new UAS based on the heartbeat received
// Todo dynamically load plugin at run-time for MAV
// WIKISEARCH:AUTOPILOT_TYPE_INSTANTIATION
// First create new UAS object
// Decode heartbeat message
mavlink_heartbeat_t heartbeat;
// Reset version field to 0
heartbeat.mavlink_version = 0;
mavlink_msg_heartbeat_decode(&message, &heartbeat);
// Check if the UAS has a different protocol version
if (m_enable_version_check && (heartbeat.mavlink_version != MAVLINK_VERSION))
{
// Bring up dialog to inform user
if (!versionMismatchIgnore)
{
emit protocolStatusMessage(tr("The MAVLink protocol version on the MAV and APM Planner mismatch!"),
tr("It is unsafe to use different MAVLink versions. APM Planner therefore refuses to connect to system %1, which sends MAVLink version %2 (APM Planner uses version %3).").arg(message.sysid).arg(heartbeat.mavlink_version).arg(MAVLINK_VERSION));
versionMismatchIgnore = true;
}
// Ignore this message and continue gracefully
continue;
}
// Create a new UAS object
uas = m_connectionManager->createUAS(this,link,message.sysid,&heartbeat); //QGCMAVLinkUASFactory::createUAS(this, link, message.sysid, &heartbeat);
}
// Only count message if UAS exists for this message
if (uas != NULL)
{
// Increase receive counter
totalReceiveCounter[linkId]++;
currReceiveCounter[linkId]++;
// Update last message sequence ID
uint8_t expectedIndex;
if (lastIndex.contains(message.sysid))
{
if (lastIndex.value(message.sysid).contains(message.compid))
{
if (lastIndex.value(message.sysid).value(message.compid) == -1)
{
lastIndex[message.sysid][message.compid] = message.seq;
expectedIndex = message.seq;
}
else
{
expectedIndex = lastIndex[message.sysid][message.compid] + 1;
}
}
else
{
lastIndex[message.sysid].insert(message.compid,message.seq);
expectedIndex = message.seq;
}
}
else
{
lastIndex.insert(message.sysid,QMap<int,uint8_t>());
lastIndex[message.sysid].insert(message.compid,message.seq);
expectedIndex = message.seq;
}
// Make some noise if a message was skipped
//QLOG_DEBUG() << "SYSID" << message.sysid << "COMPID" << message.compid << "MSGID" << message.msgid << "EXPECTED INDEX:" << expectedIndex << "SEQ" << message.seq;
if (message.seq != expectedIndex)
{
// Determine how many messages were skipped accounting for 0-wraparound
int16_t lostMessages = message.seq - expectedIndex;
if (lostMessages < 0)
{
// Usually, this happens in the case of an out-of order packet
lostMessages = 0;
}
else
{
// Console generates excessive load at high loss rates, needs better GUI visualization
//QLOG_DEBUG() << QString("Lost %1 messages for comp %4: expected sequence ID %2 but received %3.").arg(lostMessages).arg(expectedIndex).arg(message.seq).arg(message.compid);
}
totalLossCounter[linkId] += lostMessages;
currLossCounter[linkId] += lostMessages;
}
// Update the last sequence ID
lastIndex[message.sysid][message.compid] = message.seq;
// Update on every 32th packet
if (totalReceiveCounter[linkId] % 32 == 0)
{
// Calculate new loss ratio
// Receive loss
float receiveLoss = (double)currLossCounter[linkId]/(double)(currReceiveCounter[linkId]+currLossCounter[linkId]);
receiveLoss *= 100.0f;
currLossCounter[linkId] = 0;
currReceiveCounter[linkId] = 0;
emit receiveLossChanged(message.sysid, receiveLoss);
}
// The packet is emitted as a whole, as it is only 255 - 261 bytes short
// kind of inefficient, but no issue for a groundstation pc.
// It buys as reentrancy for the whole code over all threads
emit messageReceived(link, message);
// Multiplex message if enabled
//if (m_multiplexingEnabled)
//{
// Get all links connected to this unit
//QList<LinkInterface*> links = LinkManager::instance()->getLinksForProtocol(this);
// Emit message on all links that are currently connected
//foreach (LinkInterface* currLink, links)
//{
// Only forward this message to the other links,
// not the link the message was received on
// if (currLink != link) sendMessage(currLink, message, message.sysid, message.compid);
//}
//}
}
}
}
}
void MAVLinkProtocol::stopLogging()
{
if (m_logfile && m_logfile->isOpen()){
QLOG_DEBUG() << "Stop MAVLink logging" << m_logfile->fileName();
// Close the current open file
m_logfile->close();
delete m_logfile;
m_logfile = NULL;
}
m_loggingEnabled = false;
}
bool MAVLinkProtocol::startLogging(const QString& filename)
{
if (m_logfile && m_logfile->isOpen())
{
return true;
}
stopLogging();
QLOG_DEBUG() << "Start MAVLink logging" << filename;
Q_ASSERT_X(m_logfile == NULL, "startLogging", "m_logFile == NULL");
m_logfile = new QFile(filename);
if (m_logfile->open(QIODevice::WriteOnly | QIODevice::Append)){
m_loggingEnabled = true;
} else {
emit protocolStatusMessage(tr("Started MAVLink logging"),
tr("FAILED: MAVLink cannot start logging to.").arg(m_logfile->fileName()));
m_loggingEnabled = false;
delete m_logfile;
m_logfile = NULL;
}
//emit loggingChanged(m_loggingEnabled);
return m_loggingEnabled; // reflects if logging started or not.
}
<commit_msg>Comms: Fix to undo tautological code<commit_after>/*===================================================================
APM_PLANNER Open Source Ground Control Station
(c) 2014 APM_PLANNER PROJECT <http://www.diydrones.com>
This file is part of the APM_PLANNER project
APM_PLANNER is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
APM_PLANNER 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 APM_PLANNER. If not, see <http://www.gnu.org/licenses/>.
======================================================================*/
/**
* @file
* @brief MAVLinkProtocol
* This class handles incoming mavlink_message_t packets.
* It will create a UAS class if one does not exist for a particular heartbeat systemid
* It will pass mavlink_message_t on to the UAS class for further parsing
*
* @author Michael Carpenter <[email protected]>
* @author QGROUNDCONTROL PROJECT - This code has GPLv3+ snippets from QGROUNDCONTROL, (c) 2009, 2010 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
*
*/
#include "MAVLinkProtocol.h"
#include "LinkManager.h"
MAVLinkProtocol::MAVLinkProtocol(QObject *parent)
{
m_loggingEnabled = false;
m_logfile=NULL;
}
void MAVLinkProtocol::receiveBytes(LinkInterface* link, QByteArray b)
{
mavlink_message_t message;
mavlink_status_t status;
// Cache the link ID for common use.
int linkId = link->getId();
static int mavlink09Count = 0;
static int nonmavlinkCount = 0;
static bool decodedFirstPacket = false;
static bool warnedUser = false;
static bool checkedUserNonMavlink = false;
static bool warnedUserNonMavlink = false;
// FIXME: Add check for if link->getId() >= MAVLINK_COMM_NUM_BUFFERS
for (int position = 0; position < b.size(); position++) {
unsigned int decodeState = mavlink_parse_char(linkId, (uint8_t)(b[position]), &message, &status);
if ((uint8_t)b[position] == 0x55) mavlink09Count++;
if ((mavlink09Count > 100) && !decodedFirstPacket && !warnedUser)
{
warnedUser = true;
// Obviously the user tries to use a 0.9 autopilot
// with QGroundControl built for version 1.0
emit protocolStatusMessage("MAVLink Version or Baud Rate Mismatch", "Your MAVLink device seems to use the deprecated version 0.9, while APM Planner only supports version 1.0+. Please upgrade the MAVLink version of your autopilot. If your autopilot is using version 1.0, check if the baud rates of APM Planner and your autopilot are the same.");
}
if (decodeState == 0 && !decodedFirstPacket)
{
nonmavlinkCount++;
if (nonmavlinkCount > 2000 && !warnedUserNonMavlink)
{
//500 bytes with no mavlink message. Are we connected to a mavlink capable device?
if (!checkedUserNonMavlink)
{
link->requestReset();
nonmavlinkCount=0;
checkedUserNonMavlink = true;
}
else
{
warnedUserNonMavlink = true;
emit protocolStatusMessage("MAVLink Baud Rate Mismatch", "Please check if the baud rates of APM Planner and your autopilot are the same.");
}
}
}
if (decodeState == 1)
{
decodedFirstPacket = true;
if(message.msgid == MAVLINK_MSG_ID_PING)
{
// process ping requests (tgt_system and tgt_comp must be zero)
mavlink_ping_t ping;
mavlink_msg_ping_decode(&message, &ping);
if(!ping.target_system && !ping.target_component)
{
mavlink_message_t msg;
mavlink_msg_ping_pack(getSystemId(), getComponentId(), &msg, ping.time_usec, ping.seq, message.sysid, message.compid);
sendMessage(msg);
}
}
#if defined(QGC_PROTOBUF_ENABLED)
if (message.msgid == MAVLINK_MSG_ID_EXTENDED_MESSAGE)
{
mavlink_extended_message_t extended_message;
extended_message.base_msg = message;
// read extended header
uint8_t* payload = reinterpret_cast<uint8_t*>(message.payload64);
memcpy(&extended_message.extended_payload_len, payload + 3, 4);
// Check if message is valid
if
(b.size() != MAVLINK_NUM_NON_PAYLOAD_BYTES+MAVLINK_EXTENDED_HEADER_LEN+ extended_message.extended_payload_len)
{
//invalid message
QLOG_DEBUG() << "GOT INVALID EXTENDED MESSAGE, ABORTING";
return;
}
const uint8_t* extended_payload = reinterpret_cast<const uint8_t*>(b.constData()) + MAVLINK_NUM_NON_PAYLOAD_BYTES + MAVLINK_EXTENDED_HEADER_LEN;
// copy extended payload data
memcpy(extended_message.extended_payload, extended_payload, extended_message.extended_payload_len);
#if defined(QGC_USE_PIXHAWK_MESSAGES)
if (protobufManager.cacheFragment(extended_message))
{
std::tr1::shared_ptr<google::protobuf::Message> protobuf_msg;
if (protobufManager.getMessage(protobuf_msg))
{
const google::protobuf::Descriptor* descriptor = protobuf_msg->GetDescriptor();
if (!descriptor)
{
continue;
}
const google::protobuf::FieldDescriptor* headerField = descriptor->FindFieldByName("header");
if (!headerField)
{
continue;
}
const google::protobuf::Descriptor* headerDescriptor = headerField->message_type();
if (!headerDescriptor)
{
continue;
}
const google::protobuf::FieldDescriptor* sourceSysIdField = headerDescriptor->FindFieldByName("source_sysid");
if (!sourceSysIdField)
{
continue;
}
const google::protobuf::Reflection* reflection = protobuf_msg->GetReflection();
const google::protobuf::Message& headerMsg = reflection->GetMessage(*protobuf_msg, headerField);
const google::protobuf::Reflection* headerReflection = headerMsg.GetReflection();
int source_sysid = headerReflection->GetInt32(headerMsg, sourceSysIdField);
UASInterface* uas = UASManager::instance()->getUASForId(source_sysid);
if (uas != NULL)
{
emit extendedMessageReceived(link, protobuf_msg);
}
}
}
#endif
position += extended_message.extended_payload_len;
continue;
}
#endif
// Log data
if (m_loggingEnabled && m_logfile)
{
quint64 time = QGC::groundTimeUsecs();
QDataStream outStream(m_logfile);
outStream.setByteOrder(QDataStream::BigEndian);
outStream << time; // write time stamp
// write headers, payload (incs CRC)
int bytesWritten = outStream.writeRawData((const char*)&message.magic,
static_cast<uint>(MAVLINK_NUM_NON_PAYLOAD_BYTES + message.len));
if(bytesWritten != (MAVLINK_NUM_NON_PAYLOAD_BYTES + message.len))
{
emit protocolStatusMessage(tr("MAVLink Logging failed"),
tr("Could not write to file %1, disabling logging.")
.arg(m_logfile->fileName()));
// Stop logging
stopLogging();
}
}
// ORDER MATTERS HERE!
// If the matching UAS object does not yet exist, it has to be created
// before emitting the packetReceived signal
//UASInterface* uas = UASManager::instance()->getUASForId(message.sysid);
UASInterface* uas = m_connectionManager->getUas(message.sysid);
//qDebug() << "MAVLinkProtocol::receiveBytes" << uas;
// Check and (if necessary) create UAS object
if (uas == NULL && message.msgid == MAVLINK_MSG_ID_HEARTBEAT)
{
// ORDER MATTERS HERE!
// The UAS object has first to be created and connected,
// only then the rest of the application can be made aware
// of its existence, as it only then can send and receive
// it's first messages.
// Check if the UAS has the same id like this system
if (message.sysid == getSystemId())
{
if (m_throwAwayGCSPackets)
{
//If replaying, we have to assume that it's just hearing ground control traffic
return;
}
emit protocolStatusMessage(tr("SYSTEM ID CONFLICT!"), tr("Warning: A second system is using the same system id (%1)").arg(getSystemId()));
}
// Create a new UAS based on the heartbeat received
// Todo dynamically load plugin at run-time for MAV
// WIKISEARCH:AUTOPILOT_TYPE_INSTANTIATION
// First create new UAS object
// Decode heartbeat message
mavlink_heartbeat_t heartbeat;
// Reset version field to 0
heartbeat.mavlink_version = 0;
mavlink_msg_heartbeat_decode(&message, &heartbeat);
// Check if the UAS has a different protocol version
if (m_enable_version_check && (heartbeat.mavlink_version != MAVLINK_VERSION))
{
// Bring up dialog to inform user
if (!versionMismatchIgnore)
{
emit protocolStatusMessage(tr("The MAVLink protocol version on the MAV and APM Planner mismatch!"),
tr("It is unsafe to use different MAVLink versions. APM Planner therefore refuses to connect to system %1, which sends MAVLink version %2 (APM Planner uses version %3).").arg(message.sysid).arg(heartbeat.mavlink_version).arg(MAVLINK_VERSION));
versionMismatchIgnore = true;
}
// Ignore this message and continue gracefully
continue;
}
// Create a new UAS object
uas = m_connectionManager->createUAS(this,link,message.sysid,&heartbeat); //QGCMAVLinkUASFactory::createUAS(this, link, message.sysid, &heartbeat);
}
// Only count message if UAS exists for this message
if (uas != NULL)
{
// Increase receive counter
totalReceiveCounter[linkId]++;
currReceiveCounter[linkId]++;
// Update last message sequence ID
uint8_t expectedIndex;
if (lastIndex.contains(message.sysid))
{
if (lastIndex.value(message.sysid).contains(message.compid))
{
if (lastIndex.value(message.sysid).value(message.compid) == static_cast<uint8_t>(-1))
{
lastIndex[message.sysid][message.compid] = message.seq;
expectedIndex = message.seq;
}
else
{
expectedIndex = lastIndex[message.sysid][message.compid] + 1;
}
}
else
{
lastIndex[message.sysid].insert(message.compid,message.seq);
expectedIndex = message.seq;
}
}
else
{
lastIndex.insert(message.sysid,QMap<int,uint8_t>());
lastIndex[message.sysid].insert(message.compid,message.seq);
expectedIndex = message.seq;
}
// Make some noise if a message was skipped
//QLOG_DEBUG() << "SYSID" << message.sysid << "COMPID" << message.compid << "MSGID" << message.msgid << "EXPECTED INDEX:" << expectedIndex << "SEQ" << message.seq;
if (message.seq != expectedIndex)
{
// Determine how many messages were skipped accounting for 0-wraparound
int16_t lostMessages = message.seq - expectedIndex;
if (lostMessages < 0)
{
// Usually, this happens in the case of an out-of order packet
lostMessages = 0;
}
else
{
// Console generates excessive load at high loss rates, needs better GUI visualization
//QLOG_DEBUG() << QString("Lost %1 messages for comp %4: expected sequence ID %2 but received %3.").arg(lostMessages).arg(expectedIndex).arg(message.seq).arg(message.compid);
}
totalLossCounter[linkId] += lostMessages;
currLossCounter[linkId] += lostMessages;
}
// Update the last sequence ID
lastIndex[message.sysid][message.compid] = message.seq;
// Update on every 32th packet
if (totalReceiveCounter[linkId] % 32 == 0)
{
// Calculate new loss ratio
// Receive loss
float receiveLoss = (double)currLossCounter[linkId]/(double)(currReceiveCounter[linkId]+currLossCounter[linkId]);
receiveLoss *= 100.0f;
currLossCounter[linkId] = 0;
currReceiveCounter[linkId] = 0;
emit receiveLossChanged(message.sysid, receiveLoss);
}
// The packet is emitted as a whole, as it is only 255 - 261 bytes short
// kind of inefficient, but no issue for a groundstation pc.
// It buys as reentrancy for the whole code over all threads
emit messageReceived(link, message);
// Multiplex message if enabled
//if (m_multiplexingEnabled)
//{
// Get all links connected to this unit
//QList<LinkInterface*> links = LinkManager::instance()->getLinksForProtocol(this);
// Emit message on all links that are currently connected
//foreach (LinkInterface* currLink, links)
//{
// Only forward this message to the other links,
// not the link the message was received on
// if (currLink != link) sendMessage(currLink, message, message.sysid, message.compid);
//}
//}
}
}
}
}
void MAVLinkProtocol::stopLogging()
{
if (m_logfile && m_logfile->isOpen()){
QLOG_DEBUG() << "Stop MAVLink logging" << m_logfile->fileName();
// Close the current open file
m_logfile->close();
delete m_logfile;
m_logfile = NULL;
}
m_loggingEnabled = false;
}
bool MAVLinkProtocol::startLogging(const QString& filename)
{
if (m_logfile && m_logfile->isOpen())
{
return true;
}
stopLogging();
QLOG_DEBUG() << "Start MAVLink logging" << filename;
Q_ASSERT_X(m_logfile == NULL, "startLogging", "m_logFile == NULL");
m_logfile = new QFile(filename);
if (m_logfile->open(QIODevice::WriteOnly | QIODevice::Append)){
m_loggingEnabled = true;
} else {
emit protocolStatusMessage(tr("Started MAVLink logging"),
tr("FAILED: MAVLink cannot start logging to.").arg(m_logfile->fileName()));
m_loggingEnabled = false;
delete m_logfile;
m_logfile = NULL;
}
//emit loggingChanged(m_loggingEnabled);
return m_loggingEnabled; // reflects if logging started or not.
}
<|endoftext|> |
<commit_before>// This file is a part of the OpenSurgSim project.
// Copyright 2013, SimQuest Solutions 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.
/// \file
/// Tests for the FilteredDevice class.
#include <memory>
#include <string>
#include <gtest/gtest.h>
#include "SurgSim/DataStructures/DataGroup.h"
#include "SurgSim/DataStructures/DataGroupBuilder.h"
#include "SurgSim/Devices/Devices.h"
#include "SurgSim/Framework/Runtime.h"
#include "SurgSim/Testing/MockInputOutput.h"
using SurgSim::DataStructures::DataGroup;
using SurgSim::DataStructures::DataGroupBuilder;
using SurgSim::Devices::FilteredDevice;
using SurgSim::Testing::MockInputOutput;
TEST(FilteredDeviceTest, ByHand)
{
auto filteredDevice = std::make_shared<FilteredDevice>("device");
ASSERT_FALSE(filteredDevice->initialize());
ASSERT_ANY_THROW(filteredDevice->setDevice(nullptr));
ASSERT_NO_THROW(filteredDevice->setDevice(std::make_shared<SurgSim::Devices::IdentityPoseDevice>("identity")));
filteredDevice->addFilter(std::make_shared<SurgSim::Devices::PoseTransform>("filter1"));
filteredDevice->addFilter(std::make_shared<SurgSim::Devices::PoseTransform>("filter2"));
EXPECT_TRUE(filteredDevice->initialize());
EXPECT_ANY_THROW(filteredDevice->initialize());
auto inputOutput = std::make_shared<MockInputOutput>();
EXPECT_TRUE(filteredDevice->addInputConsumer(inputOutput));
EXPECT_TRUE(filteredDevice->removeInputConsumer(inputOutput));
EXPECT_TRUE(filteredDevice->setOutputProducer(inputOutput));
EXPECT_TRUE(filteredDevice->hasOutputProducer());
EXPECT_TRUE(filteredDevice->removeOutputProducer(inputOutput));
EXPECT_FALSE(filteredDevice->hasOutputProducer());
}
TEST(FilteredDeviceTest, Serialization)
{
auto runtime = std::make_shared<SurgSim::Framework::Runtime>("config.txt");
std::shared_ptr<SurgSim::Input::DeviceInterface> device;
ASSERT_NO_THROW(device = SurgSim::Devices::loadDevice("FilteredDevice.yaml"));
ASSERT_NE(nullptr, device);
auto typedDevice = std::dynamic_pointer_cast<FilteredDevice>(device);
ASSERT_NE(nullptr, typedDevice);
auto input = std::make_shared<MockInputOutput>();
ASSERT_TRUE(device->addInputConsumer(input));
SurgSim::Math::RigidTransform3d pose;
ASSERT_TRUE(input->m_lastReceivedInput.poses().get(SurgSim::DataStructures::Names::POSE, &pose));
Eigen::AngleAxisd angleAxis;
angleAxis.angle() = 12.3;
angleAxis.axis() = SurgSim::Math::Vector3d(0.5, 0.5, 0.0);
SurgSim::Math::Vector3d translation = SurgSim::Math::Vector3d(7.8, 8.9, 9.0);
SurgSim::Math::RigidTransform3d expectedTransform =
SurgSim::Math::makeRigidTransform(SurgSim::Math::Quaterniond(angleAxis), translation);
EXPECT_TRUE(pose.isApprox(expectedTransform));
ASSERT_NO_THROW(device = SurgSim::Devices::loadDevice("BadFilteredDevice.yaml"));
EXPECT_EQ(nullptr, device);
}<commit_msg>FilteredDevice whitespace fix.<commit_after>// This file is a part of the OpenSurgSim project.
// Copyright 2013, SimQuest Solutions 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.
/// \file
/// Tests for the FilteredDevice class.
#include <memory>
#include <string>
#include <gtest/gtest.h>
#include "SurgSim/DataStructures/DataGroup.h"
#include "SurgSim/DataStructures/DataGroupBuilder.h"
#include "SurgSim/Devices/Devices.h"
#include "SurgSim/Framework/Runtime.h"
#include "SurgSim/Testing/MockInputOutput.h"
using SurgSim::DataStructures::DataGroup;
using SurgSim::DataStructures::DataGroupBuilder;
using SurgSim::Devices::FilteredDevice;
using SurgSim::Testing::MockInputOutput;
TEST(FilteredDeviceTest, ByHand)
{
auto filteredDevice = std::make_shared<FilteredDevice>("device");
ASSERT_FALSE(filteredDevice->initialize());
ASSERT_ANY_THROW(filteredDevice->setDevice(nullptr));
ASSERT_NO_THROW(filteredDevice->setDevice(std::make_shared<SurgSim::Devices::IdentityPoseDevice>("identity")));
filteredDevice->addFilter(std::make_shared<SurgSim::Devices::PoseTransform>("filter1"));
filteredDevice->addFilter(std::make_shared<SurgSim::Devices::PoseTransform>("filter2"));
EXPECT_TRUE(filteredDevice->initialize());
EXPECT_ANY_THROW(filteredDevice->initialize());
auto inputOutput = std::make_shared<MockInputOutput>();
EXPECT_TRUE(filteredDevice->addInputConsumer(inputOutput));
EXPECT_TRUE(filteredDevice->removeInputConsumer(inputOutput));
EXPECT_TRUE(filteredDevice->setOutputProducer(inputOutput));
EXPECT_TRUE(filteredDevice->hasOutputProducer());
EXPECT_TRUE(filteredDevice->removeOutputProducer(inputOutput));
EXPECT_FALSE(filteredDevice->hasOutputProducer());
}
TEST(FilteredDeviceTest, Serialization)
{
auto runtime = std::make_shared<SurgSim::Framework::Runtime>("config.txt");
std::shared_ptr<SurgSim::Input::DeviceInterface> device;
ASSERT_NO_THROW(device = SurgSim::Devices::loadDevice("FilteredDevice.yaml"));
ASSERT_NE(nullptr, device);
auto typedDevice = std::dynamic_pointer_cast<FilteredDevice>(device);
ASSERT_NE(nullptr, typedDevice);
auto input = std::make_shared<MockInputOutput>();
ASSERT_TRUE(device->addInputConsumer(input));
SurgSim::Math::RigidTransform3d pose;
ASSERT_TRUE(input->m_lastReceivedInput.poses().get(SurgSim::DataStructures::Names::POSE, &pose));
Eigen::AngleAxisd angleAxis;
angleAxis.angle() = 12.3;
angleAxis.axis() = SurgSim::Math::Vector3d(0.5, 0.5, 0.0);
SurgSim::Math::Vector3d translation = SurgSim::Math::Vector3d(7.8, 8.9, 9.0);
SurgSim::Math::RigidTransform3d expectedTransform =
SurgSim::Math::makeRigidTransform(SurgSim::Math::Quaterniond(angleAxis), translation);
EXPECT_TRUE(pose.isApprox(expectedTransform));
ASSERT_NO_THROW(device = SurgSim::Devices::loadDevice("BadFilteredDevice.yaml"));
EXPECT_EQ(nullptr, device);
}<|endoftext|> |
<commit_before>/*
* Copyright (c) 2012 Fredrik Mellbin
*
* This file is part of VapourSynth.
*
* VapourSynth 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.
*
* VapourSynth 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 VapourSynth; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <QtCore/QtCore>
#include "vscore.h"
#include "cachefilter.h"
VSCache::CacheAction VSCache::recommendSize() {
// fixme, constants pulled out of my ass
int total = hits + nearMiss + farMiss;
if (total == 0)
return caClear;
if (total < 30)
return caNoChange; // not enough requests to know what to do so keep it this way
if ((float)nearMiss / total > 0.2) // growing the cache would be beneficial
return caGrow;
else if ((float)farMiss / total > 0.9) // probably a linear scan, no reason to waste space here
return caShrink;
return caNoChange; // probably fine the way it is
}
inline VSCache::VSCache(int maxSize, int maxHistorySize)
: maxSize(maxSize), maxHistorySize(maxHistorySize) {
clear();
}
inline void VSCache::clear() {
hash.clear();
first = NULL;
last = NULL;
weakpoint = NULL;
currentSize = 0;
historySize = 0;
clearStats();
}
inline void VSCache::clearStats() {
hits = 0;
nearMiss = 0;
farMiss = 0;
}
inline PVideoFrame VSCache::object(const int key) const {
return const_cast<VSCache *>(this)->relink(key);
}
inline PVideoFrame VSCache::operator[](const int key) const {
return object(key);
}
inline bool VSCache::remove(const int key) {
QHash<int, Node>::iterator i = hash.find(key);
if (QHash<int, Node>::const_iterator(i) == hash.constEnd()) {
return false;
} else {
unlink(*i);
return true;
}
}
bool VSCache::insert(const int akey, const PVideoFrame &aobject) {
Q_ASSERT(aobject);
Q_ASSERT(akey >= 0);
remove(akey);
trim(maxSize - 1, maxHistorySize);
QHash<int, Node>::iterator i = hash.insert(akey, Node(akey, aobject));
currentSize++;
Node *n = &i.value();
if (first)
first->prevNode = n;
n->nextNode = first;
first = n;
if (!last)
last = first;
trim(maxSize, maxHistorySize);
return true;
}
void VSCache::trim(int max, int maxHistory) {
// first adjust the number of cached frames and extra history length
while (currentSize > max) {
if (!weakpoint)
weakpoint = last;
else
weakpoint = weakpoint->prevNode;
if (weakpoint)
weakpoint->frame.clear();
currentSize--;
historySize++;
}
// remove history until the tail is small enough
while (last && historySize > maxHistory) {
unlink(*last);
}
}
// cache filter start
class CacheInstance {
public:
VSCache cache;
VSNodeRef *clip;
VSNode *node;
VSCore *core;
bool fixedsize;
CacheInstance(VSNodeRef *clip, VSNode *node, VSCore *core) : cache(20, 20), clip(clip), node(node), core(core), fixedsize(false) { }
void addCache() { QMutexLocker lock(&core->cacheLock); core->caches.append(node); }
void removeCache() { QMutexLocker lock(&core->cacheLock); core->caches.removeOne(node); }
};
static void VS_CC cacheInit(VSMap *in, VSMap *out, void **instanceData, VSNode *node, VSCore *core, const VSAPI *vsapi) {
VSNodeRef *video = vsapi->propGetNode(in, "clip", 0, 0);
CacheInstance *c = new CacheInstance(video, node, core);
int err;
int fixed = vsapi->propGetInt(in, "fixed", 0, &err);
if (!err)
c->fixedsize = (bool)fixed;
int size = vsapi->propGetInt(in, "size", 0, &err);
if (!err && size > 0)
c->cache.setMaxFrames(size);
*instanceData = c;
vsapi->setVideoInfo(vsapi->getVideoInfo(video), 1, node);
c->addCache();
}
static const VSFrameRef *VS_CC cacheGetframe(int n, int activationReason, void **instanceData, void **frameData, VSFrameContext *frameCtx, VSCore *core, const VSAPI *vsapi) {
CacheInstance *c = (CacheInstance *) * instanceData;
if (activationReason == arInitial) {
if (n == cCacheTick) {
if (!c->fixedsize)
switch (c->cache.recommendSize()) {
case VSCache::caClear:
c->cache.clear();
case VSCache::caNoChange:
return NULL;
case VSCache::caGrow:
c->cache.setMaxFrames(c->cache.getMaxFrames() + 2);
return NULL;
case VSCache::caShrink:
c->cache.setMaxFrames(qMax(c->cache.getMaxFrames() - 1, 1));
return NULL;
}
} else if (n == cNeedMemory) {
if (!c->fixedsize)
switch (c->cache.recommendSize()) {
case VSCache::caClear:
c->cache.clear();
return NULL;
case VSCache::caGrow:
return NULL;
case VSCache::caShrink:
if (c->cache.getMaxFrames() <= 2)
c->cache.clear();
c->cache.setMaxFrames(qMax(c->cache.getMaxFrames() - 2, 1));
return NULL;
case VSCache::caNoChange:
if (c->cache.getMaxFrames() <= 1)
c->cache.clear();
c->cache.setMaxFrames(qMax(c->cache.getMaxFrames() - 1, 1));
return NULL;
}
} else {
PVideoFrame f(c->cache[n]);
if (f)
return new VSFrameRef(f);
vsapi->requestFrameFilter(n, c->clip, frameCtx);
return NULL;
}
} else if (activationReason == arAllFramesReady) {
const VSFrameRef *r = vsapi->getFrameFilter(n, c->clip, frameCtx);
c->cache.insert(n, r->frame);
return r;
}
return NULL;
}
static void VS_CC cacheFree(void *instanceData, VSCore *core, const VSAPI *vsapi) {
CacheInstance *c = (CacheInstance *)instanceData;
c->removeCache();
vsapi->freeNode(c->clip);
delete c;
}
static QAtomicInt cacheId(1);
static void VS_CC createCacheFilter(const VSMap *in, VSMap *out, void *userData, VSCore *core, const VSAPI *vsapi) {
vsapi->createFilter(in, out, ("Cache" + QString::number(cacheId.fetchAndAddAcquire(1))).toUtf8(), cacheInit, cacheGetframe, cacheFree, fmUnordered, nfNoCache, userData, core);
}
void VS_CC cacheInitialize(VSConfigPlugin configFunc, VSRegisterFunction registerFunc, VSPlugin *plugin) {
registerFunc("Cache", "clip:clip;size:int:opt;fixed:int:opt;", &createCacheFilter, NULL, plugin);
}
<commit_msg>Properly reset cache stats after a decision<commit_after>/*
* Copyright (c) 2012 Fredrik Mellbin
*
* This file is part of VapourSynth.
*
* VapourSynth 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.
*
* VapourSynth 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 VapourSynth; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <QtCore/QtCore>
#include "vscore.h"
#include "cachefilter.h"
VSCache::CacheAction VSCache::recommendSize() {
// fixme, constants pulled out of my ass
int total = hits + nearMiss + farMiss;
if (total == 0)
return caClear;
if (total < 30)
return caNoChange; // not enough requests to know what to do so keep it this way
if ((float)nearMiss / total > 0.2) { // growing the cache would be beneficial
clearStats();
return caGrow;
} else if ((float)farMiss / total > 0.9) { // probably a linear scan, no reason to waste space here
clearStats();
return caShrink;
} else {
clearStats();
return caNoChange; // probably fine the way it is
}
}
inline VSCache::VSCache(int maxSize, int maxHistorySize)
: maxSize(maxSize), maxHistorySize(maxHistorySize) {
clear();
}
inline void VSCache::clear() {
hash.clear();
first = NULL;
last = NULL;
weakpoint = NULL;
currentSize = 0;
historySize = 0;
clearStats();
}
inline void VSCache::clearStats() {
hits = 0;
nearMiss = 0;
farMiss = 0;
}
inline PVideoFrame VSCache::object(const int key) const {
return const_cast<VSCache *>(this)->relink(key);
}
inline PVideoFrame VSCache::operator[](const int key) const {
return object(key);
}
inline bool VSCache::remove(const int key) {
QHash<int, Node>::iterator i = hash.find(key);
if (QHash<int, Node>::const_iterator(i) == hash.constEnd()) {
return false;
} else {
unlink(*i);
return true;
}
}
bool VSCache::insert(const int akey, const PVideoFrame &aobject) {
Q_ASSERT(aobject);
Q_ASSERT(akey >= 0);
remove(akey);
trim(maxSize - 1, maxHistorySize);
QHash<int, Node>::iterator i = hash.insert(akey, Node(akey, aobject));
currentSize++;
Node *n = &i.value();
if (first)
first->prevNode = n;
n->nextNode = first;
first = n;
if (!last)
last = first;
trim(maxSize, maxHistorySize);
return true;
}
void VSCache::trim(int max, int maxHistory) {
// first adjust the number of cached frames and extra history length
while (currentSize > max) {
if (!weakpoint)
weakpoint = last;
else
weakpoint = weakpoint->prevNode;
if (weakpoint)
weakpoint->frame.clear();
currentSize--;
historySize++;
}
// remove history until the tail is small enough
while (last && historySize > maxHistory) {
unlink(*last);
}
}
// cache filter start
class CacheInstance {
public:
VSCache cache;
VSNodeRef *clip;
VSNode *node;
VSCore *core;
bool fixedsize;
CacheInstance(VSNodeRef *clip, VSNode *node, VSCore *core) : cache(20, 20), clip(clip), node(node), core(core), fixedsize(false) { }
void addCache() { QMutexLocker lock(&core->cacheLock); core->caches.append(node); }
void removeCache() { QMutexLocker lock(&core->cacheLock); core->caches.removeOne(node); }
};
static void VS_CC cacheInit(VSMap *in, VSMap *out, void **instanceData, VSNode *node, VSCore *core, const VSAPI *vsapi) {
VSNodeRef *video = vsapi->propGetNode(in, "clip", 0, 0);
CacheInstance *c = new CacheInstance(video, node, core);
int err;
int fixed = vsapi->propGetInt(in, "fixed", 0, &err);
if (!err)
c->fixedsize = (bool)fixed;
int size = vsapi->propGetInt(in, "size", 0, &err);
if (!err && size > 0)
c->cache.setMaxFrames(size);
*instanceData = c;
vsapi->setVideoInfo(vsapi->getVideoInfo(video), 1, node);
c->addCache();
}
static const VSFrameRef *VS_CC cacheGetframe(int n, int activationReason, void **instanceData, void **frameData, VSFrameContext *frameCtx, VSCore *core, const VSAPI *vsapi) {
CacheInstance *c = (CacheInstance *) * instanceData;
if (activationReason == arInitial) {
if (n == cCacheTick) {
if (!c->fixedsize)
switch (c->cache.recommendSize()) {
case VSCache::caClear:
c->cache.clear();
case VSCache::caNoChange:
return NULL;
case VSCache::caGrow:
c->cache.setMaxFrames(c->cache.getMaxFrames() + 2);
return NULL;
case VSCache::caShrink:
c->cache.setMaxFrames(qMax(c->cache.getMaxFrames() - 1, 1));
return NULL;
}
} else if (n == cNeedMemory) {
if (!c->fixedsize)
switch (c->cache.recommendSize()) {
case VSCache::caClear:
c->cache.clear();
return NULL;
case VSCache::caGrow:
return NULL;
case VSCache::caShrink:
if (c->cache.getMaxFrames() <= 2)
c->cache.clear();
c->cache.setMaxFrames(qMax(c->cache.getMaxFrames() - 2, 1));
return NULL;
case VSCache::caNoChange:
if (c->cache.getMaxFrames() <= 1)
c->cache.clear();
c->cache.setMaxFrames(qMax(c->cache.getMaxFrames() - 1, 1));
return NULL;
}
} else {
PVideoFrame f(c->cache[n]);
if (f)
return new VSFrameRef(f);
vsapi->requestFrameFilter(n, c->clip, frameCtx);
return NULL;
}
} else if (activationReason == arAllFramesReady) {
const VSFrameRef *r = vsapi->getFrameFilter(n, c->clip, frameCtx);
c->cache.insert(n, r->frame);
return r;
}
return NULL;
}
static void VS_CC cacheFree(void *instanceData, VSCore *core, const VSAPI *vsapi) {
CacheInstance *c = (CacheInstance *)instanceData;
c->removeCache();
vsapi->freeNode(c->clip);
delete c;
}
static QAtomicInt cacheId(1);
static void VS_CC createCacheFilter(const VSMap *in, VSMap *out, void *userData, VSCore *core, const VSAPI *vsapi) {
vsapi->createFilter(in, out, ("Cache" + QString::number(cacheId.fetchAndAddAcquire(1))).toUtf8(), cacheInit, cacheGetframe, cacheFree, fmUnordered, nfNoCache, userData, core);
}
void VS_CC cacheInitialize(VSConfigPlugin configFunc, VSRegisterFunction registerFunc, VSPlugin *plugin) {
registerFunc("Cache", "clip:clip;size:int:opt;fixed:int:opt;", &createCacheFilter, NULL, plugin);
}
<|endoftext|> |
<commit_before>#include "include/geom.h"
#include <assert.h>
Constructor::Constructor(MoveListener listener) :
Scope(listener), angles() {}
Constructor::~Constructor()
{
for (auto *a : angles)
delete a;
Scope::~Scope();
}
bool Constructor::contains(const Angle *a) const
{
return a != nullptr &&
std::count_if(angles.begin(), angles.end(), [a](const Angle *p) {return *p == *a; });
}
void Constructor::add(const Angle *a)
{
if (!contains(a))
angles.push_back(a);
}
#define _make_move(movetype, arg1, arg1type, arg2, arg2type, res, restype) do { \
if (res != nullptr) { \
Scope::add(res); \
Scope::listener(Move<arg1type,arg2type,restype>(MoveType::movetype, arg1, arg2, res)); \
}} while (0)
const LineSegment *Constructor::join_segment(const Point &a, const Point &b)
{
if (!Scope::contains(&a) || !Scope::contains(&b))
return nullptr;
const LineSegment *res = new LineSegment(a, b);
Scope::add(res);
_make_move(straightedge, &a, Point, &b, Point, res, Line);
return res;
}
const Angle *Constructor::join_angle(const Point &end1, const Point &vertex, const Point &end2)
{
if (!Scope::contains(&end1) || !Scope::contains(&vertex) || !Scope::contains(&end2))
return nullptr;
const Angle *res = new Angle(end1, vertex, end2);
add(res);
if (!Scope::contains(&res->l1)) {
Scope::add(&res->l1);
_make_move(straightedge, &vertex, Point, &end1, Point, &res->l1, Line);
}
if (!Scope::contains(&res->l2)) {
Scope::add(&res->l2);
_make_move(straightedge, &vertex, Point, &end2, Point, &res->l2, Line);
}
return res;
}
#undef _make_move
const Line *Constructor::perpendicular(const Line &l, const Point &p)
{
const Point *o1, *o2;
const Circle *c, *c1, *c2;
const Line &l1 (l); // ensure containment for line segments
if (!Scope::contains(&p) || !Scope::contains(&l))
return nullptr;
// generate two points on the line equidistant from p
o1 = nullptr;
for (auto *p2 : points)
if (l1.contains(*p2) && *p2 != p) { o1 = p2; break; }
assert(o1 != nullptr);
c = join_circle(p, *o1);
assert(c != nullptr);
auto pair = meet(l1, *c); // the copy constructor works well with Scope::contains
o2 = pair.first == o1 ? pair.second : pair.first;
assert(o2 != nullptr);
// create circles from o1 to o2 and from o2 to o1
c1 = join_circle(*o1, *o2);
c2 = join_circle(*o2, *o1);
assert(c1 != nullptr);
assert(c2 != nullptr);
assert(*c1 != *c2); // o1 and o2 are different
pair = meet(*c1, *c2);
assert(pair.first != nullptr);
assert(pair.second != nullptr);
assert(*pair.first != *pair.second); // c1 and c2 are different
return join_line(*pair.first, *pair.second);
// the deletion of all these items are to be handled by ~Scope()
}
const Line *Constructor::parallel(const Line &l, const Point &p)
{
if (l.contains(p))
return &l;
auto perp = perpendicular(l, p);
if (perp == nullptr)
return nullptr;
return perpendicular(*perp, p);
}
const LineSegment *Constructor::translate(const LineSegment &l, const Point &start)
{
const Line *par, *diff, *diff1;
const Point *end;
const LineSegment *res;
par = parallel(l, start);
if (par == nullptr) // l or start isn't added
return nullptr;
diff = join_line(l.start, start);
assert(diff != nullptr);
diff1 = parallel(*diff, l.end);
assert(diff1 != nullptr);
end = meet(*par, *diff1);
assert(end != nullptr); // TODO move these assertions to Scope
res = new LineSegment(start, *end);
Scope::add(res);
return res;
}
#define _ratio(l1, l2) ((l1).x_coeff == 0) ? sgn((l1).y_coeff * (l2).y_coeff) : sgn((l1).x_coeff * (l2).x_coeff)
const Angle *Constructor::translate(const Angle &a, const Point &p)
{
const Line *l1 = parallel(a.l1, p),
*l2 = parallel(a.l2, p);
// the sign of the ratio of nonconstant coefficients for l1 and l2
int r1 = _ratio(a.l1, *l1),
r2 = _ratio(a.l2, *l2);
const Angle *res = new Angle(*l1, *l2, r1 * a.region1, r2 * a.region2);
add(res);
return res;
}
#undef _ratio
const Line *Constructor::bisect(const Point &a, const Point &b)
{
const Circle *c1 = join_circle(a, b),
*c2 = join_circle(b, a);
if (c1 == nullptr || c2 == nullptr || c1 == c2)
return nullptr;
auto _meet = meet(*c1, *c2);
assert(_meet.first != nullptr);
assert(_meet.second != nullptr);
return join_line(*_meet.first, *_meet.second);
}
const Line *Constructor::bisect(const LineSegment &l)
{
return bisect(l.start, l.end);
}
const Line *Constructor::bisect(const Angle &a)
{
if (a.l1 == a.l2)
return &a.l1;
// find point on l1 other than vertex
const Point *p1 = nullptr;
for (auto *p : points)
if (a.l1.contains(*p) && *p != a.vertex) { p1 = p; break; }
assert(p1 != nullptr);
// find point on l2 with same region as p1
const Circle *c = join_circle(a.vertex, *p1);
auto _meet = meet(a.l2, *c);
assert(_meet.first != nullptr);
assert(_meet.second != nullptr);
const Point *p2 = a.l1.precedes(a.vertex, *p1) == a.l1.precedes(a.vertex, *_meet.first) ? _meet.first : _meet.second;
return join_line(*p1, *p2);
}
const Point *Constructor::midpoint(const Point &a, const Point &b)
{
const Line *l1 = join_line(a, b),
*l2 = bisect(a, b);
if (l1 == nullptr || l2 == nullptr)
return nullptr;
return meet(*l1, *l2);
}
const Point *Constructor::midpoint(const LineSegment &a)
{
return midpoint(a.start, a.end);
}
const Point *Constructor::reflect(const Point &a, const Point &pivot)
{
const Line *l = join_line(a, pivot);
const Circle *c = join_circle(pivot, a);
auto _meet = meet(*l, *c);
if (_meet.first == nullptr || _meet.second == nullptr)
return nullptr;
return *_meet.first == a ? _meet.second : _meet.first;
}
const Point *Constructor::reflect(const Point &a, const Line &pivot)
{
const Line &p (pivot), // override within_boundary
*l = perpendicular(p, a);
if (l == nullptr)
return nullptr;
const Point *c = meet(p, *l);
if (c == nullptr)
return nullptr;
return reflect(a, *c);
}
const Line *Constructor::reflect(const Line &a, const Point &pivot)
{
const Line &l (a),
*p = perpendicular(l, pivot);
if (p == nullptr)
return nullptr;
const Point *b = reflect(*meet(l, *p), pivot);
if (b == nullptr)
return nullptr;
return perpendicular(*p, *b);
}
const Line *Constructor::reflect(const Line &a, const Line &pivot)
{
// different cases for a and pivot being parallel or not
const Point *vertex = meet(a, pivot), *p1 = nullptr;
if (vertex == nullptr) { // parallel
// find point on pivot
for (auto *p : points)
if (pivot.contains(*p)) { p1 = p; break; }
assert(p1 != nullptr);
// reflect a by p1
return reflect(a, *p1);
}
// not parallel
// find point on a
for (auto *p : points)
if (a.contains(*p) && *p != *vertex) { p1 = p; break; }
assert(p1 != nullptr);
// reflect p1 around pivot
const Point *p = reflect(*p1, pivot);
if (p == nullptr)
return nullptr;
return join_line(*vertex, *p);
}
const Line *Constructor::rotate(const Line &l, const Angle &a, const Point &pivot)
{
// find bisector of angle
const Line *l1 = bisect(a);
assert(l1 != nullptr);
// get parallel of bisector at pivot
l1 = parallel(*l1, pivot);
assert(l1 != nullptr);
// reflect line around parallel
return reflect(l, *l1);
}
const LineSegment *Constructor::rotate(const LineSegment &l, const Angle &a)
{
// find bisector of angle
const Line *l1 = bisect(a);
if (l1 == nullptr) return nullptr;
// get parallel of bisector at l.start
l1 = parallel(*l1, l.start);
if (l1 == nullptr) return nullptr;
// reflect end around parallel
const Point *end = reflect(l.end, *l1);
if (end == nullptr) return nullptr;
// connect start and end
return join_segment(l.start, *end);
/* Awful previous algorithm:
// - Translate l to the vertex of a, call the new segment l1
const LineSegment *l1 = translate(l, a.vertex);
// - Draw circle with center l1.start and touching l1.end
if (l1 == nullptr)
return nullptr;
const Circle *c = join_circle(l1->start, l1->end);
// - Pick the meets p1 and p2 of the circle with a.l1 and a.l2 that lie in a.region1 and a.region2
auto meet1 = meet(a.l1, *c),
meet2 = meet(a.l2, *c);
assert(meet1.second != nullptr);
assert(meet2.second != nullptr);
const Point *p1 = a.l1.precedes(a.vertex, *meet1.first) == (a.region1 > 0) ? meet1.first : meet1.second,
*p2 = a.l2.precedes(a.vertex, *meet2.first) == (a.region2 > 0) ? meet2.first : meet2.second;
// - Find perpendicular bisector to l1.end and p2
const Line *l2 = bisect(l1->end, *p2);
assert(l2 != nullptr);
// - Reflect p1 around the bisector
const Point *p = reflect(*p1, *l2);
assert(p != nullptr);
// - Connect l1.start with p1 and translate the new line segment back to l.start
const LineSegment *l3 = join_segment(l1->start, *p);
assert(l3 != nullptr);
return translate(*l3, l.start);
*/
}
<commit_msg>Added destructor for Constructor<commit_after>#include "include/geom.h"
#include <assert.h>
Constructor::Constructor(MoveListener listener) :
Scope(listener), angles() {}
Constructor::~Constructor()
{
for (auto *a : angles)
delete a;
}
bool Constructor::contains(const Angle *a) const
{
return a != nullptr &&
std::count_if(angles.begin(), angles.end(), [a](const Angle *p) {return *p == *a; });
}
void Constructor::add(const Angle *a)
{
if (!contains(a))
angles.push_back(a);
}
#define _make_move(movetype, arg1, arg1type, arg2, arg2type, res, restype) do { \
if (res != nullptr) { \
Scope::add(res); \
Scope::listener(Move<arg1type,arg2type,restype>(MoveType::movetype, arg1, arg2, res)); \
}} while (0)
const LineSegment *Constructor::join_segment(const Point &a, const Point &b)
{
if (!Scope::contains(&a) || !Scope::contains(&b))
return nullptr;
const LineSegment *res = new LineSegment(a, b);
Scope::add(res);
_make_move(straightedge, &a, Point, &b, Point, res, Line);
return res;
}
const Angle *Constructor::join_angle(const Point &end1, const Point &vertex, const Point &end2)
{
if (!Scope::contains(&end1) || !Scope::contains(&vertex) || !Scope::contains(&end2))
return nullptr;
const Angle *res = new Angle(end1, vertex, end2);
add(res);
if (!Scope::contains(&res->l1)) {
Scope::add(&res->l1);
_make_move(straightedge, &vertex, Point, &end1, Point, &res->l1, Line);
}
if (!Scope::contains(&res->l2)) {
Scope::add(&res->l2);
_make_move(straightedge, &vertex, Point, &end2, Point, &res->l2, Line);
}
return res;
}
#undef _make_move
const Line *Constructor::perpendicular(const Line &l, const Point &p)
{
const Point *o1, *o2;
const Circle *c, *c1, *c2;
const Line &l1 (l); // ensure containment for line segments
if (!Scope::contains(&p) || !Scope::contains(&l))
return nullptr;
// generate two points on the line equidistant from p
o1 = nullptr;
for (auto *p2 : points)
if (l1.contains(*p2) && *p2 != p) { o1 = p2; break; }
assert(o1 != nullptr);
c = join_circle(p, *o1);
assert(c != nullptr);
auto pair = meet(l1, *c); // the copy constructor works well with Scope::contains
o2 = pair.first == o1 ? pair.second : pair.first;
assert(o2 != nullptr);
// create circles from o1 to o2 and from o2 to o1
c1 = join_circle(*o1, *o2);
c2 = join_circle(*o2, *o1);
assert(c1 != nullptr);
assert(c2 != nullptr);
assert(*c1 != *c2); // o1 and o2 are different
pair = meet(*c1, *c2);
assert(pair.first != nullptr);
assert(pair.second != nullptr);
assert(*pair.first != *pair.second); // c1 and c2 are different
return join_line(*pair.first, *pair.second);
// the deletion of all these items are to be handled by ~Scope()
}
const Line *Constructor::parallel(const Line &l, const Point &p)
{
if (l.contains(p))
return &l;
auto perp = perpendicular(l, p);
if (perp == nullptr)
return nullptr;
return perpendicular(*perp, p);
}
const LineSegment *Constructor::translate(const LineSegment &l, const Point &start)
{
const Line *par, *diff, *diff1;
const Point *end;
const LineSegment *res;
par = parallel(l, start);
if (par == nullptr) // l or start isn't added
return nullptr;
diff = join_line(l.start, start);
assert(diff != nullptr);
diff1 = parallel(*diff, l.end);
assert(diff1 != nullptr);
end = meet(*par, *diff1);
assert(end != nullptr); // TODO move these assertions to Scope
res = new LineSegment(start, *end);
Scope::add(res);
return res;
}
#define _ratio(l1, l2) ((l1).x_coeff == 0) ? sgn((l1).y_coeff * (l2).y_coeff) : sgn((l1).x_coeff * (l2).x_coeff)
const Angle *Constructor::translate(const Angle &a, const Point &p)
{
const Line *l1 = parallel(a.l1, p),
*l2 = parallel(a.l2, p);
// the sign of the ratio of nonconstant coefficients for l1 and l2
int r1 = _ratio(a.l1, *l1),
r2 = _ratio(a.l2, *l2);
const Angle *res = new Angle(*l1, *l2, r1 * a.region1, r2 * a.region2);
add(res);
return res;
}
#undef _ratio
const Line *Constructor::bisect(const Point &a, const Point &b)
{
const Circle *c1 = join_circle(a, b),
*c2 = join_circle(b, a);
if (c1 == nullptr || c2 == nullptr || c1 == c2)
return nullptr;
auto _meet = meet(*c1, *c2);
assert(_meet.first != nullptr);
assert(_meet.second != nullptr);
return join_line(*_meet.first, *_meet.second);
}
const Line *Constructor::bisect(const LineSegment &l)
{
return bisect(l.start, l.end);
}
const Line *Constructor::bisect(const Angle &a)
{
if (a.l1 == a.l2)
return &a.l1;
// find point on l1 other than vertex
const Point *p1 = nullptr;
for (auto *p : points)
if (a.l1.contains(*p) && *p != a.vertex) { p1 = p; break; }
assert(p1 != nullptr);
// find point on l2 with same region as p1
const Circle *c = join_circle(a.vertex, *p1);
auto _meet = meet(a.l2, *c);
assert(_meet.first != nullptr);
assert(_meet.second != nullptr);
const Point *p2 = a.l1.precedes(a.vertex, *p1) == a.l1.precedes(a.vertex, *_meet.first) ? _meet.first : _meet.second;
return join_line(*p1, *p2);
}
const Point *Constructor::midpoint(const Point &a, const Point &b)
{
const Line *l1 = join_line(a, b),
*l2 = bisect(a, b);
if (l1 == nullptr || l2 == nullptr)
return nullptr;
return meet(*l1, *l2);
}
const Point *Constructor::midpoint(const LineSegment &a)
{
return midpoint(a.start, a.end);
}
const Point *Constructor::reflect(const Point &a, const Point &pivot)
{
const Line *l = join_line(a, pivot);
const Circle *c = join_circle(pivot, a);
auto _meet = meet(*l, *c);
if (_meet.first == nullptr || _meet.second == nullptr)
return nullptr;
return *_meet.first == a ? _meet.second : _meet.first;
}
const Point *Constructor::reflect(const Point &a, const Line &pivot)
{
const Line &p (pivot), // override within_boundary
*l = perpendicular(p, a);
if (l == nullptr)
return nullptr;
const Point *c = meet(p, *l);
if (c == nullptr)
return nullptr;
return reflect(a, *c);
}
const Line *Constructor::reflect(const Line &a, const Point &pivot)
{
const Line &l (a),
*p = perpendicular(l, pivot);
if (p == nullptr)
return nullptr;
const Point *b = reflect(*meet(l, *p), pivot);
if (b == nullptr)
return nullptr;
return perpendicular(*p, *b);
}
const Line *Constructor::reflect(const Line &a, const Line &pivot)
{
// different cases for a and pivot being parallel or not
const Point *vertex = meet(a, pivot), *p1 = nullptr;
if (vertex == nullptr) { // parallel
// find point on pivot
for (auto *p : points)
if (pivot.contains(*p)) { p1 = p; break; }
assert(p1 != nullptr);
// reflect a by p1
return reflect(a, *p1);
}
// not parallel
// find point on a
for (auto *p : points)
if (a.contains(*p) && *p != *vertex) { p1 = p; break; }
assert(p1 != nullptr);
// reflect p1 around pivot
const Point *p = reflect(*p1, pivot);
if (p == nullptr)
return nullptr;
return join_line(*vertex, *p);
}
const Line *Constructor::rotate(const Line &l, const Angle &a, const Point &pivot)
{
// find bisector of angle
const Line *l1 = bisect(a);
assert(l1 != nullptr);
// get parallel of bisector at pivot
l1 = parallel(*l1, pivot);
assert(l1 != nullptr);
// reflect line around parallel
return reflect(l, *l1);
}
const LineSegment *Constructor::rotate(const LineSegment &l, const Angle &a)
{
// find bisector of angle
const Line *l1 = bisect(a);
if (l1 == nullptr) return nullptr;
// get parallel of bisector at l.start
l1 = parallel(*l1, l.start);
if (l1 == nullptr) return nullptr;
// reflect end around parallel
const Point *end = reflect(l.end, *l1);
if (end == nullptr) return nullptr;
// connect start and end
return join_segment(l.start, *end);
/* Awful previous algorithm:
// - Translate l to the vertex of a, call the new segment l1
const LineSegment *l1 = translate(l, a.vertex);
// - Draw circle with center l1.start and touching l1.end
if (l1 == nullptr)
return nullptr;
const Circle *c = join_circle(l1->start, l1->end);
// - Pick the meets p1 and p2 of the circle with a.l1 and a.l2 that lie in a.region1 and a.region2
auto meet1 = meet(a.l1, *c),
meet2 = meet(a.l2, *c);
assert(meet1.second != nullptr);
assert(meet2.second != nullptr);
const Point *p1 = a.l1.precedes(a.vertex, *meet1.first) == (a.region1 > 0) ? meet1.first : meet1.second,
*p2 = a.l2.precedes(a.vertex, *meet2.first) == (a.region2 > 0) ? meet2.first : meet2.second;
// - Find perpendicular bisector to l1.end and p2
const Line *l2 = bisect(l1->end, *p2);
assert(l2 != nullptr);
// - Reflect p1 around the bisector
const Point *p = reflect(*p1, *l2);
assert(p != nullptr);
// - Connect l1.start with p1 and translate the new line segment back to l.start
const LineSegment *l3 = join_segment(l1->start, *p);
assert(l3 != nullptr);
return translate(*l3, l.start);
*/
}
<|endoftext|> |
<commit_before>/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Microsoft Corporation
*
* -=- Robust Distributed System Nucleus (rDSN) -=-
*
* 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 <dsn/internal/task_worker.h>
# include "task_engine.h"
# include <sstream>
# include <errno.h>
# ifdef _WIN32
# else
# include <pthread.h>
# ifdef __FreeBSD__
# include <pthread_np.h>
# endif
# ifdef __APPLE__
# include <mach/thread_policy.h>
# endif
# endif
# ifdef __TITLE__
# undef __TITLE__
# endif
# define __TITLE__ "task.worker"
namespace dsn {
join_point<void, task_worker*> task_worker::on_start("task_worker::on_start");
join_point<void, task_worker*> task_worker::on_create("task_worker::on_create");
task_worker::task_worker(task_worker_pool* pool, task_queue* q, int index, task_worker* inner_provider)
{
_owner_pool = pool;
_input_queue = q;
_index = index;
_native_tid = ::dsn::utils::get_invalid_tid();
char name[256];
sprintf(name, "%5s.%s.%u", pool->node()->name(), pool->spec().name.c_str(), index);
_name = std::string(name);
_is_running = false;
_thread = nullptr;
}
task_worker::~task_worker()
{
stop();
}
void task_worker::start()
{
if (_is_running)
return;
_is_running = true;
_thread = new std::thread(std::bind(&task_worker::run_internal, this));
_started.wait();
}
void task_worker::stop()
{
if (!_is_running)
return;
_is_running = false;
_thread->join();
delete _thread;
_thread = nullptr;
_is_running = false;
}
void task_worker::set_name()
{
# ifdef _WIN32
#ifndef MS_VC_EXCEPTION
#define MS_VC_EXCEPTION 0x406D1388
#endif
typedef struct tagTHREADNAME_INFO
{
uint32_t dwType; // Must be 0x1000.
LPCSTR szName; // Pointer to name (in user addr space).
uint32_t dwThreadID; // Thread ID (-1=caller thread).
uint32_t dwFlags; // Reserved for future use, must be zero.
}THREADNAME_INFO;
THREADNAME_INFO info;
info.dwType = 0x1000;
info.szName = name().c_str();
info.dwThreadID = (uint32_t)-1;
info.dwFlags = 0;
__try
{
::RaiseException (MS_VC_EXCEPTION, 0, sizeof(info)/sizeof(uint32_t), (ULONG_PTR*)&info);
}
__except(EXCEPTION_CONTINUE_EXECUTION)
{
}
# else
auto thread_name = name()
# ifdef __linux__
.substr(0, (16 - 1))
# endif
;
auto tid = _thread->native_handle();
int err = 0;
# ifdef __FreeBSD__
pthread_set_name_np(tid, thread_name.c_str());
# elif defined(__linux__)
err = pthread_setname_np(tid, thread_name.c_str());
# elif defined(__APPLE__)
err = pthread_setname_np(thread_name.c_str());
# endif
if (err != 0)
{
dwarn("Fail to set pthread name. ret = %d", err);
}
# endif
}
void task_worker::set_priority(worker_priority_t pri)
{
# ifndef _WIN32
static int policy = SCHED_OTHER;
static int prio_max =
#ifdef __linux__
-20;
#else
sched_get_priority_max(policy);
#endif
static int prio_min =
#ifdef __linux__
19;
#else
sched_get_priority_min(policy);
#endif
static int prio_middle = ((prio_min + prio_max + 1) / 2);
#endif
static int g_thread_priority_map[] =
{
# ifdef _WIN32
THREAD_PRIORITY_LOWEST,
THREAD_PRIORITY_BELOW_NORMAL,
THREAD_PRIORITY_NORMAL,
THREAD_PRIORITY_ABOVE_NORMAL,
THREAD_PRIORITY_HIGHEST
# else
prio_min,
(prio_min + prio_middle) / 2,
prio_middle,
(prio_middle + prio_max) / 2,
prio_max
# endif
};
static_assert(ARRAYSIZE(g_thread_priority_map) == THREAD_xPRIORITY_COUNT,
"ARRAYSIZE(g_thread_priority_map) != THREAD_xPRIORITY_COUNT");
int prio = g_thread_priority_map[static_cast<int>(pri)];
bool succ = true;
# if !defined(_WIN32) && !defined(__linux__)
struct sched_param param;
memset(¶m, 0, sizeof(struct sched_param));
param.sched_priority = prio;
# endif
# ifdef _WIN32
succ = (::SetThreadPriority(_thread->native_handle(), prio) == TRUE);
# elif defined(__linux__)
if ((nice(prio) == -1) && (errno != 0))
{
succ = false;
}
# else
succ = (pthread_setschedparam(_thread->native_handle(), policy, ¶m) == 0);
//# error "not implemented"
# endif
if (!succ)
{
dwarn("You may need priviledge to set thread priority. errno = %d.\n", errno);
}
}
void task_worker::set_affinity(uint64_t affinity)
{
dassert(affinity > 0, "affinity cannot be 0.");
int nr_cpu = static_cast<int>(std::thread::hardware_concurrency());
dassert(affinity <= (((uint64_t)1 << nr_cpu) - 1),
"There are %d cpus in total, while setting thread affinity to a nonexistent one.", nr_cpu);
auto tid = _thread->native_handle();
int err;
# ifdef _WIN32
if (::SetThreadAffinityMask(tid, static_cast<DWORD_PTR>(affinity)) == 0)
{
err = static_cast<int>::GetLastError();
}
# elif defined(__APPLE__)
thread_affinity_policy_data_t policy;
policy.affinity_tag = static_cast<integer_t>(affinity);
err = static_cast<int>(thread_policy_set(
static_cast<thread_t>(::dsn::utils::get_current_tid()),
THREAD_AFFINITY_POLICY,
(thread_policy_t)&policy,
THREAD_AFFINITY_POLICY_COUNT
));
# else
# ifdef __FreeBSD__
# ifndef cpu_set_t
# define cpu_set_t cpuset_t
# endif
# endif
cpu_set_t cpuset;
int nr_bits = std::min(nr_cpu, static_cast<int>(sizeof(affinity) * 8));
CPU_ZERO(&cpuset);
for (int i = 0; i < nr_bits; i++)
{
if ((affinity & ((uint64_t)1 << i)) != 0)
{
CPU_SET(i, &cpuset);
}
}
err = pthread_setaffinity_np(tid, sizeof(cpuset), &cpuset);
# endif
if (err != 0)
{
dwarn("Fail to set thread affinity. err = %d", err);
}
}
void task_worker::run_internal()
{
while (_thread == nullptr)
{
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
task::set_current_worker(this);
_native_tid = ::dsn::utils::get_current_tid();
set_name();
set_priority(pool_spec().worker_priority);
if (true == pool_spec().worker_share_core)
{
if (pool_spec().worker_affinity_mask > 0)
{
set_affinity(pool_spec().worker_affinity_mask);
}
}
else
{
uint64_t current_mask = pool_spec().worker_affinity_mask;
for (int i = 0; i < _index; ++i)
{
current_mask &= (current_mask - 1);
if (0 == current_mask)
{
current_mask = pool_spec().worker_affinity_mask;
}
}
current_mask -= (current_mask & (current_mask - 1));
set_affinity(current_mask);
}
_started.notify();
on_start.execute(this);
loop();
}
void task_worker::loop()
{
task_queue* q = queue();
//try {
while (_is_running)
{
task_ptr task = q->dequeue();
if (task != nullptr)
{
task->exec_internal();
}
}
/*}
catch (std::exception& ex)
{
dassert (false, "%s: unhandled exception '%s'", name().c_str(), ex.what());
}*/
}
const threadpool_spec& task_worker::pool_spec() const
{
return pool()->spec();
}
} // end namespace
<commit_msg>Fix a typo.<commit_after>/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Microsoft Corporation
*
* -=- Robust Distributed System Nucleus (rDSN) -=-
*
* 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 <dsn/internal/task_worker.h>
# include "task_engine.h"
# include <sstream>
# include <errno.h>
# ifdef _WIN32
# else
# include <pthread.h>
# ifdef __FreeBSD__
# include <pthread_np.h>
# endif
# ifdef __APPLE__
# include <mach/thread_policy.h>
# endif
# endif
# ifdef __TITLE__
# undef __TITLE__
# endif
# define __TITLE__ "task.worker"
namespace dsn {
join_point<void, task_worker*> task_worker::on_start("task_worker::on_start");
join_point<void, task_worker*> task_worker::on_create("task_worker::on_create");
task_worker::task_worker(task_worker_pool* pool, task_queue* q, int index, task_worker* inner_provider)
{
_owner_pool = pool;
_input_queue = q;
_index = index;
_native_tid = ::dsn::utils::get_invalid_tid();
char name[256];
sprintf(name, "%5s.%s.%u", pool->node()->name(), pool->spec().name.c_str(), index);
_name = std::string(name);
_is_running = false;
_thread = nullptr;
}
task_worker::~task_worker()
{
stop();
}
void task_worker::start()
{
if (_is_running)
return;
_is_running = true;
_thread = new std::thread(std::bind(&task_worker::run_internal, this));
_started.wait();
}
void task_worker::stop()
{
if (!_is_running)
return;
_is_running = false;
_thread->join();
delete _thread;
_thread = nullptr;
_is_running = false;
}
void task_worker::set_name()
{
# ifdef _WIN32
#ifndef MS_VC_EXCEPTION
#define MS_VC_EXCEPTION 0x406D1388
#endif
typedef struct tagTHREADNAME_INFO
{
uint32_t dwType; // Must be 0x1000.
LPCSTR szName; // Pointer to name (in user addr space).
uint32_t dwThreadID; // Thread ID (-1=caller thread).
uint32_t dwFlags; // Reserved for future use, must be zero.
}THREADNAME_INFO;
THREADNAME_INFO info;
info.dwType = 0x1000;
info.szName = name().c_str();
info.dwThreadID = (uint32_t)-1;
info.dwFlags = 0;
__try
{
::RaiseException (MS_VC_EXCEPTION, 0, sizeof(info)/sizeof(uint32_t), (ULONG_PTR*)&info);
}
__except(EXCEPTION_CONTINUE_EXECUTION)
{
}
# else
auto thread_name = name()
# ifdef __linux__
.substr(0, (16 - 1))
# endif
;
auto tid = _thread->native_handle();
int err = 0;
# ifdef __FreeBSD__
pthread_set_name_np(tid, thread_name.c_str());
# elif defined(__linux__)
err = pthread_setname_np(tid, thread_name.c_str());
# elif defined(__APPLE__)
err = pthread_setname_np(thread_name.c_str());
# endif
if (err != 0)
{
dwarn("Fail to set pthread name. err = %d", err);
}
# endif
}
void task_worker::set_priority(worker_priority_t pri)
{
# ifndef _WIN32
static int policy = SCHED_OTHER;
static int prio_max =
#ifdef __linux__
-20;
#else
sched_get_priority_max(policy);
#endif
static int prio_min =
#ifdef __linux__
19;
#else
sched_get_priority_min(policy);
#endif
static int prio_middle = ((prio_min + prio_max + 1) / 2);
#endif
static int g_thread_priority_map[] =
{
# ifdef _WIN32
THREAD_PRIORITY_LOWEST,
THREAD_PRIORITY_BELOW_NORMAL,
THREAD_PRIORITY_NORMAL,
THREAD_PRIORITY_ABOVE_NORMAL,
THREAD_PRIORITY_HIGHEST
# else
prio_min,
(prio_min + prio_middle) / 2,
prio_middle,
(prio_middle + prio_max) / 2,
prio_max
# endif
};
static_assert(ARRAYSIZE(g_thread_priority_map) == THREAD_xPRIORITY_COUNT,
"ARRAYSIZE(g_thread_priority_map) != THREAD_xPRIORITY_COUNT");
int prio = g_thread_priority_map[static_cast<int>(pri)];
bool succ = true;
# if !defined(_WIN32) && !defined(__linux__)
struct sched_param param;
memset(¶m, 0, sizeof(struct sched_param));
param.sched_priority = prio;
# endif
# ifdef _WIN32
succ = (::SetThreadPriority(_thread->native_handle(), prio) == TRUE);
# elif defined(__linux__)
if ((nice(prio) == -1) && (errno != 0))
{
succ = false;
}
# else
succ = (pthread_setschedparam(_thread->native_handle(), policy, ¶m) == 0);
//# error "not implemented"
# endif
if (!succ)
{
dwarn("You may need priviledge to set thread priority. errno = %d.\n", errno);
}
}
void task_worker::set_affinity(uint64_t affinity)
{
dassert(affinity > 0, "affinity cannot be 0.");
int nr_cpu = static_cast<int>(std::thread::hardware_concurrency());
dassert(affinity <= (((uint64_t)1 << nr_cpu) - 1),
"There are %d cpus in total, while setting thread affinity to a nonexistent one.", nr_cpu);
auto tid = _thread->native_handle();
int err;
# ifdef _WIN32
if (::SetThreadAffinityMask(tid, static_cast<DWORD_PTR>(affinity)) == 0)
{
err = static_cast<int>::GetLastError();
}
# elif defined(__APPLE__)
thread_affinity_policy_data_t policy;
policy.affinity_tag = static_cast<integer_t>(affinity);
err = static_cast<int>(thread_policy_set(
static_cast<thread_t>(::dsn::utils::get_current_tid()),
THREAD_AFFINITY_POLICY,
(thread_policy_t)&policy,
THREAD_AFFINITY_POLICY_COUNT
));
# else
# ifdef __FreeBSD__
# ifndef cpu_set_t
# define cpu_set_t cpuset_t
# endif
# endif
cpu_set_t cpuset;
int nr_bits = std::min(nr_cpu, static_cast<int>(sizeof(affinity) * 8));
CPU_ZERO(&cpuset);
for (int i = 0; i < nr_bits; i++)
{
if ((affinity & ((uint64_t)1 << i)) != 0)
{
CPU_SET(i, &cpuset);
}
}
err = pthread_setaffinity_np(tid, sizeof(cpuset), &cpuset);
# endif
if (err != 0)
{
dwarn("Fail to set thread affinity. err = %d", err);
}
}
void task_worker::run_internal()
{
while (_thread == nullptr)
{
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
task::set_current_worker(this);
_native_tid = ::dsn::utils::get_current_tid();
set_name();
set_priority(pool_spec().worker_priority);
if (true == pool_spec().worker_share_core)
{
if (pool_spec().worker_affinity_mask > 0)
{
set_affinity(pool_spec().worker_affinity_mask);
}
}
else
{
uint64_t current_mask = pool_spec().worker_affinity_mask;
for (int i = 0; i < _index; ++i)
{
current_mask &= (current_mask - 1);
if (0 == current_mask)
{
current_mask = pool_spec().worker_affinity_mask;
}
}
current_mask -= (current_mask & (current_mask - 1));
set_affinity(current_mask);
}
_started.notify();
on_start.execute(this);
loop();
}
void task_worker::loop()
{
task_queue* q = queue();
//try {
while (_is_running)
{
task_ptr task = q->dequeue();
if (task != nullptr)
{
task->exec_internal();
}
}
/*}
catch (std::exception& ex)
{
dassert (false, "%s: unhandled exception '%s'", name().c_str(), ex.what());
}*/
}
const threadpool_spec& task_worker::pool_spec() const
{
return pool()->spec();
}
} // end namespace
<|endoftext|> |
<commit_before><commit_msg>VariantAnnotateFrequency: fixed indel handling (uses normalized variant notation)<commit_after><|endoftext|> |
<commit_before>/*
* Copyright (c) 2002-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: Steve Reinhardt
*/
#ifndef __CPU_SIMPLE_TIMING_HH__
#define __CPU_SIMPLE_TIMING_HH__
#include "cpu/simple/base.hh"
#include "cpu/translation.hh"
#include "params/TimingSimpleCPU.hh"
class TimingSimpleCPU : public BaseSimpleCPU
{
public:
TimingSimpleCPU(TimingSimpleCPUParams * params);
virtual ~TimingSimpleCPU();
virtual void init();
public:
Event *drainEvent;
private:
/*
* If an access needs to be broken into fragments, currently at most two,
* the the following two classes are used as the sender state of the
* packets so the CPU can keep track of everything. In the main packet
* sender state, there's an array with a spot for each fragment. If a
* fragment has already been accepted by the CPU, aka isn't waiting for
* a retry, it's pointer is NULL. After each fragment has successfully
* been processed, the "outstanding" counter is decremented. Once the
* count is zero, the entire larger access is complete.
*/
class SplitMainSenderState : public Packet::SenderState
{
public:
int outstanding;
PacketPtr fragments[2];
int
getPendingFragment()
{
if (fragments[0]) {
return 0;
} else if (fragments[1]) {
return 1;
} else {
return -1;
}
}
};
class SplitFragmentSenderState : public Packet::SenderState
{
public:
SplitFragmentSenderState(PacketPtr _bigPkt, int _index) :
bigPkt(_bigPkt), index(_index)
{}
PacketPtr bigPkt;
int index;
void
clearFromParent()
{
SplitMainSenderState * main_send_state =
dynamic_cast<SplitMainSenderState *>(bigPkt->senderState);
main_send_state->fragments[index] = NULL;
}
};
class FetchTranslation : public BaseTLB::Translation
{
protected:
TimingSimpleCPU *cpu;
public:
FetchTranslation(TimingSimpleCPU *_cpu)
: cpu(_cpu)
{}
void
markDelayed()
{
assert(cpu->_status == Running);
cpu->_status = ITBWaitResponse;
}
void
finish(Fault fault, RequestPtr req, ThreadContext *tc,
BaseTLB::Mode mode)
{
cpu->sendFetch(fault, req, tc);
}
};
FetchTranslation fetchTranslation;
void sendData(RequestPtr req, uint8_t *data, uint64_t *res, bool read);
void sendSplitData(RequestPtr req1, RequestPtr req2, RequestPtr req,
uint8_t *data, bool read);
void translationFault(Fault fault);
void buildPacket(PacketPtr &pkt, RequestPtr req, bool read);
void buildSplitPacket(PacketPtr &pkt1, PacketPtr &pkt2,
RequestPtr req1, RequestPtr req2, RequestPtr req,
uint8_t *data, bool read);
bool handleReadPacket(PacketPtr pkt);
// This function always implicitly uses dcache_pkt.
bool handleWritePacket();
/**
* A TimingCPUPort overrides the default behaviour of the
* recvTiming and recvRetry and implements events for the
* scheduling of handling of incoming packets in the following
* cycle.
*/
class TimingCPUPort : public CpuPort
{
public:
TimingCPUPort(const std::string& _name, TimingSimpleCPU* _cpu)
: CpuPort(_name, _cpu), cpu(_cpu), retryEvent(this)
{ }
protected:
/**
* Snooping a coherence request, do nothing.
*/
virtual void recvTimingSnoopReq(PacketPtr pkt) { }
TimingSimpleCPU* cpu;
struct TickEvent : public Event
{
PacketPtr pkt;
TimingSimpleCPU *cpu;
CpuPort *port;
TickEvent(TimingSimpleCPU *_cpu) : pkt(NULL), cpu(_cpu) {}
const char *description() const { return "Timing CPU tick"; }
void schedule(PacketPtr _pkt, Tick t);
};
EventWrapper<Port, &Port::sendRetry> retryEvent;
};
class IcachePort : public TimingCPUPort
{
public:
IcachePort(TimingSimpleCPU *_cpu)
: TimingCPUPort(_cpu->name() + "-iport", _cpu),
tickEvent(_cpu)
{ }
protected:
virtual bool recvTimingResp(PacketPtr pkt);
virtual void recvRetry();
struct ITickEvent : public TickEvent
{
ITickEvent(TimingSimpleCPU *_cpu)
: TickEvent(_cpu) {}
void process();
const char *description() const { return "Timing CPU icache tick"; }
};
ITickEvent tickEvent;
};
class DcachePort : public TimingCPUPort
{
public:
DcachePort(TimingSimpleCPU *_cpu)
: TimingCPUPort(_cpu->name() + "-dport", _cpu), tickEvent(_cpu)
{ }
protected:
virtual bool recvTimingResp(PacketPtr pkt);
virtual void recvRetry();
struct DTickEvent : public TickEvent
{
DTickEvent(TimingSimpleCPU *_cpu)
: TickEvent(_cpu) {}
void process();
const char *description() const { return "Timing CPU dcache tick"; }
};
DTickEvent tickEvent;
};
IcachePort icachePort;
DcachePort dcachePort;
PacketPtr ifetch_pkt;
PacketPtr dcache_pkt;
Tick previousTick;
protected:
/** Return a reference to the data port. */
virtual CpuPort &getDataPort() { return dcachePort; }
/** Return a reference to the instruction port. */
virtual CpuPort &getInstPort() { return icachePort; }
public:
virtual void serialize(std::ostream &os);
virtual void unserialize(Checkpoint *cp, const std::string §ion);
virtual unsigned int drain(Event *drain_event);
virtual void resume();
void switchOut();
void takeOverFrom(BaseCPU *oldCPU);
virtual void activateContext(ThreadID thread_num, int delay);
virtual void suspendContext(ThreadID thread_num);
Fault readMem(Addr addr, uint8_t *data, unsigned size, unsigned flags);
Fault writeMem(uint8_t *data, unsigned size,
Addr addr, unsigned flags, uint64_t *res);
void fetch();
void sendFetch(Fault fault, RequestPtr req, ThreadContext *tc);
void completeIfetch(PacketPtr );
void completeDataAccess(PacketPtr pkt);
void advanceInst(Fault fault);
/**
* Print state of address in memory system via PrintReq (for
* debugging).
*/
void printAddr(Addr a);
/**
* Finish a DTB translation.
* @param state The DTB translation state.
*/
void finishTranslation(WholeTranslationState *state);
private:
typedef EventWrapper<TimingSimpleCPU, &TimingSimpleCPU::fetch> FetchEvent;
FetchEvent fetchEvent;
struct IprEvent : Event {
Packet *pkt;
TimingSimpleCPU *cpu;
IprEvent(Packet *_pkt, TimingSimpleCPU *_cpu, Tick t);
virtual void process();
virtual const char *description() const;
};
void completeDrain();
};
#endif // __CPU_SIMPLE_TIMING_HH__
<commit_msg>Timing CPU: Remove a redundant port pointer<commit_after>/*
* Copyright (c) 2002-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: Steve Reinhardt
*/
#ifndef __CPU_SIMPLE_TIMING_HH__
#define __CPU_SIMPLE_TIMING_HH__
#include "cpu/simple/base.hh"
#include "cpu/translation.hh"
#include "params/TimingSimpleCPU.hh"
class TimingSimpleCPU : public BaseSimpleCPU
{
public:
TimingSimpleCPU(TimingSimpleCPUParams * params);
virtual ~TimingSimpleCPU();
virtual void init();
public:
Event *drainEvent;
private:
/*
* If an access needs to be broken into fragments, currently at most two,
* the the following two classes are used as the sender state of the
* packets so the CPU can keep track of everything. In the main packet
* sender state, there's an array with a spot for each fragment. If a
* fragment has already been accepted by the CPU, aka isn't waiting for
* a retry, it's pointer is NULL. After each fragment has successfully
* been processed, the "outstanding" counter is decremented. Once the
* count is zero, the entire larger access is complete.
*/
class SplitMainSenderState : public Packet::SenderState
{
public:
int outstanding;
PacketPtr fragments[2];
int
getPendingFragment()
{
if (fragments[0]) {
return 0;
} else if (fragments[1]) {
return 1;
} else {
return -1;
}
}
};
class SplitFragmentSenderState : public Packet::SenderState
{
public:
SplitFragmentSenderState(PacketPtr _bigPkt, int _index) :
bigPkt(_bigPkt), index(_index)
{}
PacketPtr bigPkt;
int index;
void
clearFromParent()
{
SplitMainSenderState * main_send_state =
dynamic_cast<SplitMainSenderState *>(bigPkt->senderState);
main_send_state->fragments[index] = NULL;
}
};
class FetchTranslation : public BaseTLB::Translation
{
protected:
TimingSimpleCPU *cpu;
public:
FetchTranslation(TimingSimpleCPU *_cpu)
: cpu(_cpu)
{}
void
markDelayed()
{
assert(cpu->_status == Running);
cpu->_status = ITBWaitResponse;
}
void
finish(Fault fault, RequestPtr req, ThreadContext *tc,
BaseTLB::Mode mode)
{
cpu->sendFetch(fault, req, tc);
}
};
FetchTranslation fetchTranslation;
void sendData(RequestPtr req, uint8_t *data, uint64_t *res, bool read);
void sendSplitData(RequestPtr req1, RequestPtr req2, RequestPtr req,
uint8_t *data, bool read);
void translationFault(Fault fault);
void buildPacket(PacketPtr &pkt, RequestPtr req, bool read);
void buildSplitPacket(PacketPtr &pkt1, PacketPtr &pkt2,
RequestPtr req1, RequestPtr req2, RequestPtr req,
uint8_t *data, bool read);
bool handleReadPacket(PacketPtr pkt);
// This function always implicitly uses dcache_pkt.
bool handleWritePacket();
/**
* A TimingCPUPort overrides the default behaviour of the
* recvTiming and recvRetry and implements events for the
* scheduling of handling of incoming packets in the following
* cycle.
*/
class TimingCPUPort : public CpuPort
{
public:
TimingCPUPort(const std::string& _name, TimingSimpleCPU* _cpu)
: CpuPort(_name, _cpu), cpu(_cpu), retryEvent(this)
{ }
protected:
/**
* Snooping a coherence request, do nothing.
*/
virtual void recvTimingSnoopReq(PacketPtr pkt) { }
TimingSimpleCPU* cpu;
struct TickEvent : public Event
{
PacketPtr pkt;
TimingSimpleCPU *cpu;
TickEvent(TimingSimpleCPU *_cpu) : pkt(NULL), cpu(_cpu) {}
const char *description() const { return "Timing CPU tick"; }
void schedule(PacketPtr _pkt, Tick t);
};
EventWrapper<Port, &Port::sendRetry> retryEvent;
};
class IcachePort : public TimingCPUPort
{
public:
IcachePort(TimingSimpleCPU *_cpu)
: TimingCPUPort(_cpu->name() + "-iport", _cpu),
tickEvent(_cpu)
{ }
protected:
virtual bool recvTimingResp(PacketPtr pkt);
virtual void recvRetry();
struct ITickEvent : public TickEvent
{
ITickEvent(TimingSimpleCPU *_cpu)
: TickEvent(_cpu) {}
void process();
const char *description() const { return "Timing CPU icache tick"; }
};
ITickEvent tickEvent;
};
class DcachePort : public TimingCPUPort
{
public:
DcachePort(TimingSimpleCPU *_cpu)
: TimingCPUPort(_cpu->name() + "-dport", _cpu), tickEvent(_cpu)
{ }
protected:
virtual bool recvTimingResp(PacketPtr pkt);
virtual void recvRetry();
struct DTickEvent : public TickEvent
{
DTickEvent(TimingSimpleCPU *_cpu)
: TickEvent(_cpu) {}
void process();
const char *description() const { return "Timing CPU dcache tick"; }
};
DTickEvent tickEvent;
};
IcachePort icachePort;
DcachePort dcachePort;
PacketPtr ifetch_pkt;
PacketPtr dcache_pkt;
Tick previousTick;
protected:
/** Return a reference to the data port. */
virtual CpuPort &getDataPort() { return dcachePort; }
/** Return a reference to the instruction port. */
virtual CpuPort &getInstPort() { return icachePort; }
public:
virtual void serialize(std::ostream &os);
virtual void unserialize(Checkpoint *cp, const std::string §ion);
virtual unsigned int drain(Event *drain_event);
virtual void resume();
void switchOut();
void takeOverFrom(BaseCPU *oldCPU);
virtual void activateContext(ThreadID thread_num, int delay);
virtual void suspendContext(ThreadID thread_num);
Fault readMem(Addr addr, uint8_t *data, unsigned size, unsigned flags);
Fault writeMem(uint8_t *data, unsigned size,
Addr addr, unsigned flags, uint64_t *res);
void fetch();
void sendFetch(Fault fault, RequestPtr req, ThreadContext *tc);
void completeIfetch(PacketPtr );
void completeDataAccess(PacketPtr pkt);
void advanceInst(Fault fault);
/**
* Print state of address in memory system via PrintReq (for
* debugging).
*/
void printAddr(Addr a);
/**
* Finish a DTB translation.
* @param state The DTB translation state.
*/
void finishTranslation(WholeTranslationState *state);
private:
typedef EventWrapper<TimingSimpleCPU, &TimingSimpleCPU::fetch> FetchEvent;
FetchEvent fetchEvent;
struct IprEvent : Event {
Packet *pkt;
TimingSimpleCPU *cpu;
IprEvent(Packet *_pkt, TimingSimpleCPU *_cpu, Tick t);
virtual void process();
virtual const char *description() const;
};
void completeDrain();
};
#endif // __CPU_SIMPLE_TIMING_HH__
<|endoftext|> |
<commit_before>//
// Created by Dawid Drozd aka Gelldur on 7/19/16.
//
#include "Preferences.h"
#include<cstdio>
#include <Poco/Data/Session.h>
#include <Poco/Data/SQLite/Connector.h>
#include <log.h>
#include <acme/MakeUnique.h>
Preferences::Preferences(const std::string& databaseName, const std::string& tableName)
: TABLE_NAME(tableName)
, DATABSE_FILE_NAME(databaseName)
{
Poco::Data::SQLite::Connector::registerConnector();
recreate();
}
Preferences::~Preferences()
{
_session->close();
Poco::Data::SQLite::Connector::unregisterConnector();
}
void Preferences::setValue(const std::string& key, const std::string& value)
{
_cache[key] = value;
if (_session == nullptr)
{
ELOG("Session not created\nNo storage");
return;
}
Poco::Data::Session& session = *_session;
Poco::Data::Statement insert(session);
insert << "INSERT OR REPLACE INTO " << TABLE_NAME << " VALUES(?, ?)",
Poco::Data::Keywords::useRef(key),
Poco::Data::Keywords::useRef(value);
DLOG("Preferences: %s\n(%s)=(%s)", insert.toString().c_str(), key.c_str(), value.c_str());
insert.execute();
}
std::string Preferences::getValue(const std::string& key, const std::string& defaultValue)
{
auto found = _cache.find(key);
if (found != _cache.end())
{
return found->second;
}
if (_session == nullptr)
{
ELOG("Session not created\nNo storage");
_cache[key] = defaultValue;
return defaultValue;
}
std::string returnedValue = defaultValue;
Poco::Data::Session& session = *_session;
// a simple query
Poco::Data::Statement select(session);
select << "SELECT value FROM " << TABLE_NAME << " WHERE key=?",
Poco::Data::Keywords::useRef(key),
Poco::Data::Keywords::into(returnedValue); // iterate over result set one row at a time
DLOG("Select: %s\nkey:%s", select.toString().c_str(), key.c_str());
select.execute();
_cache[key] = returnedValue;
return returnedValue;
}
void Preferences::clean()
{
_cache.clear();
if (_session == nullptr)
{
ELOG("Session not created\nNo storage");
return;
}
_session->close();
if (std::remove(DATABSE_FILE_NAME.c_str()) != 0)
{
ELOG("Can't remove database: %s", DATABSE_FILE_NAME.c_str());
}
recreate();
}
void Preferences::recreate()
{
_session = std::make_unique<Poco::Data::Session>("SQLite", DATABSE_FILE_NAME.c_str());
if (_session == nullptr)
{
ELOG("Session not created\nNo storage");
return;
}
Poco::Data::Session& session = *_session;
session << "CREATE TABLE IF NOT EXISTS `" << TABLE_NAME << "`("
"`key` TEXT NOT NULL UNIQUE,"
"`value` TEXT,"
"PRIMARY KEY(key)"
");", Poco::Data::Keywords::now;
}
<commit_msg>Fix NPE<commit_after>//
// Created by Dawid Drozd aka Gelldur on 7/19/16.
//
#include "Preferences.h"
#include<cstdio>
#include <Poco/Data/Session.h>
#include <Poco/Data/SQLite/Connector.h>
#include <log.h>
#include <acme/MakeUnique.h>
Preferences::Preferences(const std::string& databaseName, const std::string& tableName)
: TABLE_NAME(tableName)
, DATABSE_FILE_NAME(databaseName)
{
Poco::Data::SQLite::Connector::registerConnector();
recreate();
}
Preferences::~Preferences()
{
if (_session != nullptr)
{
_session->close();
}
Poco::Data::SQLite::Connector::unregisterConnector();
}
void Preferences::setValue(const std::string& key, const std::string& value)
{
_cache[key] = value;
if (_session == nullptr)
{
ELOG("Session not created\nNo storage");
return;
}
Poco::Data::Session& session = *_session;
Poco::Data::Statement insert(session);
insert << "INSERT OR REPLACE INTO " << TABLE_NAME << " VALUES(?, ?)",
Poco::Data::Keywords::useRef(key),
Poco::Data::Keywords::useRef(value);
DLOG("Preferences: %s\n(%s)=(%s)", insert.toString().c_str(), key.c_str(), value.c_str());
insert.execute();
}
std::string Preferences::getValue(const std::string& key, const std::string& defaultValue)
{
auto found = _cache.find(key);
if (found != _cache.end())
{
return found->second;
}
if (_session == nullptr)
{
ELOG("Session not created\nNo storage");
_cache[key] = defaultValue;
return defaultValue;
}
std::string returnedValue = defaultValue;
Poco::Data::Session& session = *_session;
// a simple query
Poco::Data::Statement select(session);
select << "SELECT value FROM " << TABLE_NAME << " WHERE key=?",
Poco::Data::Keywords::useRef(key),
Poco::Data::Keywords::into(returnedValue); // iterate over result set one row at a time
DLOG("Select: %s\nkey:%s", select.toString().c_str(), key.c_str());
select.execute();
_cache[key] = returnedValue;
return returnedValue;
}
void Preferences::clean()
{
_cache.clear();
if (_session == nullptr)
{
ELOG("Session not created\nNo storage");
return;
}
_session->close();
if (std::remove(DATABSE_FILE_NAME.c_str()) != 0)
{
ELOG("Can't remove database: %s", DATABSE_FILE_NAME.c_str());
}
recreate();
}
void Preferences::recreate()
{
_session = std::make_unique<Poco::Data::Session>("SQLite", DATABSE_FILE_NAME.c_str());
if (_session == nullptr)
{
ELOG("Session not created\nNo storage");
return;
}
Poco::Data::Session& session = *_session;
session << "CREATE TABLE IF NOT EXISTS `" << TABLE_NAME << "`("
"`key` TEXT NOT NULL UNIQUE,"
"`value` TEXT,"
"PRIMARY KEY(key)"
");", Poco::Data::Keywords::now;
}
<|endoftext|> |
<commit_before>#include <stdexcept>
#include "python_api.h"
static int python_count=0;
Python::Python()
{
this->_init(-1, NULL);
}
Python::Python(int argc, char* argv[])
{
this->_init(argc, argv);
}
void Python::_init(int argc, char* argv[])
{
python_count++;
if (python_count == 1) {
// This is a hack, so that we can load hermes_common below. Some better
// mechanism should be used instead, once we figure out how to do it:
putenv((char *)"PYTHONPATH=.:../..:../../../python");
Py_Initialize();
if (argc >= 0)
PySys_SetArgv(argc, argv);
if (import__hermes_common())
throw std::runtime_error("hermes_common failed to import.");
}
this->_namespace = namespace_create();
}
Python::~Python()
{
// Free the namespace. This frees all the dictionary items, so if there
// are some numpy arrays (or your classes) in the namespace, they will be
// deallocated at this time.
Py_DECREF(this->_namespace);
// free the interpreter if this was the last instance using it:
python_count--;
if (python_count == 0) {
// don't finalize python, because the numpy package segfaults when
// imported again:
//Py_Finalize();
}
}
void Python::print()
{
namespace_print(_namespace);
}
void Python::exec(const char *text)
{
run_cmd(text, this->_namespace);
}
void Python::push(const char *name, PyObject *o)
{
namespace_push(this->_namespace, name, o);
// namespace_push() is a regular Cython function and
// as such, it increfs the object "o" before storing it in the namespace,
// but we want to steal the reference, so we decref it here (there is still
// at least one reference stored in the dictionary this->_namespace, so
// it's safe). This is so that
// this->push("i", c2py_int(5));
// doesn't leak (c2py_int() creates a python reference and push() destroys
// this python reference)
Py_DECREF(o);
}
PyObject *Python::pull(const char *name)
{
PyObject *tmp = namespace_pull(this->_namespace, name);
// namespace_pull() is a regular Cython function and
// as such, it increfs the result before returning it, but we only want to
// borrow a reference, so we decref it here (there is still at least one
// reference stored in the dictionary this->_namespace, so it's safe)
// This is so that
// int i = py2c_int(this->pull("i"));
// doesn't leak (pull() borrows the reference, py2c_int() doesn't do
// anything with the reference, so no leak nor segfault happens)
Py_DECREF(tmp);
return tmp;
}
<commit_msg>refactor setting up PYTHONPATH<commit_after>#include <stdexcept>
#include "python_api.h"
#include "matrix.h"
static int python_count=0;
Python::Python()
{
this->_init(-1, NULL);
}
Python::Python(int argc, char* argv[])
{
this->_init(argc, argv);
}
void Python::_init(int argc, char* argv[])
{
python_count++;
if (python_count == 1) {
char *PYTHONPATH = getenv("PYTHONPATH");
if (PYTHONPATH == NULL)
_error("internal error in hermes_common: PYTHONPATH not defined");
int max_len = 10000;
char new_path[max_len];
// This is a hack, so that we can load hermes_common below. Some better
// mechanism should be used instead, once we figure out how to do it:
int nchars = snprintf(new_path, max_len, "PYTHONPATH=.:../..:../../../python:../hermes_common/:../../hermes_common/:%s", PYTHONPATH);
if (nchars >= max_len)
_error("internal error in hermes_common: PYTHONPATH too long.");
// We have to make a copy of the string, because new_path[] will get
// deallocated:
putenv(strdup(new_path));
Py_Initialize();
if (argc >= 0)
PySys_SetArgv(argc, argv);
if (import__hermes_common())
throw std::runtime_error("hermes_common failed to import.");
}
this->_namespace = namespace_create();
}
Python::~Python()
{
// Free the namespace. This frees all the dictionary items, so if there
// are some numpy arrays (or your classes) in the namespace, they will be
// deallocated at this time.
Py_DECREF(this->_namespace);
// The code below would free the interpreter if this was the last instance
// using it. However, it is currently disabled, because the numpy package
// segfaults when imported again; also the PYTHONPATH is set only once if
// python_count is never decreased (which is what we want).
/*python_count--;
if (python_count == 0) {
Py_Finalize();
}
*/
}
void Python::print()
{
namespace_print(_namespace);
}
void Python::exec(const char *text)
{
run_cmd(text, this->_namespace);
}
void Python::push(const char *name, PyObject *o)
{
namespace_push(this->_namespace, name, o);
// namespace_push() is a regular Cython function and
// as such, it increfs the object "o" before storing it in the namespace,
// but we want to steal the reference, so we decref it here (there is still
// at least one reference stored in the dictionary this->_namespace, so
// it's safe). This is so that
// this->push("i", c2py_int(5));
// doesn't leak (c2py_int() creates a python reference and push() destroys
// this python reference)
Py_DECREF(o);
}
PyObject *Python::pull(const char *name)
{
PyObject *tmp = namespace_pull(this->_namespace, name);
// namespace_pull() is a regular Cython function and
// as such, it increfs the result before returning it, but we only want to
// borrow a reference, so we decref it here (there is still at least one
// reference stored in the dictionary this->_namespace, so it's safe)
// This is so that
// int i = py2c_int(this->pull("i"));
// doesn't leak (pull() borrows the reference, py2c_int() doesn't do
// anything with the reference, so no leak nor segfault happens)
Py_DECREF(tmp);
return tmp;
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2016 Genome Research Ltd.
Author: Jouni Siren <[email protected]>
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 "gcsa.h"
using namespace gcsa;
//------------------------------------------------------------------------------
int
main(int argc, char** argv)
{
if(argc < 3)
{
std::cerr << "usage: query_gcsa base_name patterns" << std::endl;
std::cerr << std::endl;
std::exit(EXIT_SUCCESS);
}
std::string base_name = argv[1];
std::string pattern_name = argv[2];
std::cout << "GCSA2 query benchmark" << std::endl;
std::cout << std::endl;
printHeader("Base name"); std::cout << base_name << std::endl;
printHeader("Pattern file"); std::cout << pattern_name << std::endl;
std::cout << std::endl;
GCSA index;
std::string gcsa_name = base_name + GCSA::EXTENSION;
sdsl::load_from_file(index, gcsa_name);
printHeader("GCSA"); std::cout << inMegabytes(sdsl::size_in_bytes(index)) << " MB" << std::endl;
std::vector<std::string> patterns;
size_type pattern_total = readRows(pattern_name, patterns, true);
printHeader("Patterns");
std::cout << patterns.size() << " (total " << inMegabytes(pattern_total) << " MB)" << std::endl;
std::cout << std::endl;
std::vector<range_type> ranges; ranges.reserve(patterns.size());
{
double start = readTimer();
for(size_type i = 0; i < patterns.size(); i++)
{
range_type temp = index.find(patterns[i]);
if(!Range::empty(temp)) { ranges.push_back(temp); }
}
double seconds = readTimer() - start;
printTime("find()", patterns.size(), seconds);
printHeader("find()");
std::cout << "Found " << ranges.size() << " patterns ("
<< (inMegabytes(pattern_total) / seconds) << " MB/s)" << std::endl;
std::cout << std::endl;
}
std::vector<size_type> counts(ranges.size());
{
double start = readTimer();
for(size_type i = 0; i < ranges.size(); i++)
{
counts[i] = index.count(ranges[i]);
}
double seconds = readTimer() - start;
printTime("count()", ranges.size(), seconds);
std::cout << std::endl;
}
{
double start = readTimer();
std::vector<node_type> results;
size_type total = 0;
for(size_type i = 0; i < ranges.size(); i++)
{
index.locate(ranges[i], results);
counts[i] -= results.size();
total += results.size();
}
double seconds = readTimer() - start;
printTime("locate()", ranges.size(), seconds);
printHeader("locate()");
std::cout << "Found " << total << " occurrences (" <<
(total / seconds) << " / second)" << std::endl;
std::cout << std::endl;
}
bool ok = true;
for(size_type i = 0; i < counts.size(); i++)
{
if(counts[i] != 0) { ok = false; }
}
if(!ok)
{
std::cout << "Warning: count() and locate() returned inconsistent results" << std::endl;
std::cout << std::endl;
}
return 0;
}
//------------------------------------------------------------------------------
<commit_msg>Filter patterns of Ns in the benchmark<commit_after>/*
Copyright (c) 2016 Genome Research Ltd.
Author: Jouni Siren <[email protected]>
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 "gcsa.h"
using namespace gcsa;
//------------------------------------------------------------------------------
void filter(std::vector<std::string>& patterns);
int
main(int argc, char** argv)
{
if(argc < 3)
{
std::cerr << "usage: query_gcsa base_name patterns" << std::endl;
std::cerr << std::endl;
std::exit(EXIT_SUCCESS);
}
std::string base_name = argv[1];
std::string pattern_name = argv[2];
std::cout << "GCSA2 query benchmark" << std::endl;
std::cout << std::endl;
printHeader("Base name"); std::cout << base_name << std::endl;
printHeader("Pattern file"); std::cout << pattern_name << std::endl;
std::cout << std::endl;
GCSA index;
std::string gcsa_name = base_name + GCSA::EXTENSION;
sdsl::load_from_file(index, gcsa_name);
printHeader("GCSA"); std::cout << inMegabytes(sdsl::size_in_bytes(index)) << " MB" << std::endl;
std::vector<std::string> patterns;
size_type pattern_total = readRows(pattern_name, patterns, true);
filter(patterns);
printHeader("Patterns");
std::cout << patterns.size() << " (total " << inMegabytes(pattern_total) << " MB)" << std::endl;
std::cout << std::endl;
std::vector<range_type> ranges; ranges.reserve(patterns.size());
{
double start = readTimer();
for(size_type i = 0; i < patterns.size(); i++)
{
range_type temp = index.find(patterns[i]);
if(!Range::empty(temp)) { ranges.push_back(temp); }
}
double seconds = readTimer() - start;
printTime("find()", patterns.size(), seconds);
printHeader("find()");
std::cout << "Found " << ranges.size() << " patterns ("
<< (inMegabytes(pattern_total) / seconds) << " MB/s)" << std::endl;
std::cout << std::endl;
}
std::vector<size_type> counts(ranges.size());
{
double start = readTimer();
for(size_type i = 0; i < ranges.size(); i++)
{
counts[i] = index.count(ranges[i]);
}
double seconds = readTimer() - start;
printTime("count()", ranges.size(), seconds);
std::cout << std::endl;
}
{
double start = readTimer();
std::vector<node_type> results;
size_type total = 0;
for(size_type i = 0; i < ranges.size(); i++)
{
index.locate(ranges[i], results);
counts[i] -= results.size();
total += results.size();
}
double seconds = readTimer() - start;
printTime("locate()", ranges.size(), seconds);
printHeader("locate()");
std::cout << "Found " << total << " occurrences (" <<
(total / seconds) << " / second)" << std::endl;
std::cout << std::endl;
}
bool ok = true;
for(size_type i = 0; i < counts.size(); i++)
{
if(counts[i] != 0) { ok = false; }
}
if(!ok)
{
std::cout << "Warning: count() and locate() returned inconsistent results" << std::endl;
std::cout << std::endl;
}
return 0;
}
//------------------------------------------------------------------------------
void
filter(std::vector<std::string>& patterns)
{
size_type tail = 0;
for(size_type i = 0; i < patterns.size(); i++)
{
const std::string& curr = patterns[i];
for(size_type j = 0; j < curr.length(); j++)
{
if(curr[j] != 'N') { patterns[tail] = curr; tail++; break; }
}
}
patterns.resize(tail);
}
//------------------------------------------------------------------------------
<|endoftext|> |
<commit_before>// Copyright 2013 Sean McKenna
//
// 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.
//
// a ray tracer in C++
// libraries, namespace
#include <thread>
#include <fstream>
#include "xmlload.cpp"
#include "scene.cpp"
using namespace std;
// variables for ray tracing
int w;
int h;
int size;
Color24 white = {233, 233, 233};
Color24 black = {33, 33, 33};
Color24* img;
float* zImg;
// variables for threading
static const int numThreads = 8;
void rayTracing(int i);
// variables for camera ray generation
void cameraRayVars();
Point3 *imageTopLeftV;
Point3 *dXV;
Point3 *dYV;
Point3 firstPixel;
Point3 cameraPos;
Point3 cameraDir;
Transformation* c;
Point3 cameraRay(int pX, int pY);
// trace a ray against all objects
void objectIntersection(Node &n, Ray r, int pixel);
// ray tracer
int main(){
// load scene: root node, camera, image
LoadScene("scenes/prj1.xml");
// set up background image color
renderImage.setBackground(black);
// variables for ray tracing
w = renderImage.GetWidth();
h = renderImage.GetHeight();
size = w * h;
img = renderImage.GetPixels();
zImg = renderImage.GetZBuffer();
// variables for generating camera rays
cameraRayVars();
// ray tracing loop (in parallel with threads)
std::thread t[numThreads];
for(int i = 0; i < numThreads; i++)
t[i] = std::thread(rayTracing, i);
// join threads back to main
for(int i = 0; i < numThreads; i++)
t[i].join();
// output ray-traced image & z-buffer
renderImage.SaveImage("images/image.ppm");
renderImage.ComputeZBufferImage();
renderImage.SaveZImage("images/imageZ.ppm");
}
// ray tracing loop (for an individual pixel)
void rayTracing(int i){
// initial starting pixel
int pixel = i;
// thread continuation condition
while(pixel < size){
// establish pixel location
int pX = pixel % w;
int pY = pixel / w;
// transform ray into world space
Point3 rayDir = cameraRay(pX, pY);
Ray *ray = new Ray();
ray->p = cameraPos;
ray->dir = c->TransformFrom(rayDir);
// traverse through scene DOM
// transform rays into model space
// detect ray intersections & update pixel
objectIntersection(rootNode, *ray, pixel);
// re-assign next pixel
pixel += numThreads;
}
}
// create variables for camera ray generation
void cameraRayVars(){
float fov = camera.fov * M_PI / 180.0;
float aspectRatio = (float) w / (float) h;
float imageDistance = 1.0;
float imageTipY = imageDistance * tan(fov / 2.0);
float imageTipX = imageTipY * aspectRatio;
float dX = (2.0 * imageTipX) / (float) w;
float dY = (2.0 * imageTipY) / (float) h;
imageTopLeftV = new Point3(-imageTipX, imageTipY, -imageDistance);
dXV = new Point3(dX, 0.0, 0.0);
dYV = new Point3(0.0, -dY, 0.0);
firstPixel = *imageTopLeftV + (*dXV * 0.5) + (*dYV * 0.5);
// set up camera transformation (translation + rotation)
Point3 cameraPos = camera.pos;
c = new Transformation();
c->Translate(cameraPos);
Matrix3 *rotate = new cyMatrix3f();
Point3 cameraDir = camera.dir;
Point3 cameraUp = camera.up;
cameraDir.Normalize();
cameraUp.Normalize();
Point3 cameraCross = cameraDir ^ cameraUp;
cameraCross.Normalize();
rotate->Set(cameraCross, cameraUp, -cameraDir);
c->Transform(*rotate);
}
// compute camera rays
Point3 cameraRay(int pX, int pY){
Point3 ray = firstPixel + (*dXV * pX) + (*dYV * pY);
ray.Normalize();
return ray;
}
// recursive object intersection through all scene objects
void objectIntersection(Node &n, Ray r, int pixel){
// loop on child nodes
int j = 0;
int numChild = n.GetNumChild();
while(j < numChild){
// grab child node
Node *child = n.GetChild(j);
Object *obj = child->GetObject();
// transform rays into model space (or local space)
Ray r2 = child->ToNodeCoords(r);
// compute ray intersections
HitInfo h = HitInfo();
bool hit = obj->IntersectRay(r2, h);
// check the ray computation, update pixel & z-buffer
if(hit){
img[pixel] = white;
if(h.z < zImg[pixel])
zImg[pixel] = h.z;
}
// recursively check this child's children
objectIntersection(*child, r2, pixel);
j++;
}
}
<commit_msg>refactor ray-tracer to clean up and better comments<commit_after>// Copyright 2013 Sean McKenna
//
// 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.
//
// a ray tracer in C++
// libraries, namespace
#include <thread>
#include <fstream>
#include "xmlload.cpp"
#include "scene.cpp"
using namespace std;
// for ray tracing
int w;
int h;
int size;
Color24 white = {233, 233, 233};
Color24 black = {33, 33, 33};
Color24* img;
float* zImg;
// for threading
static const int numThreads = 8;
void rayTracing(int i);
// for camera ray generation
void cameraRayVars();
Point3 *imageTopLeftV;
Point3 *dXV;
Point3 *dYV;
Point3 firstPixel;
Point3 cameraPos;
Point3 cameraDir;
Transformation* c;
Point3 cameraRay(int pX, int pY);
// for tracing rays to objects
void objectIntersection(Node &n, Ray r, int pixel);
// ray tracer
int main(){
// load scene: root node, camera, image
LoadScene("scenes/prj1.xml");
// set up background image color
renderImage.setBackground(black);
// set variables for ray tracing
w = renderImage.GetWidth();
h = renderImage.GetHeight();
size = w * h;
img = renderImage.GetPixels();
zImg = renderImage.GetZBuffer();
// set variables for generating camera rays
cameraRayVars();
// start ray tracing loop (in parallel with threads)
thread t[numThreads];
for(int i = 0; i < numThreads; i++)
t[i] = thread(rayTracing, i);
// when finished, join all threads back to main
for(int i = 0; i < numThreads; i++)
t[i].join();
// output ray-traced image & z-buffer
renderImage.SaveImage("images/image.ppm");
renderImage.ComputeZBufferImage();
renderImage.SaveZImage("images/imageZ.ppm");
}
// ray tracing loop (for an individual pixel)
void rayTracing(int i){
// initial starting pixel
int pixel = i;
// thread continuation condition
while(pixel < size){
// establish pixel location
int pX = pixel % w;
int pY = pixel / w;
// transform ray into world space
Point3 rayDir = cameraRay(pX, pY);
Ray *ray = new Ray();
ray->p = cameraPos;
ray->dir = c->TransformFrom(rayDir);
// traverse through scene DOM
// transform rays into model space
// detect ray intersections & update pixel
objectIntersection(rootNode, *ray, pixel);
// re-assign next pixel (naive, but works)
pixel += numThreads;
}
}
// create variables for camera ray generation
void cameraRayVars(){
float fov = camera.fov * M_PI / 180.0;
float aspectRatio = (float) w / (float) h;
float imageDistance = 1.0;
float imageTipY = imageDistance * tan(fov / 2.0);
float imageTipX = imageTipY * aspectRatio;
float dX = (2.0 * imageTipX) / (float) w;
float dY = (2.0 * imageTipY) / (float) h;
imageTopLeftV = new Point3(-imageTipX, imageTipY, -imageDistance);
dXV = new Point3(dX, 0.0, 0.0);
dYV = new Point3(0.0, -dY, 0.0);
firstPixel = *imageTopLeftV + (*dXV * 0.5) + (*dYV * 0.5);
// set up camera transformation (translation + rotation)
Point3 cameraPos = camera.pos;
c = new Transformation();
c->Translate(cameraPos);
Matrix3 *rotate = new cyMatrix3f();
Point3 cameraDir = camera.dir;
Point3 cameraUp = camera.up;
cameraDir.Normalize();
cameraUp.Normalize();
Point3 cameraCross = cameraDir ^ cameraUp;
cameraCross.Normalize();
rotate->Set(cameraCross, cameraUp, -cameraDir);
c->Transform(*rotate);
}
// compute camera rays
Point3 cameraRay(int pX, int pY){
Point3 ray = firstPixel + (*dXV * pX) + (*dYV * pY);
ray.Normalize();
return ray;
}
// recursive object intersection through all scene objects
void objectIntersection(Node &n, Ray r, int pixel){
// loop on child nodes
int j = 0;
int numChild = n.GetNumChild();
while(j < numChild){
// grab child node
Node *child = n.GetChild(j);
Object *obj = child->GetObject();
// transform rays into model space (or local space)
Ray r2 = child->ToNodeCoords(r);
// compute ray intersections
HitInfo h = HitInfo();
bool hit = obj->IntersectRay(r2, h);
// check the ray computation, update pixel & z-buffer
if(hit){
img[pixel] = white;
if(h.z < zImg[pixel])
zImg[pixel] = h.z;
}
// recursively check this child's children
objectIntersection(*child, r2, pixel);
j++;
}
}
<|endoftext|> |
<commit_before>/**@addtogroup Probe Test whether a given port on a host is connectable.
* @{@file
*
* This application attempts to connect to a server and port, and just returns
* the status as a result to the invoker.
*
* @author Nigel Bree <[email protected]>
*
* Copyright (C) 2011 Nigel Bree; All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <winsock2.h>
#include <ws2tcpip.h>
/**
* Cliche for returning array lengths.
*/
#define ARRAY_LENGTH(a) (sizeof (a) / sizeof ((a) [0]))
/**
* Simple command-line argument extraction, about as unsophisticated as it can
* possibly get.
*/
wchar_t * split (wchar_t * args) {
if (args == 0)
return args;
/*
* The argument is quoted (which is typical of the first argument, the
* program name, because of the need to avoid problems with spaces in
* the path), in which case we skip to the ending quote first.
*/
if (* args == '"') {
for (;;) {
++ args;
wchar_t ch = * args;
if (ch == '"')
break;
if (ch == 0)
return 0;
}
}
/*
* Split at the next space.
*/
for (;;) {
wchar_t ch = * args;
if (ch == ' ')
break;
if (ch == 0)
return 0;
++ args;
}
* args = 0;
++ args;
/*
* If there are additional spaces, consume them.
*/
while (* args == ' ')
++ args;
return args;
}
/**
* If we're asked to probe for an NTTP port, then sometimes we have to deal
* with local proxies.
*
* In this case, we actually try and read from the socket to at least get the
* server's initial hello. For the annoying Avast! proxy, that at least does
* not get sent until the real target responds to the proxy, and if the proxy
* connection doesn't work (after 5-6 seconds, since it tries the TLS version
* of the port even if we connected plain-text) then it spits a 400 out.
*/
int checkNntp (SOCKET s) {
char buf [128];
int result;
result = recv (s, buf, sizeof (buf), 0);
if (result < 5)
return 1;
/*
* Various tedious socket-isms can apply, such as the bytes for the
* initial response code trickling in over time. Let's not worry
* about that, just deal with the basics.
*/
void * end = memchr (buf, ' ', result);
if (end == 0)
return 1;
return memcmp (buf, "400", 3) == 0 ? 1 : 0;
}
/**
* If we're asked to probe for an HTTP port, then we need to avoid problems
* with local proxies.
*
* Unlike NNTP, the HTTP protocol is client-driven; as it turns out the way the
* crappy Avast! proxy works is that it'll unilaterally close the connection if
* it can't reach the real intended target, but in order to have this work for
* real targets it pays to request a resource. The safest thing to ask for seems
* to be favicon.ico - it's something lots of browsers request anyway and it's
* almost always a small image, so we shouldn't clog up logs with requests for
* 404 resources or get elaborate 404 response pages back.
*
* It turns out that the Avast! proxy has some other exciting misbehaviours; it
* will sometimes (but not always) when a connection fails return an "HTTP/1.1
* 200 OK" status with some fixed bogus fields, one of which is a "Refresh: 1;"
* to re-fetch the target URL.
*/
int checkHttp (SOCKET s, HANDLE show) {
static char head [] = "HEAD /favicon.ico HTTP/1.0\n\n";
int result;
int length = strlen (head);
result = send (s, head, length, 0);
if (result < length)
return 1;
char buf [1024];
result = recv (s, buf, sizeof (buf) - 1, 0);
#if 1
/*
* Show the HTTP response, for debugging. I'll keep this in as long as
* it doesn't cost me any compile-time space.
*/
if (result > 0 && show > 0) {
HANDLE err = GetStdHandle (STD_ERROR_HANDLE);
unsigned long written = 0;
WriteFile (err, buf, result, & written, 0);
}
#endif
/*
* Normally we wouldn't care what the actual response text was, but to
* deal with the fake response sometimes returned from Avast! I have to
* recognize and suppress it.
*/
if (result > 0) {
buf [result] = 0;
if (strstr (buf, "\nRefresh: 1;") != 0)
return 1;
}
return result < 5 ? 1 : 0;
}
/**
* Probe for the indicated port at the given host.
*/
int probe (wchar_t * host, wchar_t * port, HANDLE show) {
/*
* Detect the presence of the Avast! virus scanner; it includes a set
* of proxy-type firewalls that are somewhat tedious to deal with, and
* in the case of NNTP mean that NNTP connections go through their
* proxy; so, our connect will succeed (being locally looped back) and
* send us nothing while the proxy module slowly decides whether it can
* or can't connect to the real target over TLS or plain-text NNTP.
*
* So, if Avast! is present we can choose to either try and read from
* the socket once it connects (so we can get the response code, which
* will generally be 400 once the Avast proxy fails), or we can forget
* the whole probing process because that introduces too much delay.
*/
HMODULE avast = GetModuleHandle (L"snxhk.dll");
SOCKET s;
s = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (s == SOCKET_ERROR)
return 2;
sockaddr_in any;
any.sin_family = AF_INET;
any.sin_port = 0;
any.sin_addr.S_un.S_addr = INADDR_ANY;
if (bind (s, (sockaddr *) & any, sizeof (any)) != 0)
return 2;
/*
* Look up the hostname and convert the port number into numeric form,
* all handily in one function.
*/
ADDRINFOW * address;
if (GetAddrInfoW (host, port, 0, & address) != 0)
return 2;
/*
* Ensure that we only connect via IPv4, having made an IPv4 socket
* already (yes, I could do things in a different order, but for my
* purposes here with Steam I care about IPv4 only for now since they
* are IPv4-only).
*/
while (address->ai_addr->sa_family != AF_INET)
if ((address = address->ai_next) == 0)
return 2;
/*
* Just test whether the port is open or not.
*/
int result;
result = connect (s, address->ai_addr, address->ai_addrlen) ? 1 : 0;
/*
* Decide whether to actually wait for data, if we're dealing with the
* Avast! proxy being present on a system.
*/
sockaddr_in * addr = (sockaddr_in *) address->ai_addr;
switch (htons (addr->sin_port)) {
case 119:
if (avast && result == 0)
result = checkNntp (s);
break;
case 80:
if (avast && result == 0)
result = checkHttp (s, show);
break;
default:
break;
}
return result;
}
#include <iphlpapi.h>
#include <icmpapi.h>
#include "../steamfilter/glob.h"
/*
* As an alternative to probing for a host, do a traceroute and permit glob
* matches against the hostnames.
*
* In principle one could just script a traceroute, but that's a bit slow and
* rather than writing a regex against the output it seems better to have a
* more direct match available.
*/
int trace (wchar_t * host, wchar_t * pattern, HANDLE err) {
HANDLE icmp = IcmpCreateFile ();
if (icmp == INVALID_HANDLE_VALUE)
return 2;
/*
* Resolve an IPv4 hostname.
*/
ADDRINFOW * address;
if (GetAddrInfoW (host, 0, 0, & address) != 0)
return 2;
/*
* Ensure that we only connect via IPv4, having made an IPv4 socket
* already (yes, I could do things in a different order, but for my
* purposes here with Steam I care about IPv4 only for now since they
* are IPv4-only).
*/
while (address->ai_addr->sa_family != AF_INET)
if ((address = address->ai_next) == 0)
return 2;
sockaddr_in * addr = (sockaddr_in *) address->ai_addr;
IPAddr dest = addr->sin_addr.s_addr;
/*
* The timeouts in this loop are tighter than they are in general kinds
* of traceroute applications since we are generally probing for things
* near to the origin system and with latencies in the <50ms bracket.
*/
unsigned short ttl = 1;
for (; ttl < 5 ; ++ ttl) {
unsigned char buf [128];
/*
* Part the first; send an echo request.
*/
IP_OPTION_INFORMATION info = { ttl };
DWORD echo;
echo = IcmpSendEcho (icmp, dest, 0, 0, & info, buf, sizeof (buf), 50);
if (echo < 1)
continue;
/*
* We expect to see IP_TTL_EXPIRED_TRANSIT since we set the TTL
* to find the intermediate systems.
*/
ICMP_ECHO_REPLY * reply = (ICMP_ECHO_REPLY *) buf;
if (reply->Status != IP_TTL_EXPIRED_TRANSIT && reply->Status != 0)
return 1;
/*
* Part the second; protocol-independent reverse name lookup.
*/
sockaddr_in find = { AF_INET };
find.sin_addr.s_addr = reply->Address;
find.sin_port = 0;
char name [128];
char port [20];
unsigned long error;
error = getnameinfo ((SOCKADDR *) & find, sizeof (find),
name, ARRAY_LENGTH (name),
0, 0, NI_NAMEREQD);
if (error != 0)
continue;
/*
* We have a name, now we can glob-match it. If we see the
* desired pattern, we win. If we don't, we bail; the first
* name we resolve wins.
*/
return globMatch (name, pattern) ? 0 : 1;
}
return 1;
}
/**
* This is intended as a "naked" WinMain without the Visual C++ run-time
* at all (not just avoiding the broken locale machinery).
*/
int CALLBACK myWinMain (void) {
HANDLE err = GetStdHandle (STD_ERROR_HANDLE);
unsigned long written = 0;
/*
* Since we're not using the regular C machinery, get and split the
* command line by hand. The CommandLineToArgvW () routine would do the
* normal conversion to C style for us, but that depends on SHELL32.DLL
* and we shouldn't need it.
*/
wchar_t * base = GetCommandLineW ();
wchar_t * name = split (base);
wchar_t * port = split (name);
wchar_t * extra = split (port);
if (port == 0)
return 2;
WSADATA wsaData;
if (WSAStartup (MAKEWORD (2, 2), & wsaData) != 0)
return 2;
int result;
if (wcscmp (port, L"icmp") == 0) {
result = trace (name, extra, err);
} else {
result = probe (name, port, err);
}
if (extra == 0)
ExitProcess (result);
static const char text [] = "Probe result: ";
WriteFile (err, text, strlen (text), & written, 0);
char buf [2] = { '0' + result };
WriteFile (err, buf, 1, & written, 0);
ExitProcess (result);
}
<commit_msg>Add some more polish to the probe utility to prepare for a v0.5.4.0 release<commit_after>/**@addtogroup Probe Test whether a given port on a host is connectable.
* @{@file
*
* This application attempts to connect to a server and port, and just returns
* the status as a result to the invoker.
*
* @author Nigel Bree <[email protected]>
*
* Copyright (C) 2011 Nigel Bree; All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <winsock2.h>
#include <ws2tcpip.h>
/**
* Cliche for returning array lengths.
*/
#define ARRAY_LENGTH(a) (sizeof (a) / sizeof ((a) [0]))
/**
* Simple command-line argument extraction, about as unsophisticated as it can
* possibly get.
*/
wchar_t * split (wchar_t * args) {
if (args == 0)
return args;
/*
* The argument is quoted (which is typical of the first argument, the
* program name, because of the need to avoid problems with spaces in
* the path), in which case we skip to the ending quote first.
*/
wchar_t * quoted = 0;
if (* args == '"') {
quoted = args;
for (;;) {
++ args;
wchar_t ch = * args;
if (ch == '"')
break;
if (ch == 0)
return 0;
}
}
/*
* Split at the next space.
*/
for (;;) {
wchar_t ch = * args;
if (ch == ' ')
break;
if (ch == 0)
return 0;
++ args;
}
* args = 0;
++ args;
/*
* If the arguments start with quotes, strip the quotes (this isn't a
* completely generic thing to do, but it fits our purposes).
*/
if (quoted) {
wchar_t * from = quoted;
wchar_t ch;
while ((ch = * ++ quoted) != '"')
* from ++ = ch;
while (ch != 0) {
ch = * ++ quoted;
* from ++ = ch;
}
* from = ch;
}
/*
* If there are additional spaces, consume them.
*/
while (* args == ' ')
++ args;
return args;
}
/**
* If we're asked to probe for an NTTP port, then sometimes we have to deal
* with local proxies.
*
* In this case, we actually try and read from the socket to at least get the
* server's initial hello. For the annoying Avast! proxy, that at least does
* not get sent until the real target responds to the proxy, and if the proxy
* connection doesn't work (after 5-6 seconds, since it tries the TLS version
* of the port even if we connected plain-text) then it spits a 400 out.
*/
int checkNntp (SOCKET s) {
char buf [128];
int result;
result = recv (s, buf, sizeof (buf), 0);
if (result < 5)
return 1;
/*
* Various tedious socket-isms can apply, such as the bytes for the
* initial response code trickling in over time. Let's not worry
* about that, just deal with the basics.
*/
void * end = memchr (buf, ' ', result);
if (end == 0)
return 1;
return memcmp (buf, "400", 3) == 0 ? 1 : 0;
}
/**
* If we're asked to probe for an HTTP port, then we need to avoid problems
* with local proxies.
*
* Unlike NNTP, the HTTP protocol is client-driven; as it turns out the way the
* crappy Avast! proxy works is that it'll unilaterally close the connection if
* it can't reach the real intended target, but in order to have this work for
* real targets it pays to request a resource. The safest thing to ask for seems
* to be favicon.ico - it's something lots of browsers request anyway and it's
* almost always a small image, so we shouldn't clog up logs with requests for
* 404 resources or get elaborate 404 response pages back.
*
* It turns out that the Avast! proxy has some other exciting misbehaviours; it
* will sometimes (but not always) when a connection fails return an "HTTP/1.1
* 200 OK" status with some fixed bogus fields, one of which is a "Refresh: 1;"
* to re-fetch the target URL.
*/
int checkHttp (SOCKET s, HANDLE show) {
static char head [] = "HEAD /favicon.ico HTTP/1.0\n\n";
int result;
int length = strlen (head);
result = send (s, head, length, 0);
if (result < length)
return 1;
char buf [1024];
result = recv (s, buf, sizeof (buf) - 1, 0);
/*
* Show the HTTP response, for debugging. I'll keep this in as long as
* it doesn't cost me any compile-time space. I started out aiming to
* keep this around 4kb, and now that the traceroute code is in the
* aim is to keep it below 8kb.
*/
if (result > 0 && show > 0) {
unsigned long written = 0;
WriteFile (show, buf, result, & written, 0);
}
/*
* Normally we wouldn't care what the actual response text was, but to
* deal with the fake response sometimes returned from Avast! I have to
* recognize and suppress it.
*/
if (result > 0) {
buf [result] = 0;
if (strstr (buf, "\nRefresh: 1;") != 0)
return 1;
}
return result < 5 ? 1 : 0;
}
/**
* Probe for the indicated port at the given host.
*/
int probe (wchar_t * host, wchar_t * port, HANDLE show) {
/*
* Detect the presence of the Avast! virus scanner; it includes a set
* of proxy-type firewalls that are somewhat tedious to deal with, and
* in the case of NNTP mean that NNTP connections go through their
* proxy; so, our connect will succeed (being locally looped back) and
* send us nothing while the proxy module slowly decides whether it can
* or can't connect to the real target over TLS or plain-text NNTP.
*
* So, if Avast! is present we can choose to either try and read from
* the socket once it connects (so we can get the response code, which
* will generally be 400 once the Avast proxy fails), or we can forget
* the whole probing process because that introduces too much delay.
*/
HMODULE avast = GetModuleHandle (L"snxhk.dll");
SOCKET s;
s = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (s == SOCKET_ERROR)
return 2;
sockaddr_in any;
any.sin_family = AF_INET;
any.sin_port = 0;
any.sin_addr.S_un.S_addr = INADDR_ANY;
if (bind (s, (sockaddr *) & any, sizeof (any)) != 0)
return 2;
/*
* Look up the hostname and convert the port number into numeric form,
* all handily in one function.
*/
ADDRINFOW * address;
if (GetAddrInfoW (host, port, 0, & address) != 0)
return 2;
/*
* Ensure that we only connect via IPv4, having made an IPv4 socket
* already (yes, I could do things in a different order, but for my
* purposes here with Steam I care about IPv4 only for now since they
* are IPv4-only).
*/
while (address->ai_addr->sa_family != AF_INET)
if ((address = address->ai_next) == 0)
return 2;
/*
* Just test whether the port is open or not.
*/
int result;
result = connect (s, address->ai_addr, address->ai_addrlen) ? 1 : 0;
/*
* Decide whether to actually wait for data, if we're dealing with the
* Avast! proxy being present on a system.
*/
sockaddr_in * addr = (sockaddr_in *) address->ai_addr;
switch (htons (addr->sin_port)) {
case 119:
if (avast && result == 0)
result = checkNntp (s);
break;
case 80:
if (avast && result == 0)
result = checkHttp (s, show);
break;
default:
break;
}
return result;
}
#include <iphlpapi.h>
#include <icmpapi.h>
#include "../steamfilter/glob.h"
/*
* As an alternative to probing for a host, do a traceroute and permit glob
* matches against the hostnames.
*
* In principle one could just script a traceroute, but that's a bit slow and
* rather than writing a regex against the output it seems better to have a
* more direct match available.
*/
int trace (wchar_t * host, wchar_t * pattern, HANDLE err) {
HANDLE icmp = IcmpCreateFile ();
if (icmp == INVALID_HANDLE_VALUE)
return 2;
/*
* Resolve an IPv4 hostname.
*/
ADDRINFOW * address;
if (GetAddrInfoW (host, 0, 0, & address) != 0)
return 2;
/*
* Ensure that we only connect via IPv4, having made an IPv4 socket
* already (yes, I could do things in a different order, but for my
* purposes here with Steam I care about IPv4 only for now since they
* are IPv4-only).
*/
while (address->ai_addr->sa_family != AF_INET)
if ((address = address->ai_next) == 0)
return 2;
sockaddr_in * addr = (sockaddr_in *) address->ai_addr;
IPAddr dest = addr->sin_addr.s_addr;
/*
* The timeouts in this loop are tighter than they are in general kinds
* of traceroute applications since we are generally probing for things
* near to the origin system and with latencies in the <50ms bracket.
*
* We'll also only use a relatively short TTL for the echo requests as
* we're matching the first host with a DNS name. Also, some ISPs block
* ICMP echo on their Steam servers (e.g. TelstraClear, who also keep
* port 80 firewalled) so there's no point searching too hard since the
* route will stall after only 2 or so hops.
*/
unsigned short ttl = 1;
for (; ttl < 8 ; ++ ttl) {
unsigned char buf [128];
/*
* Part the first; send an echo request.
*/
IP_OPTION_INFORMATION info = { ttl };
DWORD echo;
echo = IcmpSendEcho (icmp, dest, 0, 0, & info, buf,
sizeof (buf), 50);
if (echo < 1) {
/*
* Allow one retry, "just in case".
*/
echo = IcmpSendEcho (icmp, dest, 0, 0, & info, buf,
sizeof (buf), 50);
if (echo < 1)
continue;
}
/*
* We expect to see IP_TTL_EXPIRED_TRANSIT since we set the TTL
* to find the intermediate systems.
*/
ICMP_ECHO_REPLY * reply = (ICMP_ECHO_REPLY *) buf;
if (reply->Status != IP_TTL_EXPIRED_TRANSIT && reply->Status != 0)
return 1;
/*
* Part the second; protocol-independent reverse name lookup.
*/
sockaddr_in find = { AF_INET };
find.sin_addr.s_addr = reply->Address;
find.sin_port = 0;
char name [128];
char port [20];
unsigned long error;
error = getnameinfo ((SOCKADDR *) & find, sizeof (find),
name, ARRAY_LENGTH (name),
0, 0, NI_NAMEREQD);
if (error != 0)
continue;
/*
* If we're given a handle to write to, print the name we found.
*/
unsigned long written = 0;
WriteFile (err, name, strlen (name), & written, 0);
WriteFile (err, "\r\n", 2, & written, 0);
/*
* If the status is 0, then we've hit the target host and that
* means we should stop and return 1.
*/
if (reply->Status == 0 || reply->Address == dest)
break;
/*
* If the pattern is empty, we're just printing results.
*/
if (pattern == 0 || * pattern == 0)
continue;
/*
* We have a name, now we can glob-match it. If we see the
* desired pattern, we win. If we don't, we bail; the first
* name we resolve wins.
*/
return globMatch (name, pattern) ? 0 : 1;
}
return 1;
}
/**
* This is intended as a "naked" WinMain without the Visual C++ run-time
* at all (not just avoiding the broken locale machinery).
*/
int CALLBACK myWinMain (void) {
HANDLE err = GetStdHandle (STD_ERROR_HANDLE);
unsigned long written = 0;
/*
* Since we're not using the regular C machinery, get and split the
* command line by hand. The CommandLineToArgvW () routine would do the
* normal conversion to C style for us, but that depends on SHELL32.DLL
* and we shouldn't need it.
*/
wchar_t * base = GetCommandLineW ();
wchar_t * name = split (base);
wchar_t * port = split (name);
wchar_t * extra = split (port);
if (port == 0)
return 2;
WSADATA wsaData;
if (WSAStartup (MAKEWORD (2, 2), & wsaData) != 0)
return 2;
int result;
if (wcscmp (port, L"icmp") == 0) {
wchar_t * find = extra;
extra = split (find);
if (find == 0 || * find == 0) {
/*
* If there is no third argument, just print the names
* of the first few systems we find.
*/
find = 0;
} else if (extra == 0)
err = INVALID_HANDLE_VALUE;
result = trace (name, find, err);
} else {
if (extra == 0)
err = INVALID_HANDLE_VALUE;
result = probe (name, port, err);
}
if (extra == 0)
ExitProcess (result);
static const char text [] = "Probe result: ";
WriteFile (err, text, strlen (text), & written, 0);
char buf [2] = { '0' + result };
WriteFile (err, buf, 1, & written, 0);
ExitProcess (result);
}
<|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/gtk/content_blocked_bubble_gtk.h"
#include "app/l10n_util.h"
#include "base/i18n/rtl.h"
#include "chrome/browser/blocked_popup_container.h"
#include "chrome/browser/content_setting_bubble_model.h"
#include "chrome/browser/gtk/gtk_chrome_link_button.h"
#include "chrome/browser/gtk/gtk_theme_provider.h"
#include "chrome/browser/gtk/gtk_util.h"
#include "chrome/browser/gtk/options/content_settings_window_gtk.h"
#include "chrome/browser/host_content_settings_map.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/content_settings.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/notification_type.h"
#include "gfx/gtk_util.h"
#include "grit/app_resources.h"
#include "grit/generated_resources.h"
// Padding between content and edge of info bubble.
static const int kContentBorder = 7;
ContentSettingBubbleGtk::ContentSettingBubbleGtk(
GtkWindow* toplevel_window,
const gfx::Rect& bounds,
InfoBubbleGtkDelegate* delegate,
ContentSettingBubbleModel* content_setting_bubble_model,
Profile* profile,
TabContents* tab_contents)
: toplevel_window_(toplevel_window),
bounds_(bounds),
profile_(profile),
tab_contents_(tab_contents),
delegate_(delegate),
content_setting_bubble_model_(content_setting_bubble_model),
info_bubble_(NULL) {
registrar_.Add(this, NotificationType::TAB_CONTENTS_DESTROYED,
Source<TabContents>(tab_contents));
BuildBubble();
}
ContentSettingBubbleGtk::~ContentSettingBubbleGtk() {
}
void ContentSettingBubbleGtk::Close() {
if (info_bubble_)
info_bubble_->Close();
}
void ContentSettingBubbleGtk::InfoBubbleClosing(InfoBubbleGtk* info_bubble,
bool closed_by_escape) {
delegate_->InfoBubbleClosing(info_bubble, closed_by_escape);
delete this;
}
void ContentSettingBubbleGtk::Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
DCHECK(type == NotificationType::TAB_CONTENTS_DESTROYED);
DCHECK(source == Source<TabContents>(tab_contents_));
tab_contents_ = NULL;
}
void ContentSettingBubbleGtk::BuildBubble() {
GtkThemeProvider* theme_provider = GtkThemeProvider::GetFrom(profile_);
GtkWidget* bubble_content = gtk_vbox_new(FALSE, gtk_util::kControlSpacing);
gtk_container_set_border_width(GTK_CONTAINER(bubble_content), kContentBorder);
const ContentSettingBubbleModel::BubbleContent& content =
content_setting_bubble_model_->bubble_content();
if (!content.title.empty()) {
// Add the content label.
GtkWidget* label = gtk_label_new(content.title.c_str());
gtk_box_pack_start(GTK_BOX(bubble_content), label, FALSE, FALSE, 0);
}
if (content_setting_bubble_model_->content_type() ==
CONTENT_SETTINGS_TYPE_POPUPS) {
const std::vector<ContentSettingBubbleModel::PopupItem>& popup_items =
content.popup_items;
GtkWidget* table = gtk_table_new(popup_items.size(), 2, FALSE);
int row = 0;
for (std::vector<ContentSettingBubbleModel::PopupItem>::const_iterator
i(popup_items.begin()); i != popup_items.end(); ++i, ++row) {
GtkWidget* image = gtk_image_new();
if (!i->bitmap.empty()) {
GdkPixbuf* icon_pixbuf = gfx::GdkPixbufFromSkBitmap(&i->bitmap);
gtk_image_set_from_pixbuf(GTK_IMAGE(image), icon_pixbuf);
g_object_unref(icon_pixbuf);
// We stuff the image in an event box so we can trap mouse clicks on the
// image (and launch the popup).
GtkWidget* event_box = gtk_event_box_new();
gtk_container_add(GTK_CONTAINER(event_box), image);
popup_icons_[event_box] = i -popup_items.begin();
g_signal_connect(event_box, "button_press_event",
G_CALLBACK(OnPopupIconButtonPress), this);
gtk_table_attach(GTK_TABLE(table), event_box, 0, 1, row, row + 1,
GTK_FILL, GTK_FILL, gtk_util::kControlSpacing / 2,
gtk_util::kControlSpacing / 2);
}
GtkWidget* button = gtk_chrome_link_button_new(i->title.c_str());
popup_links_[button] = i -popup_items.begin();
g_signal_connect(button, "clicked", G_CALLBACK(OnPopupLinkClicked),
this);
gtk_table_attach(GTK_TABLE(table), button, 1, 2, row, row + 1,
GTK_FILL, GTK_FILL, gtk_util::kControlSpacing / 2,
gtk_util::kControlSpacing / 2);
}
gtk_box_pack_start(GTK_BOX(bubble_content), table, FALSE, FALSE, 0);
}
if (content_setting_bubble_model_->content_type() !=
CONTENT_SETTINGS_TYPE_COOKIES) {
const ContentSettingBubbleModel::RadioGroups& radio_groups =
content.radio_groups;
for (ContentSettingBubbleModel::RadioGroups::const_iterator i =
radio_groups.begin(); i != radio_groups.end(); ++i) {
const ContentSettingBubbleModel::RadioItems& radio_items = i->radio_items;
RadioGroupGtk radio_group_gtk;
for (ContentSettingBubbleModel::RadioItems::const_iterator j =
radio_items.begin(); j != radio_items.end(); ++j) {
GtkWidget* radio =
radio_group_gtk.empty() ?
gtk_radio_button_new_with_label(NULL, j->c_str()) :
gtk_radio_button_new_with_label_from_widget(
GTK_RADIO_BUTTON(radio_group_gtk[0]),
j->c_str());
gtk_box_pack_start(GTK_BOX(bubble_content), radio, FALSE, FALSE, 0);
if (j - radio_items.begin() == i->default_item) {
// We must set the default value before we attach the signal handlers
// or pain occurs.
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(radio), TRUE);
}
radio_group_gtk.push_back(radio);
}
for (std::vector<GtkWidget*>::const_iterator j = radio_group_gtk.begin();
j != radio_group_gtk.end(); ++j) {
g_signal_connect(*j, "toggled", G_CALLBACK(OnRadioToggled), this);
}
radio_groups_gtk_.push_back(radio_group_gtk);
gtk_box_pack_start(GTK_BOX(bubble_content), gtk_hseparator_new(), FALSE,
FALSE, 0);
}
}
for (std::vector<ContentSettingBubbleModel::DomainList>::const_iterator i =
content.domain_lists.begin();
i != content.domain_lists.end(); ++i) {
// Put each list into its own vbox to allow spacing between lists.
GtkWidget* list_content = gtk_vbox_new(FALSE, gtk_util::kControlSpacing);
GtkWidget* label = gtk_label_new(i->title.c_str());
gtk_label_set_line_wrap(GTK_LABEL(label), TRUE);
GtkWidget* label_box = gtk_hbox_new(FALSE, 0);
gtk_box_pack_start(GTK_BOX(label_box), label, FALSE, FALSE, 0);
gtk_box_pack_start(GTK_BOX(list_content), label_box, FALSE, FALSE, 0);
for (std::set<std::string>::const_iterator j = i->hosts.begin();
j != i->hosts.end(); ++j) {
gtk_box_pack_start(GTK_BOX(list_content),
gtk_util::IndentWidget(gtk_util::CreateBoldLabel(*j)),
FALSE, FALSE, 0);
}
gtk_box_pack_start(GTK_BOX(bubble_content), list_content, FALSE, FALSE,
gtk_util::kControlSpacing);
}
if (!content.clear_link.empty()) {
GtkWidget* clear_link_box = gtk_hbox_new(FALSE, 0);
GtkWidget* clear_link = gtk_chrome_link_button_new(
content.clear_link.c_str());
g_signal_connect(clear_link, "clicked", G_CALLBACK(OnClearLinkClicked),
this);
gtk_box_pack_start(GTK_BOX(clear_link_box), clear_link, FALSE, FALSE, 0);
gtk_box_pack_start(GTK_BOX(bubble_content), clear_link_box,
FALSE, FALSE, 0);
gtk_box_pack_start(GTK_BOX(bubble_content), gtk_hseparator_new(),
FALSE, FALSE, 0);
}
GtkWidget* bottom_box = gtk_hbox_new(FALSE, 0);
GtkWidget* manage_link =
gtk_chrome_link_button_new(content.manage_link.c_str());
g_signal_connect(manage_link, "clicked", G_CALLBACK(OnManageLinkClicked),
this);
gtk_box_pack_start(GTK_BOX(bottom_box), manage_link, FALSE, FALSE, 0);
GtkWidget* button = gtk_button_new_with_label(
l10n_util::GetStringUTF8(IDS_DONE).c_str());
g_signal_connect(button, "clicked", G_CALLBACK(OnCloseButtonClicked), this);
gtk_box_pack_end(GTK_BOX(bottom_box), button, FALSE, FALSE, 0);
gtk_box_pack_start(GTK_BOX(bubble_content), bottom_box, FALSE, FALSE, 0);
gtk_widget_grab_focus(bottom_box);
gtk_widget_grab_focus(button);
InfoBubbleGtk::ArrowLocationGtk arrow_location =
!base::i18n::IsRTL() ?
InfoBubbleGtk::ARROW_LOCATION_TOP_RIGHT :
InfoBubbleGtk::ARROW_LOCATION_TOP_LEFT;
info_bubble_ = InfoBubbleGtk::Show(
toplevel_window_,
bounds_,
bubble_content,
arrow_location,
true, // match_system_theme
true, // grab_input
theme_provider,
this);
}
// static
void ContentSettingBubbleGtk::OnPopupIconButtonPress(
GtkWidget* icon_event_box,
GdkEventButton* event,
ContentSettingBubbleGtk* bubble) {
PopupMap::iterator i(bubble->popup_icons_.find(icon_event_box));
DCHECK(i != bubble->popup_icons_.end());
bubble->content_setting_bubble_model_->OnPopupClicked(i->second);
// The views interface implicitly closes because of the launching of a new
// window; we need to do that explicitly.
bubble->Close();
}
// static
void ContentSettingBubbleGtk::OnPopupLinkClicked(
GtkWidget* button,
ContentSettingBubbleGtk* bubble) {
PopupMap::iterator i(bubble->popup_links_.find(button));
DCHECK(i != bubble->popup_links_.end());
bubble->content_setting_bubble_model_->OnPopupClicked(i->second);
// The views interface implicitly closes because of the launching of a new
// window; we need to do that explicitly.
bubble->Close();
}
// static
void ContentSettingBubbleGtk::OnRadioToggled(
GtkWidget* widget,
ContentSettingBubbleGtk* bubble) {
for (std::vector<RadioGroupGtk>::const_iterator i =
bubble->radio_groups_gtk_.begin();
i != bubble->radio_groups_gtk_.end(); ++i) {
for (RadioGroupGtk::const_iterator j = i->begin(); j != i->end(); j++) {
if (widget == *j) {
bubble->content_setting_bubble_model_->OnRadioClicked(
i - bubble->radio_groups_gtk_.begin(),
j - i->begin());
return;
}
}
}
NOTREACHED() << "unknown radio toggled";
}
// static
void ContentSettingBubbleGtk::OnCloseButtonClicked(
GtkButton *button,
ContentSettingBubbleGtk* bubble) {
bubble->Close();
}
// static
void ContentSettingBubbleGtk::OnManageLinkClicked(
GtkButton* button,
ContentSettingBubbleGtk* bubble) {
bubble->content_setting_bubble_model_->OnManageLinkClicked();
bubble->Close();
}
void ContentSettingBubbleGtk::OnClearLinkClicked(
GtkButton* button,
ContentSettingBubbleGtk* bubble) {
bubble->content_setting_bubble_model_->OnClearLinkClicked();
bubble->Close();
}
<commit_msg>GTK: Left justify label in content blocking bubble.<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/gtk/content_blocked_bubble_gtk.h"
#include "app/l10n_util.h"
#include "base/i18n/rtl.h"
#include "chrome/browser/blocked_popup_container.h"
#include "chrome/browser/content_setting_bubble_model.h"
#include "chrome/browser/gtk/gtk_chrome_link_button.h"
#include "chrome/browser/gtk/gtk_theme_provider.h"
#include "chrome/browser/gtk/gtk_util.h"
#include "chrome/browser/gtk/options/content_settings_window_gtk.h"
#include "chrome/browser/host_content_settings_map.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/content_settings.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/notification_type.h"
#include "gfx/gtk_util.h"
#include "grit/app_resources.h"
#include "grit/generated_resources.h"
// Padding between content and edge of info bubble.
static const int kContentBorder = 7;
ContentSettingBubbleGtk::ContentSettingBubbleGtk(
GtkWindow* toplevel_window,
const gfx::Rect& bounds,
InfoBubbleGtkDelegate* delegate,
ContentSettingBubbleModel* content_setting_bubble_model,
Profile* profile,
TabContents* tab_contents)
: toplevel_window_(toplevel_window),
bounds_(bounds),
profile_(profile),
tab_contents_(tab_contents),
delegate_(delegate),
content_setting_bubble_model_(content_setting_bubble_model),
info_bubble_(NULL) {
registrar_.Add(this, NotificationType::TAB_CONTENTS_DESTROYED,
Source<TabContents>(tab_contents));
BuildBubble();
}
ContentSettingBubbleGtk::~ContentSettingBubbleGtk() {
}
void ContentSettingBubbleGtk::Close() {
if (info_bubble_)
info_bubble_->Close();
}
void ContentSettingBubbleGtk::InfoBubbleClosing(InfoBubbleGtk* info_bubble,
bool closed_by_escape) {
delegate_->InfoBubbleClosing(info_bubble, closed_by_escape);
delete this;
}
void ContentSettingBubbleGtk::Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
DCHECK(type == NotificationType::TAB_CONTENTS_DESTROYED);
DCHECK(source == Source<TabContents>(tab_contents_));
tab_contents_ = NULL;
}
void ContentSettingBubbleGtk::BuildBubble() {
GtkThemeProvider* theme_provider = GtkThemeProvider::GetFrom(profile_);
GtkWidget* bubble_content = gtk_vbox_new(FALSE, gtk_util::kControlSpacing);
gtk_container_set_border_width(GTK_CONTAINER(bubble_content), kContentBorder);
const ContentSettingBubbleModel::BubbleContent& content =
content_setting_bubble_model_->bubble_content();
if (!content.title.empty()) {
// Add the content label.
GtkWidget* label = gtk_label_new(content.title.c_str());
gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5);
gtk_box_pack_start(GTK_BOX(bubble_content), label, FALSE, FALSE, 0);
}
if (content_setting_bubble_model_->content_type() ==
CONTENT_SETTINGS_TYPE_POPUPS) {
const std::vector<ContentSettingBubbleModel::PopupItem>& popup_items =
content.popup_items;
GtkWidget* table = gtk_table_new(popup_items.size(), 2, FALSE);
int row = 0;
for (std::vector<ContentSettingBubbleModel::PopupItem>::const_iterator
i(popup_items.begin()); i != popup_items.end(); ++i, ++row) {
GtkWidget* image = gtk_image_new();
if (!i->bitmap.empty()) {
GdkPixbuf* icon_pixbuf = gfx::GdkPixbufFromSkBitmap(&i->bitmap);
gtk_image_set_from_pixbuf(GTK_IMAGE(image), icon_pixbuf);
g_object_unref(icon_pixbuf);
// We stuff the image in an event box so we can trap mouse clicks on the
// image (and launch the popup).
GtkWidget* event_box = gtk_event_box_new();
gtk_container_add(GTK_CONTAINER(event_box), image);
popup_icons_[event_box] = i -popup_items.begin();
g_signal_connect(event_box, "button_press_event",
G_CALLBACK(OnPopupIconButtonPress), this);
gtk_table_attach(GTK_TABLE(table), event_box, 0, 1, row, row + 1,
GTK_FILL, GTK_FILL, gtk_util::kControlSpacing / 2,
gtk_util::kControlSpacing / 2);
}
GtkWidget* button = gtk_chrome_link_button_new(i->title.c_str());
popup_links_[button] = i -popup_items.begin();
g_signal_connect(button, "clicked", G_CALLBACK(OnPopupLinkClicked),
this);
gtk_table_attach(GTK_TABLE(table), button, 1, 2, row, row + 1,
GTK_FILL, GTK_FILL, gtk_util::kControlSpacing / 2,
gtk_util::kControlSpacing / 2);
}
gtk_box_pack_start(GTK_BOX(bubble_content), table, FALSE, FALSE, 0);
}
if (content_setting_bubble_model_->content_type() !=
CONTENT_SETTINGS_TYPE_COOKIES) {
const ContentSettingBubbleModel::RadioGroups& radio_groups =
content.radio_groups;
for (ContentSettingBubbleModel::RadioGroups::const_iterator i =
radio_groups.begin(); i != radio_groups.end(); ++i) {
const ContentSettingBubbleModel::RadioItems& radio_items = i->radio_items;
RadioGroupGtk radio_group_gtk;
for (ContentSettingBubbleModel::RadioItems::const_iterator j =
radio_items.begin(); j != radio_items.end(); ++j) {
GtkWidget* radio =
radio_group_gtk.empty() ?
gtk_radio_button_new_with_label(NULL, j->c_str()) :
gtk_radio_button_new_with_label_from_widget(
GTK_RADIO_BUTTON(radio_group_gtk[0]),
j->c_str());
gtk_box_pack_start(GTK_BOX(bubble_content), radio, FALSE, FALSE, 0);
if (j - radio_items.begin() == i->default_item) {
// We must set the default value before we attach the signal handlers
// or pain occurs.
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(radio), TRUE);
}
radio_group_gtk.push_back(radio);
}
for (std::vector<GtkWidget*>::const_iterator j = radio_group_gtk.begin();
j != radio_group_gtk.end(); ++j) {
g_signal_connect(*j, "toggled", G_CALLBACK(OnRadioToggled), this);
}
radio_groups_gtk_.push_back(radio_group_gtk);
gtk_box_pack_start(GTK_BOX(bubble_content), gtk_hseparator_new(), FALSE,
FALSE, 0);
}
}
for (std::vector<ContentSettingBubbleModel::DomainList>::const_iterator i =
content.domain_lists.begin();
i != content.domain_lists.end(); ++i) {
// Put each list into its own vbox to allow spacing between lists.
GtkWidget* list_content = gtk_vbox_new(FALSE, gtk_util::kControlSpacing);
GtkWidget* label = gtk_label_new(i->title.c_str());
gtk_label_set_line_wrap(GTK_LABEL(label), TRUE);
GtkWidget* label_box = gtk_hbox_new(FALSE, 0);
gtk_box_pack_start(GTK_BOX(label_box), label, FALSE, FALSE, 0);
gtk_box_pack_start(GTK_BOX(list_content), label_box, FALSE, FALSE, 0);
for (std::set<std::string>::const_iterator j = i->hosts.begin();
j != i->hosts.end(); ++j) {
gtk_box_pack_start(GTK_BOX(list_content),
gtk_util::IndentWidget(gtk_util::CreateBoldLabel(*j)),
FALSE, FALSE, 0);
}
gtk_box_pack_start(GTK_BOX(bubble_content), list_content, FALSE, FALSE,
gtk_util::kControlSpacing);
}
if (!content.clear_link.empty()) {
GtkWidget* clear_link_box = gtk_hbox_new(FALSE, 0);
GtkWidget* clear_link = gtk_chrome_link_button_new(
content.clear_link.c_str());
g_signal_connect(clear_link, "clicked", G_CALLBACK(OnClearLinkClicked),
this);
gtk_box_pack_start(GTK_BOX(clear_link_box), clear_link, FALSE, FALSE, 0);
gtk_box_pack_start(GTK_BOX(bubble_content), clear_link_box,
FALSE, FALSE, 0);
gtk_box_pack_start(GTK_BOX(bubble_content), gtk_hseparator_new(),
FALSE, FALSE, 0);
}
GtkWidget* bottom_box = gtk_hbox_new(FALSE, 0);
GtkWidget* manage_link =
gtk_chrome_link_button_new(content.manage_link.c_str());
g_signal_connect(manage_link, "clicked", G_CALLBACK(OnManageLinkClicked),
this);
gtk_box_pack_start(GTK_BOX(bottom_box), manage_link, FALSE, FALSE, 0);
GtkWidget* button = gtk_button_new_with_label(
l10n_util::GetStringUTF8(IDS_DONE).c_str());
g_signal_connect(button, "clicked", G_CALLBACK(OnCloseButtonClicked), this);
gtk_box_pack_end(GTK_BOX(bottom_box), button, FALSE, FALSE, 0);
gtk_box_pack_start(GTK_BOX(bubble_content), bottom_box, FALSE, FALSE, 0);
gtk_widget_grab_focus(bottom_box);
gtk_widget_grab_focus(button);
InfoBubbleGtk::ArrowLocationGtk arrow_location =
!base::i18n::IsRTL() ?
InfoBubbleGtk::ARROW_LOCATION_TOP_RIGHT :
InfoBubbleGtk::ARROW_LOCATION_TOP_LEFT;
info_bubble_ = InfoBubbleGtk::Show(
toplevel_window_,
bounds_,
bubble_content,
arrow_location,
true, // match_system_theme
true, // grab_input
theme_provider,
this);
}
// static
void ContentSettingBubbleGtk::OnPopupIconButtonPress(
GtkWidget* icon_event_box,
GdkEventButton* event,
ContentSettingBubbleGtk* bubble) {
PopupMap::iterator i(bubble->popup_icons_.find(icon_event_box));
DCHECK(i != bubble->popup_icons_.end());
bubble->content_setting_bubble_model_->OnPopupClicked(i->second);
// The views interface implicitly closes because of the launching of a new
// window; we need to do that explicitly.
bubble->Close();
}
// static
void ContentSettingBubbleGtk::OnPopupLinkClicked(
GtkWidget* button,
ContentSettingBubbleGtk* bubble) {
PopupMap::iterator i(bubble->popup_links_.find(button));
DCHECK(i != bubble->popup_links_.end());
bubble->content_setting_bubble_model_->OnPopupClicked(i->second);
// The views interface implicitly closes because of the launching of a new
// window; we need to do that explicitly.
bubble->Close();
}
// static
void ContentSettingBubbleGtk::OnRadioToggled(
GtkWidget* widget,
ContentSettingBubbleGtk* bubble) {
for (std::vector<RadioGroupGtk>::const_iterator i =
bubble->radio_groups_gtk_.begin();
i != bubble->radio_groups_gtk_.end(); ++i) {
for (RadioGroupGtk::const_iterator j = i->begin(); j != i->end(); j++) {
if (widget == *j) {
bubble->content_setting_bubble_model_->OnRadioClicked(
i - bubble->radio_groups_gtk_.begin(),
j - i->begin());
return;
}
}
}
NOTREACHED() << "unknown radio toggled";
}
// static
void ContentSettingBubbleGtk::OnCloseButtonClicked(
GtkButton *button,
ContentSettingBubbleGtk* bubble) {
bubble->Close();
}
// static
void ContentSettingBubbleGtk::OnManageLinkClicked(
GtkButton* button,
ContentSettingBubbleGtk* bubble) {
bubble->content_setting_bubble_model_->OnManageLinkClicked();
bubble->Close();
}
void ContentSettingBubbleGtk::OnClearLinkClicked(
GtkButton* button,
ContentSettingBubbleGtk* bubble) {
bubble->content_setting_bubble_model_->OnClearLinkClicked();
bubble->Close();
}
<|endoftext|> |
<commit_before>// Copyright (c) 2011-2018 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <qt/transactiondescdialog.h>
#include <qt/forms/ui_transactiondescdialog.h>
#include <qt/transactiontablemodel.h>
#include <QModelIndex>
TransactionDescDialog::TransactionDescDialog(const QModelIndex &idx, QWidget *parent) :
QDialog(parent),
ui(new Ui::TransactionDescDialog)
{
ui->setupUi(this);
setWindowTitle(tr("Details for %1").arg(idx.data(TransactionTableModel::TxHashRole).toString()));
QString desc = idx.data(TransactionTableModel::LongDescriptionRole).toString();
ui->detailText->setHtml(desc);
}
TransactionDescDialog::~TransactionDescDialog()
{
delete ui;
}
<commit_msg>Port transaction description dialog<commit_after>// Copyright (c) 2011-2018 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <qt/transactiondescdialog.h>
#include <qt/forms/ui_transactiondescdialog.h>
#include <qt/transactiontablemodel.h>
#include <qt/styleSheet.h>
#include <QModelIndex>
TransactionDescDialog::TransactionDescDialog(const QModelIndex &idx, QWidget *parent) :
QDialog(parent),
ui(new Ui::TransactionDescDialog)
{
ui->setupUi(this);
// Set stylesheet
SetObjectStyleSheet(this, StyleSheetNames::ScrollBarDark);
setWindowTitle(tr("Details for %1").arg(idx.data(TransactionTableModel::TxHashRole).toString()));
QString desc = idx.data(TransactionTableModel::LongDescriptionRole).toString();
ui->detailText->setHtml(desc);
}
TransactionDescDialog::~TransactionDescDialog()
{
delete ui;
}
<|endoftext|> |
<commit_before>/*
* moneyServerClient2.cpp
*
* Created on: 20. 7. 2017
* Author: ondra
*/
#include "moneyServerClient2.h"
#include <couchit/minihttp/buffered.h>
#include <imtjson/object.h>
#include "../common/runtime_error.h"
#include "error.h"
#include "logfile.h"
#include "orderBudget.h"
namespace quark {
MoneyServerClient2::MoneyServerClient2(PMoneySvcSupport support,
String addr, String signature, String asset, String currency, String firstTradeId, bool logTrafic)
:support(support)
,addr(addr)
,signature(signature)
,asset(asset)
,currency(currency)
,firstTradeId(firstTradeId)
,client(new MyClient(addr,*this))
,inited(false)
{
client->enableLogTrafic(logTrafic);
}
MoneyServerClient2::~MoneyServerClient2() {
client->close();
}
void MoneyServerClient2::adjustBudget(json::Value ,
OrderBudget& ) {
//emoty
}
template<typename Fn>
void MoneyServerClient2::callWithRetry(RefCntPtr<MyClient> client,PMoneySvcSupport supp, String methodName, Value params, Fn callback) {
(*client)(methodName, params) >>
[=](RpcResult res) {
if (res.isError()) {
if (res.defined()) {
handleError(client,methodName,res);
}
if (!client->isClosed()) {
supp->dispatch([=]{callWithRetry(client,supp,methodName,params,callback);});
} else {
callback(res);
}
} else {
callback(res);
}
};
}
bool MoneyServerClient2::allocBudget(json::Value user, OrderBudget total,
Callback callback) {
connectIfNeed();
RefCntPtr<MyClient> c(client);
Value params = Object
("user_id",user)
("currency",total.currency)
("asset",total.asset)
("marginLong",total.marginLong)
("marginShort",total.marginShort)
("posLong",total.posLong)
("posShort",total.posShort);
(*client)("CurrencyBalance.block_money", params)
>> [c,callback](const RpcResult &res) {
if (res.isError()) {
if (res.defined())
handleError(c,"CurrencyBalance.block_money", res);
callback(allocTryAgain);
} else {
if (Value(res)["success"].getBool()) {
callback(allocOk);
} else {
callback(allocReject);
}
}
};
return false;
}
void MoneyServerClient2::reportTrade(Value prevTrade, const TradeData& data) {
connectIfNeed();
reportTrade2(prevTrade, data);
}
void MoneyServerClient2::reportTrade2(Value prevTrade, const TradeData& data) {
RefCntPtr<MyClient> c(client);
(*c)("CurrencyBalance.trade", Object("trade_id",data.id)
("prev_trade_id", prevTrade)
("timestamp",data.timestamp)
("asset",data.size)
("currency",data.price)
("buyer",Object("user_id",data.buyer.userId)
("context",data.buyer.context))
("seller",Object("user_id",data.seller.userId)
("context",data.seller.context))
("taker",data.dir == OrderDir::buy?"buyer":"seller"))
>> [c](const RpcResult &res){
if (res.isError()) {
handleError(c, "CurrencyBalance.trade", res);
}
};
lastReportedTrade = data.id;
}
MoneyServerClient2::MyClient::MyClient(String addr,
MoneyServerClient2& owner):owner(owner),closed(false) {
}
void MoneyServerClient2::MyClient::onInit() {
owner.onInit();
}
void MoneyServerClient2::MyClient::onNotify(const Notify& ntf) {
owner.onNotify(ntf);
}
void MoneyServerClient2::onInit() {
//empty
}
void MoneyServerClient2::onNotify(const Notify& ntf) {
//empty
}
class MoneyServerClient2::ResyncStream: public ITradeStream {
public:
MoneyServerClient2 &owner;
ResyncStream(MoneyServerClient2 &owner):owner(owner) {}
virtual void reportTrade(Value prevTrade, const TradeData &data) {
owner.reportTrade2(prevTrade, data);
}
};
void MoneyServerClient2::connectIfNeed() {
if (!client->isConnected()) {
if (client->connect(addr)) {
RpcResult initres = (*client)("CurrencyBalance.init", Object
("signature",signature)
("asset",asset)
("currency",currency));
if (initres.isError()) {
if (initres.defined()) {
handleError(client,"CurrencyBalance.init", initres);
}
} else {
Value r(initres);
Value lastSyncId = r["last_trade_id"];
Value version = r["version"];
if (lastSyncId.getString() == "" && firstTradeId != "") {
lastSyncId = firstTradeId;
}
logInfo({"Initialized RPC client, version, lastId", version, lastSyncId});
ResyncStream resyncStream(*this);
support->resync(resyncStream, lastSyncId, lastReportedTrade);
}
} else {
//failed connect
//nothing here - commands send to disconnected client are rejected through callback
}
}
}
void MoneyServerClient2::handleError(MyClient *c, StrViewA method, const RpcResult& res)
{
logError({method, "Money server error, dropping connection", c->getAddr(), Value(res)});
c->disconnect(false);
}
}
<commit_msg>error during sync -> unhandled exception<commit_after>/*
* moneyServerClient2.cpp
*
* Created on: 20. 7. 2017
* Author: ondra
*/
#include "moneyServerClient2.h"
#include <couchit/minihttp/buffered.h>
#include <imtjson/object.h>
#include "../common/runtime_error.h"
#include "error.h"
#include "logfile.h"
#include "orderBudget.h"
namespace quark {
MoneyServerClient2::MoneyServerClient2(PMoneySvcSupport support,
String addr, String signature, String asset, String currency, String firstTradeId, bool logTrafic)
:support(support)
,addr(addr)
,signature(signature)
,asset(asset)
,currency(currency)
,firstTradeId(firstTradeId)
,client(new MyClient(addr,*this))
,inited(false)
{
client->enableLogTrafic(logTrafic);
}
MoneyServerClient2::~MoneyServerClient2() {
client->close();
}
void MoneyServerClient2::adjustBudget(json::Value ,
OrderBudget& ) {
//emoty
}
template<typename Fn>
void MoneyServerClient2::callWithRetry(RefCntPtr<MyClient> client,PMoneySvcSupport supp, String methodName, Value params, Fn callback) {
(*client)(methodName, params) >>
[=](RpcResult res) {
if (res.isError()) {
if (res.defined()) {
handleError(client,methodName,res);
}
if (!client->isClosed()) {
supp->dispatch([=]{callWithRetry(client,supp,methodName,params,callback);});
} else {
callback(res);
}
} else {
callback(res);
}
};
}
bool MoneyServerClient2::allocBudget(json::Value user, OrderBudget total,
Callback callback) {
connectIfNeed();
RefCntPtr<MyClient> c(client);
Value params = Object
("user_id",user)
("currency",total.currency)
("asset",total.asset)
("marginLong",total.marginLong)
("marginShort",total.marginShort)
("posLong",total.posLong)
("posShort",total.posShort);
(*client)("CurrencyBalance.block_money", params)
>> [c,callback](const RpcResult &res) {
if (res.isError()) {
if (res.defined())
handleError(c,"CurrencyBalance.block_money", res);
callback(allocTryAgain);
} else {
if (Value(res)["success"].getBool()) {
callback(allocOk);
} else {
callback(allocReject);
}
}
};
return false;
}
void MoneyServerClient2::reportTrade(Value prevTrade, const TradeData& data) {
connectIfNeed();
reportTrade2(prevTrade, data);
}
void MoneyServerClient2::reportTrade2(Value prevTrade, const TradeData& data) {
RefCntPtr<MyClient> c(client);
(*c)("CurrencyBalance.trade", Object("trade_id",data.id)
("prev_trade_id", prevTrade)
("timestamp",data.timestamp)
("asset",data.size)
("currency",data.price)
("buyer",Object("user_id",data.buyer.userId)
("context",data.buyer.context))
("seller",Object("user_id",data.seller.userId)
("context",data.seller.context))
("taker",data.dir == OrderDir::buy?"buyer":"seller"))
>> [c](const RpcResult &res){
if (res.isError()) {
handleError(c, "CurrencyBalance.trade", res);
}
};
lastReportedTrade = data.id;
}
MoneyServerClient2::MyClient::MyClient(String addr,
MoneyServerClient2& owner):owner(owner),closed(false) {
}
void MoneyServerClient2::MyClient::onInit() {
owner.onInit();
}
void MoneyServerClient2::MyClient::onNotify(const Notify& ntf) {
owner.onNotify(ntf);
}
void MoneyServerClient2::onInit() {
//empty
}
void MoneyServerClient2::onNotify(const Notify& ntf) {
//empty
}
class MoneyServerClient2::ResyncStream: public ITradeStream {
public:
MoneyServerClient2 &owner;
ResyncStream(MoneyServerClient2 &owner):owner(owner) {}
virtual void reportTrade(Value prevTrade, const TradeData &data) {
owner.reportTrade2(prevTrade, data);
}
};
void MoneyServerClient2::connectIfNeed() {
if (!client->isConnected()) {
if (client->connect(addr)) {
RpcResult initres = (*client)("CurrencyBalance.init", Object
("signature",signature)
("asset",asset)
("currency",currency));
if (initres.isError()) {
if (initres.defined()) {
handleError(client,"CurrencyBalance.init", initres);
}
} else {
Value r(initres);
Value lastSyncId = r["last_trade_id"];
Value version = r["version"];
if (lastSyncId.getString() == "" && firstTradeId != "") {
lastSyncId = firstTradeId;
}
logInfo({"Initialized RPC client, version, lastId", version, lastSyncId});
try {
ResyncStream resyncStream(*this);
support->resync(resyncStream, lastSyncId, lastReportedTrade);
} catch (...) {
unhandledException();
}
}
} else {
//failed connect
//nothing here - commands send to disconnected client are rejected through callback
}
}
}
void MoneyServerClient2::handleError(MyClient *c, StrViewA method, const RpcResult& res)
{
logError({method, "Money server error, dropping connection", c->getAddr(), Value(res)});
c->disconnect(false);
}
}
<|endoftext|> |
<commit_before>#include "audio/playback.h"
namespace loftili {
namespace audio {
void Playback::Start() {
if(m_state == PLAYBACK_STATE_PLAYING) return;
spdlog::get(LOFTILI_SPDLOG_ID)->info("playback starting, opening playback thread");
m_state = PLAYBACK_STATE_PLAYING;
m_stateclient.Update("playback", 1);
m_thread = std::unique_ptr<std::thread>(new std::thread(std::bind(&Playback::Run, this)));
}
void Playback::Skip() {
Stop();
m_queue.Pop();
Start();
}
void Playback::Stop() {
spdlog::get(LOFTILI_SPDLOG_ID)->info("stopping player and playback run thread");
m_state = PLAYBACK_STATE_STOPPED;
m_player.Stop();
m_thread->join();
}
void Playback::Run() {
m_state = PLAYBACK_STATE_PLAYING;
while(m_queue >> m_player && m_state == PLAYBACK_STATE_PLAYING) {
spdlog::get(LOFTILI_SPDLOG_ID)->info("player finished, getting next track from queue");
}
spdlog::get(LOFTILI_SPDLOG_ID)->info("playback run thread finishing");
m_state = PLAYBACK_STATE_STOPPED;
m_stateclient.Update("playback", 0);
}
}
}
<commit_msg>[LFTCE-36] checking that device state playing before attempting to stop in playback skip<commit_after>#include "audio/playback.h"
namespace loftili {
namespace audio {
void Playback::Start() {
if(m_state == PLAYBACK_STATE_PLAYING) return;
spdlog::get(LOFTILI_SPDLOG_ID)->info("playback starting, opening playback thread");
m_state = PLAYBACK_STATE_PLAYING;
m_stateclient.Update("playback", 1);
m_thread = std::unique_ptr<std::thread>(new std::thread(std::bind(&Playback::Run, this)));
}
void Playback::Skip() {
if(m_state == PLAYBACK_STATE_PLAYING) Stop();
m_queue.Pop();
Start();
}
void Playback::Stop() {
spdlog::get(LOFTILI_SPDLOG_ID)->info("stopping player and playback run thread");
m_state = PLAYBACK_STATE_STOPPED;
m_player.Stop();
m_thread->join();
}
void Playback::Run() {
m_state = PLAYBACK_STATE_PLAYING;
while(m_queue >> m_player && m_state == PLAYBACK_STATE_PLAYING) {
spdlog::get(LOFTILI_SPDLOG_ID)->info("player finished, getting next track from queue");
}
spdlog::get(LOFTILI_SPDLOG_ID)->info("playback run thread finishing");
m_state = PLAYBACK_STATE_STOPPED;
m_stateclient.Update("playback", 0);
}
}
}
<|endoftext|> |
<commit_before>/*******************************************************************************
* c7a/core/stage_builder.hpp
*
* Part of Project c7a.
*
*
* This file has no license. Only Chuck Norris can compile it.
******************************************************************************/
#pragma once
#ifndef C7A_CORE_STAGE_BUILDER_HEADER
#define C7A_CORE_STAGE_BUILDER_HEADER
#include <c7a/api/dia_base.hpp>
#include <c7a/common/logger.hpp>
#include <algorithm>
#include <set>
#include <stack>
#include <string>
#include <utility>
#include <vector>
namespace c7a {
namespace core {
using c7a::api::DIABase;
class Stage
{
public:
explicit Stage(DIABase* node) : node_(node) {
LOG << "CREATING stage" << node_->ToString() << "node" << node_;
}
void Execute() {
LOG << "EXECUTING stage " << node_->ToString() << "node" << node_;
node_->Execute();
node_->UnregisterChilds();
node_->set_state(c7a::api::EXECUTED);
}
void PushData() {
LOG << "PUSHING stage " << node_->ToString() << "node" << node_;
node_->PushData();
}
void Dispose() {
LOG << "DISPOSING stage " << node_->ToString() << "node" << node_;
node_->Dispose();
node_->set_state(c7a::api::DISPOSED);
}
DIABase * node() {
return node_;
}
private:
static const bool debug = false;
DIABase* node_;
};
class StageBuilder
{
public:
void FindStages(DIABase* action, std::vector<Stage>& stages_result) {
LOG << "FINDING stages:";
// std::set<const DIABase*> stages_found;
std::vector<DIABase*> stages_found;
// Do a reverse DFS and find all stages
std::stack<DIABase*> dia_stack;
dia_stack.push(action);
// stages_found.insert(action);
stages_found.push_back(action);
while (!dia_stack.empty()) {
DIABase* curr = dia_stack.top();
dia_stack.pop();
const auto parents = curr->parents();
for (size_t i = 0; i < parents.size(); ++i) {
auto p = parents[i].get();
stages_found.push_back(p);
if (p->state() != c7a::api::EXECUTED) {
dia_stack.push(p);
}
}
}
for (auto stage : stages_found) {
stages_result.emplace_back(stage);
}
std::reverse(stages_result.begin(), stages_result.end());
}
void RunScope(DIABase* action) {
std::vector<Stage> result;
FindStages(action, result);
for (auto s : result)
{
// TODO(sl): This is nonsense -tb, fix it:
if (s.node()->state() == c7a::api::EXECUTED) s.Execute();
if (s.node()->state() == c7a::api::EXECUTED) s.PushData();
}
}
static const bool debug = false;
};
} // namespace core
} // namespace c7a
#endif // !C7A_CORE_STAGE_BUILDER_HEADER
/******************************************************************************/
<commit_msg>Fixed all except Zip.<commit_after>/*******************************************************************************
* c7a/core/stage_builder.hpp
*
* Part of Project c7a.
*
*
* This file has no license. Only Chuck Norris can compile it.
******************************************************************************/
#pragma once
#ifndef C7A_CORE_STAGE_BUILDER_HEADER
#define C7A_CORE_STAGE_BUILDER_HEADER
#include <c7a/api/dia_base.hpp>
#include <c7a/common/logger.hpp>
#include <algorithm>
#include <set>
#include <stack>
#include <string>
#include <utility>
#include <vector>
namespace c7a {
namespace core {
using c7a::api::DIABase;
class Stage
{
public:
explicit Stage(DIABase* node) : node_(node) {
LOG << "CREATING stage" << node_->ToString() << "node" << node_;
}
void Execute() {
LOG << "EXECUTING stage " << node_->ToString() << "node" << node_;
node_->Execute();
node_->PushData();
node_->UnregisterChilds();
node_->set_state(c7a::api::EXECUTED);
}
void PushData() {
LOG << "PUSHING stage " << node_->ToString() << "node" << node_;
node_->PushData();
}
void Dispose() {
LOG << "DISPOSING stage " << node_->ToString() << "node" << node_;
node_->Dispose();
node_->set_state(c7a::api::DISPOSED);
}
DIABase * node() {
return node_;
}
private:
static const bool debug = false;
DIABase* node_;
};
class StageBuilder
{
public:
void FindStages(DIABase* action, std::vector<Stage>& stages_result) {
LOG << "FINDING stages:";
// std::set<const DIABase*> stages_found;
std::vector<DIABase*> stages_found;
// Do a reverse DFS and find all stages
std::stack<DIABase*> dia_stack;
dia_stack.push(action);
// stages_found.insert(action);
stages_found.push_back(action);
while (!dia_stack.empty()) {
DIABase* curr = dia_stack.top();
dia_stack.pop();
const auto parents = curr->parents();
for (size_t i = 0; i < parents.size(); ++i) {
auto p = parents[i].get();
stages_found.push_back(p);
if (p->state() != c7a::api::EXECUTED) {
dia_stack.push(p);
}
}
}
for (auto stage : stages_found) {
stages_result.emplace_back(stage);
}
std::reverse(stages_result.begin(), stages_result.end());
}
void RunScope(DIABase* action) {
std::vector<Stage> result;
FindStages(action, result);
for (auto s : result)
{
// TODO(sl): This is nonsense -tb, fix it:
if (s.node()->state() == c7a::api::EXECUTED) s.PushData();
if (s.node()->state() == c7a::api::NEW) s.Execute();
}
}
static const bool debug = false;
};
} // namespace core
} // namespace c7a
#endif // !C7A_CORE_STAGE_BUILDER_HEADER
/******************************************************************************/
<|endoftext|> |
<commit_before>//
// libavg - Media Playback Engine.
// Copyright (C) 2003-2011 Ulrich von Zadow
//
// 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 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// Current versions can be found at www.libavg.de
//
#include "Exception.h"
#include "Backtrace.h"
#include "Logger.h"
#include "OSHelper.h"
#include <cstdlib>
#include <sstream>
using namespace std;
namespace avg {
Exception::Exception(int code, const string& sErr)
: std::exception(),
m_Code (code),
m_sErr (sErr)
{
}
Exception::Exception(const Exception& ex)
: std::exception(),
m_Code (ex.getCode()),
m_sErr (ex.getStr())
{
}
Exception::~Exception() throw()
{
}
int Exception::getCode() const
{
return m_Code;
}
const string& Exception::getStr() const
{
return m_sErr;
}
const char* Exception::what() const throw()
{
return m_sErr.c_str();
}
void fatalError(const string& sMsg, int type)
{
AVG_LOG_ERROR("Internal error: "+sMsg+" Aborting.");
throw(Exception(type, sMsg));
}
void debugBreak()
{
#ifdef _WIN32
__asm int 3;
#else
__builtin_trap();
#endif
}
void avgAssert(bool b, const char * pszFile, int line, const char * pszReason)
{
if (!b) {
string sDummy;
static bool bBreak = getEnv("AVG_BREAK_ON_ASSERT", sDummy);
if (bBreak) {
debugBreak();
} else {
stringstream ss;
ss << "Assertion failed in " << pszFile << ": " << line << endl;
if (pszReason) {
ss << "Reason: " << pszReason << endl;
}
dumpBacktrace();
throw(Exception(AVG_ERR_ASSERT_FAILED, ss.str()));
}
}
}
}
<commit_msg>Replaced __asm with __debugbreak, work on #384<commit_after>//
// libavg - Media Playback Engine.
// Copyright (C) 2003-2011 Ulrich von Zadow
//
// 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 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// Current versions can be found at www.libavg.de
//
#include "Exception.h"
#include "Backtrace.h"
#include "Logger.h"
#include "OSHelper.h"
#include <cstdlib>
#include <sstream>
#ifdef WIN32
#include <intrin.h>
#endif
using namespace std;
namespace avg {
Exception::Exception(int code, const string& sErr)
: std::exception(),
m_Code (code),
m_sErr (sErr)
{
}
Exception::Exception(const Exception& ex)
: std::exception(),
m_Code (ex.getCode()),
m_sErr (ex.getStr())
{
}
Exception::~Exception() throw()
{
}
int Exception::getCode() const
{
return m_Code;
}
const string& Exception::getStr() const
{
return m_sErr;
}
const char* Exception::what() const throw()
{
return m_sErr.c_str();
}
void fatalError(const string& sMsg, int type)
{
AVG_LOG_ERROR("Internal error: "+sMsg+" Aborting.");
throw(Exception(type, sMsg));
}
void debugBreak()
{
#ifdef _WIN32
__debugbreak();
#else
__builtin_trap();
#endif
}
void avgAssert(bool b, const char * pszFile, int line, const char * pszReason)
{
if (!b) {
string sDummy;
static bool bBreak = getEnv("AVG_BREAK_ON_ASSERT", sDummy);
if (bBreak) {
debugBreak();
} else {
stringstream ss;
ss << "Assertion failed in " << pszFile << ": " << line << endl;
if (pszReason) {
ss << "Reason: " << pszReason << endl;
}
dumpBacktrace();
throw(Exception(AVG_ERR_ASSERT_FAILED, ss.str()));
}
}
}
}
<|endoftext|> |
<commit_before>#ifndef AMGCL_SOLVERS_CG_HPP
#define AMGCL_SOLVERS_CG_HPP
/*
The MIT License
Copyright (c) 2012-2015 Denis Demidov <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
/**
* \file amgcl/solver/cg.hpp
* \author Denis Demidov <[email protected]>
* \brief Conjugate Gradient method.
*/
#include <boost/tuple/tuple.hpp>
#include <amgcl/backend/interface.hpp>
#include <amgcl/solver/detail/default_inner_product.hpp>
#include <amgcl/util.hpp>
namespace amgcl {
/// Iterative solvers
namespace solver {
/**
* \defgroup solvers
* \brief Iterative solvers
*
* AMGCL provides several iterative solvers, but it should be easy to use it as
* a preconditioner with a user-provided solver. Each solver in AMGCL is a
* class template. Its single template parameter specifies the backend to use.
* This allows to preallocate necessary resources at class construction.
* Obviously, the solver backend has to coincide with the AMG backend.
*/
/// Conjugate Gradients iterative solver.
/**
* \param Backend Backend for temporary structures allocation.
* \ingroup solvers
* \sa \cite Barrett1994
*/
template <
class Backend,
class InnerProduct = detail::default_inner_product
>
class cg {
public:
typedef Backend backend_type;
typedef typename Backend::vector vector;
typedef typename Backend::value_type value_type;
typedef typename Backend::params backend_params;
typedef typename math::scalar_of<value_type>::type scalar_type;
typedef typename math::inner_product_impl<
typename math::rhs_of<value_type>::type
>::return_type coef_type;
/// Solver parameters.
struct params {
/// Maximum number of iterations.
size_t maxiter;
/// Target residual error.
scalar_type tol;
params(size_t maxiter = 100, scalar_type tol = 1e-8)
: maxiter(maxiter), tol(tol)
{}
params(const boost::property_tree::ptree &p)
: AMGCL_PARAMS_IMPORT_VALUE(p, maxiter),
AMGCL_PARAMS_IMPORT_VALUE(p, tol)
{}
void get(boost::property_tree::ptree &p, const std::string &path) const {
AMGCL_PARAMS_EXPORT_VALUE(p, path, maxiter);
AMGCL_PARAMS_EXPORT_VALUE(p, path, tol);
}
};
/// Preallocates necessary data structures
/**
* \param n The system size.
* \param prm Solver parameters.
* \param backend_prm Backend parameters.
*/
cg(
size_t n,
const params &prm = params(),
const backend_params &backend_prm = backend_params(),
const InnerProduct &inner_product = InnerProduct()
) : prm(prm), n(n),
r(Backend::create_vector(n, backend_prm)),
s(Backend::create_vector(n, backend_prm)),
p(Backend::create_vector(n, backend_prm)),
q(Backend::create_vector(n, backend_prm)),
inner_product(inner_product)
{ }
/// Solves the linear system for the given system matrix.
/**
* \param A System matrix.
* \param P Preconditioner.
* \param rhs Right-hand side.
* \param x Solution vector.
*
* The system matrix may differ from the matrix used for the AMG
* preconditioner construction. This may be used for the solution of
* non-stationary problems with slowly changing coefficients. There is
* a strong chance that AMG built for one time step will act as a
* reasonably good preconditioner for several subsequent time steps
* \cite Demidov2012.
*/
template <class Matrix, class Precond, class Vec1, class Vec2>
boost::tuple<size_t, scalar_type> operator()(
Matrix const &A,
Precond const &P,
Vec1 const &rhs,
#ifdef BOOST_NO_CXX11_RVALUE_REFERENCES
Vec2 &x
#else
Vec2 &&x
#endif
) const
{
static const coef_type one = math::identity<coef_type>();
static const coef_type zero = math::zero<coef_type>();
backend::residual(rhs, A, x, *r);
scalar_type norm_rhs = norm(rhs);
if (norm_rhs < amgcl::detail::eps<scalar_type>(n)) {
backend::clear(x);
return boost::make_tuple(0, norm_rhs);
}
scalar_type eps = prm.tol * norm_rhs;
scalar_type eps2 = eps * eps;
coef_type rho1 = 2 * eps2 * one;
coef_type rho2 = zero;
scalar_type res_norm = norm(*r);
size_t iter = 0;
for(; iter < prm.maxiter && math::norm(rho1) > eps2; ++iter) {
P.apply(*r, *s);
rho2 = rho1;
rho1 = inner_product(*r, *s);
if (iter)
backend::axpby(one, *s, rho1 / rho2, *p);
else
backend::copy(*s, *p);
backend::spmv(one, A, *p, zero, *q);
coef_type alpha = rho1 / inner_product(*q, *p);
backend::axpby( alpha, *p, one, x);
backend::axpby(-alpha, *q, one, *r);
}
backend::residual(rhs, A, x, *r);
res_norm = norm(*r);
return boost::make_tuple(iter, res_norm / norm_rhs);
}
/// Solves the linear system for the same matrix that was used for the AMG preconditioner construction.
/**
* \param P AMG preconditioner.
* \param rhs Right-hand side.
* \param x Solution vector.
*/
template <class Precond, class Vec1, class Vec2>
boost::tuple<size_t, scalar_type> operator()(
Precond const &P,
Vec1 const &rhs,
#ifdef BOOST_NO_CXX11_RVALUE_REFERENCES
Vec2 &x
#else
Vec2 &&x
#endif
) const
{
return (*this)(P.system_matrix(), P, rhs, x);
}
public:
params prm;
private:
size_t n;
boost::shared_ptr<vector> r;
boost::shared_ptr<vector> s;
boost::shared_ptr<vector> p;
boost::shared_ptr<vector> q;
InnerProduct inner_product;
template <class Vec>
scalar_type norm(const Vec &x) const {
return sqrt(math::norm(inner_product(x, x)));
}
};
} // namespace solver
} // namespace amgcl
#endif
<commit_msg>More robust exit condition in solver::cg<commit_after>#ifndef AMGCL_SOLVERS_CG_HPP
#define AMGCL_SOLVERS_CG_HPP
/*
The MIT License
Copyright (c) 2012-2015 Denis Demidov <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
/**
* \file amgcl/solver/cg.hpp
* \author Denis Demidov <[email protected]>
* \brief Conjugate Gradient method.
*/
#include <boost/tuple/tuple.hpp>
#include <amgcl/backend/interface.hpp>
#include <amgcl/solver/detail/default_inner_product.hpp>
#include <amgcl/util.hpp>
namespace amgcl {
/// Iterative solvers
namespace solver {
/**
* \defgroup solvers
* \brief Iterative solvers
*
* AMGCL provides several iterative solvers, but it should be easy to use it as
* a preconditioner with a user-provided solver. Each solver in AMGCL is a
* class template. Its single template parameter specifies the backend to use.
* This allows to preallocate necessary resources at class construction.
* Obviously, the solver backend has to coincide with the AMG backend.
*/
/// Conjugate Gradients iterative solver.
/**
* \param Backend Backend for temporary structures allocation.
* \ingroup solvers
* \sa \cite Barrett1994
*/
template <
class Backend,
class InnerProduct = detail::default_inner_product
>
class cg {
public:
typedef Backend backend_type;
typedef typename Backend::vector vector;
typedef typename Backend::value_type value_type;
typedef typename Backend::params backend_params;
typedef typename math::scalar_of<value_type>::type scalar_type;
typedef typename math::inner_product_impl<
typename math::rhs_of<value_type>::type
>::return_type coef_type;
/// Solver parameters.
struct params {
/// Maximum number of iterations.
size_t maxiter;
/// Target residual error.
scalar_type tol;
params(size_t maxiter = 100, scalar_type tol = 1e-8)
: maxiter(maxiter), tol(tol)
{}
params(const boost::property_tree::ptree &p)
: AMGCL_PARAMS_IMPORT_VALUE(p, maxiter),
AMGCL_PARAMS_IMPORT_VALUE(p, tol)
{}
void get(boost::property_tree::ptree &p, const std::string &path) const {
AMGCL_PARAMS_EXPORT_VALUE(p, path, maxiter);
AMGCL_PARAMS_EXPORT_VALUE(p, path, tol);
}
};
/// Preallocates necessary data structures
/**
* \param n The system size.
* \param prm Solver parameters.
* \param backend_prm Backend parameters.
*/
cg(
size_t n,
const params &prm = params(),
const backend_params &backend_prm = backend_params(),
const InnerProduct &inner_product = InnerProduct()
) : prm(prm), n(n),
r(Backend::create_vector(n, backend_prm)),
s(Backend::create_vector(n, backend_prm)),
p(Backend::create_vector(n, backend_prm)),
q(Backend::create_vector(n, backend_prm)),
inner_product(inner_product)
{ }
/// Solves the linear system for the given system matrix.
/**
* \param A System matrix.
* \param P Preconditioner.
* \param rhs Right-hand side.
* \param x Solution vector.
*
* The system matrix may differ from the matrix used for the AMG
* preconditioner construction. This may be used for the solution of
* non-stationary problems with slowly changing coefficients. There is
* a strong chance that AMG built for one time step will act as a
* reasonably good preconditioner for several subsequent time steps
* \cite Demidov2012.
*/
template <class Matrix, class Precond, class Vec1, class Vec2>
boost::tuple<size_t, scalar_type> operator()(
Matrix const &A,
Precond const &P,
Vec1 const &rhs,
#ifdef BOOST_NO_CXX11_RVALUE_REFERENCES
Vec2 &x
#else
Vec2 &&x
#endif
) const
{
static const coef_type one = math::identity<coef_type>();
static const coef_type zero = math::zero<coef_type>();
backend::residual(rhs, A, x, *r);
scalar_type norm_rhs = norm(rhs);
if (norm_rhs < amgcl::detail::eps<scalar_type>(n)) {
backend::clear(x);
return boost::make_tuple(0, norm_rhs);
}
scalar_type eps = prm.tol * norm_rhs;
scalar_type eps2 = eps * eps;
coef_type rho1 = 2 * eps2 * one;
coef_type rho2 = zero;
scalar_type res_norm = norm(*r);
size_t iter = 0;
for(; iter < prm.maxiter && math::norm(res_norm) > eps2; ++iter) {
P.apply(*r, *s);
rho2 = rho1;
rho1 = inner_product(*r, *s);
if (iter)
backend::axpby(one, *s, rho1 / rho2, *p);
else
backend::copy(*s, *p);
backend::spmv(one, A, *p, zero, *q);
coef_type alpha = rho1 / inner_product(*q, *p);
backend::axpby( alpha, *p, one, x);
backend::axpby(-alpha, *q, one, *r);
res_norm = norm(*r);
}
backend::residual(rhs, A, x, *r);
res_norm = norm(*r);
return boost::make_tuple(iter, res_norm / norm_rhs);
}
/// Solves the linear system for the same matrix that was used for the AMG preconditioner construction.
/**
* \param P AMG preconditioner.
* \param rhs Right-hand side.
* \param x Solution vector.
*/
template <class Precond, class Vec1, class Vec2>
boost::tuple<size_t, scalar_type> operator()(
Precond const &P,
Vec1 const &rhs,
#ifdef BOOST_NO_CXX11_RVALUE_REFERENCES
Vec2 &x
#else
Vec2 &&x
#endif
) const
{
return (*this)(P.system_matrix(), P, rhs, x);
}
public:
params prm;
private:
size_t n;
boost::shared_ptr<vector> r;
boost::shared_ptr<vector> s;
boost::shared_ptr<vector> p;
boost::shared_ptr<vector> q;
InnerProduct inner_product;
template <class Vec>
scalar_type norm(const Vec &x) const {
return sqrt(math::norm(inner_product(x, x)));
}
};
} // namespace solver
} // namespace amgcl
#endif
<|endoftext|> |
<commit_before>/*
* This file is part of the IAN project - https://github.com/Meoo/IAN
*
* 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/.
*/
#include "ClusterConnection.hpp"
#include "ClusterInternal.hpp"
#include <common/EasyProfiler.hpp>
#include <proto-in/ClusterHandshake_generated.h>
#include <boost/asio/bind_executor.hpp>
#include <boost/asio/read.hpp>
#include <boost/beast/core/flat_buffer.hpp>
#include <boost/endian/conversion.hpp>
namespace asio = boost::asio;
#define LOG_SOCKET_TUPLE \
socket_.remote_endpoint().address().to_string(), socket_.remote_endpoint().port()
namespace
{
const size_t read_chunk_size = 16 * 1024; // 16k
bool is_connection_reset_error(const boost::system::error_code & ec)
{
if (ec.category() == asio::error::get_system_category() &&
(ec == asio::error::connection_aborted || ec == asio::error::connection_reset))
{
return true;
}
if (ec.category() == asio::ssl::error::get_stream_category() &&
ec == asio::ssl::error::stream_truncated)
{
return true;
}
return false;
}
bool is_connection_canceled_error(const boost::system::error_code & ec)
{
if (ec.category() == asio::error::get_ssl_category() &&
ERR_GET_REASON(ec.value()) == SSL_R_PROTOCOL_IS_SHUTDOWN)
{
return true;
}
return false;
}
} // namespace
ClusterConnection::ClusterConnection(const std::shared_ptr<spdlog::logger> & logger,
TcpSocket && socket)
: logger_(logger), stream_(std::move(socket), cluster::internal::get_ssl()),
socket_(stream_.next_layer()), strand_(socket_.get_io_context()),
timer_(socket_.get_io_context())
{
}
ClusterConnection::~ClusterConnection()
{
// Close must be called last or using LOG_SOCKET_TUPLE will throw
boost::system::error_code ec;
socket_.close(ec);
}
void ClusterConnection::run(SslRole role, bool safe_link)
{
safe_link_ = safe_link;
// Force peer verification
boost::system::error_code ec;
stream_.set_verify_mode(asio::ssl::verify_peer | asio::ssl::verify_fail_if_no_peer_cert, ec);
if (ec)
IAN_ERROR(logger_, "Failed to force peer verification for cluster connection: : {}:{} : {}",
LOG_SOCKET_TUPLE, ec.message());
// SSL handshake
stream_.async_handshake(
role == Client ? asio::ssl::stream_base::client : asio::ssl::stream_base::server,
asio::bind_executor(strand_, std::bind(&ClusterConnection::on_ssl_handshake,
shared_from_this(), std::placeholders::_1)));
}
void ClusterConnection::abort()
{
if (dropped_)
return;
boost::system::error_code ec;
// Ignore errors
timer_.cancel(ec);
// TODO state_timer_.cancel(ec);
// TODO message_queue_.clear();
IAN_INFO(logger_, "Peer disconnected: {}:{}", LOG_SOCKET_TUPLE);
// Abort stream at socket level
socket_.shutdown(socket_.shutdown_both, ec);
dropped_ = true;
}
void ClusterConnection::shutdown()
{
if (dropped_ || shutting_down_)
return;
boost::system::error_code ec;
// Ignore errors
timer_.cancel(ec);
// TODO state_timer_.cancel(ec);
// TODO message_queue_.clear();
if (!socket_.is_open())
return;
// Shutdown stream at SSL level
stream_.async_shutdown(
asio::bind_executor(strand_, std::bind(&ClusterConnection::on_shutdown, shared_from_this(),
std::placeholders::_1)));
shutting_down_ = true;
}
void ClusterConnection::on_shutdown(boost::system::error_code ec)
{
if (dropped_)
return;
if (ec)
{
if (!is_connection_reset_error(ec) && !is_connection_canceled_error(ec))
IAN_WARN(logger_, "Shutdown error for peer: {}:{} : {} {}", LOG_SOCKET_TUPLE, ec.message(),
ec.value());
}
IAN_INFO(logger_, "Peer disconnected: {}:{}", LOG_SOCKET_TUPLE);
// Abort stream at socket level
socket_.shutdown(socket_.shutdown_both, ec);
dropped_ = true;
}
void ClusterConnection::on_ssl_handshake(boost::system::error_code ec)
{
if (dropped_)
return;
if (ec)
{
IAN_WARN(logger_, "SSL handshake failed for peer: {}:{} : {} {}", LOG_SOCKET_TUPLE,
ec.message(), ec.value());
this->abort();
return;
}
IAN_TRACE(logger_, "SSL handshake complete for peer: {}:{}", LOG_SOCKET_TUPLE);
// Read IAN handshake
stream_.async_read_some(
read_buffer_.prepare(read_chunk_size),
asio::bind_executor(strand_,
std::bind(&ClusterConnection::on_ian_handshake, shared_from_this(),
std::placeholders::_1, std::placeholders::_2)));
}
void ClusterConnection::on_ian_handshake(boost::system::error_code ec, std::size_t readlen)
{
if (ec)
{
handle_read_error(ec);
return;
}
read_buffer_.commit(readlen);
if (message_len_ == -1U)
{
// Read handshake length
if (read_buffer_.size() < sizeof(message_len_))
{
// If first packet contains less than 4 bytes something is really wrong
IAN_ERROR(logger_, "Not enough data to read handshake length : {}:{} : {}", LOG_SOCKET_TUPLE,
read_buffer_.size());
shutdown();
return;
}
// Extract message length (little endian)
read_buffer_.consume(asio::buffer_copy(
asio::buffer((void *)&message_len_, sizeof(message_len_)), read_buffer_.data()));
boost::endian::little_to_native_inplace(message_len_);
}
if (read_buffer_.size() < message_len_)
{
IAN_DEBUG(logger_, "Not enough data to parse handshake : {}:{} : {} < {}", LOG_SOCKET_TUPLE,
read_buffer_.size(), message_len_);
// Not enough data (somehow), read again
stream_.async_read_some(
read_buffer_.prepare(read_chunk_size),
asio::bind_executor(strand_,
std::bind(&ClusterConnection::on_ian_handshake, shared_from_this(),
std::placeholders::_1, std::placeholders::_2)));
return;
}
// Flatten
boost::beast::flat_buffer buf;
buf.commit(asio::buffer_copy(buf.prepare(read_buffer_.size()), read_buffer_.data()));
// Verify handshake
if (!proto::VerifyClusterHandshakeBuffer(
flatbuffers::Verifier((const uint8_t *)buf.data().data(), buf.size())))
{
IAN_ERROR(logger_, "Cluster handshake verification failed : {}:{}", LOG_SOCKET_TUPLE);
shutdown();
return;
}
const proto::ClusterHandshake * handshake = proto::GetClusterHandshake(buf.data().data());
auto major = handshake->version_major();
auto minor = handshake->version_minor();
IAN_DEBUG(logger_, "Proto version for peer : {}:{} : {}.{}", LOG_SOCKET_TUPLE, major, minor);
safe_link_ = safe_link_ && handshake->safe_link();
if (safe_link_)
{
// TODO Downgrade to clear messages
}
else
{
// TODO Start reading messages over SSL
}
}
void ClusterConnection::handle_read_error(boost::system::error_code ec)
{
if (dropped_)
return;
if (is_connection_reset_error(ec))
{
this->abort();
return;
}
if (is_connection_canceled_error(ec))
return;
IAN_WARN(logger_, "Read failed for peer: {}:{} : {} {}", LOG_SOCKET_TUPLE, ec.message(),
ec.value());
shutdown();
}
void ClusterConnection::handle_write_error(boost::system::error_code ec)
{
if (dropped_)
return;
if (is_connection_reset_error(ec))
{
this->abort();
return;
}
if (is_connection_canceled_error(ec))
return;
IAN_WARN(logger_, "Write failed for peer: {}:{} : {} {}", LOG_SOCKET_TUPLE, ec.message(),
ec.value());
shutdown();
}
<commit_msg>Fix build<commit_after>/*
* This file is part of the IAN project - https://github.com/Meoo/IAN
*
* 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/.
*/
#include "ClusterConnection.hpp"
#include "ClusterInternal.hpp"
#include <common/EasyProfiler.hpp>
#include <proto-in/ClusterHandshake_generated.h>
#include <boost/asio/bind_executor.hpp>
#include <boost/asio/read.hpp>
#include <boost/beast/core/flat_buffer.hpp>
#include <boost/endian/conversion.hpp>
namespace asio = boost::asio;
#define LOG_SOCKET_TUPLE \
socket_.remote_endpoint().address().to_string(), socket_.remote_endpoint().port()
namespace
{
const size_t read_chunk_size = 16 * 1024; // 16k
bool is_connection_reset_error(const boost::system::error_code & ec)
{
if (ec.category() == asio::error::get_system_category() &&
(ec == asio::error::connection_aborted || ec == asio::error::connection_reset))
{
return true;
}
if (ec.category() == asio::ssl::error::get_stream_category() &&
ec == asio::ssl::error::stream_truncated)
{
return true;
}
return false;
}
bool is_connection_canceled_error(const boost::system::error_code & ec)
{
if (ec.category() == asio::error::get_ssl_category() &&
ERR_GET_REASON(ec.value()) == SSL_R_PROTOCOL_IS_SHUTDOWN)
{
return true;
}
return false;
}
} // namespace
ClusterConnection::ClusterConnection(const std::shared_ptr<spdlog::logger> & logger,
TcpSocket && socket)
: logger_(logger), stream_(std::move(socket), cluster::internal::get_ssl()),
socket_(stream_.next_layer()), strand_(socket_.get_io_context()),
timer_(socket_.get_io_context())
{
}
ClusterConnection::~ClusterConnection()
{
// Close must be called last or using LOG_SOCKET_TUPLE will throw
boost::system::error_code ec;
socket_.close(ec);
}
void ClusterConnection::run(SslRole role, bool safe_link)
{
safe_link_ = safe_link;
// Force peer verification
boost::system::error_code ec;
stream_.set_verify_mode(asio::ssl::verify_peer | asio::ssl::verify_fail_if_no_peer_cert, ec);
if (ec)
IAN_ERROR(logger_, "Failed to force peer verification for cluster connection: : {}:{} : {}",
LOG_SOCKET_TUPLE, ec.message());
// SSL handshake
stream_.async_handshake(
role == Client ? asio::ssl::stream_base::client : asio::ssl::stream_base::server,
asio::bind_executor(strand_, std::bind(&ClusterConnection::on_ssl_handshake,
shared_from_this(), std::placeholders::_1)));
}
void ClusterConnection::abort()
{
if (dropped_)
return;
boost::system::error_code ec;
// Ignore errors
timer_.cancel(ec);
// TODO state_timer_.cancel(ec);
// TODO message_queue_.clear();
IAN_INFO(logger_, "Peer disconnected: {}:{}", LOG_SOCKET_TUPLE);
// Abort stream at socket level
socket_.shutdown(socket_.shutdown_both, ec);
dropped_ = true;
}
void ClusterConnection::shutdown()
{
if (dropped_ || shutting_down_)
return;
boost::system::error_code ec;
// Ignore errors
timer_.cancel(ec);
// TODO state_timer_.cancel(ec);
// TODO message_queue_.clear();
if (!socket_.is_open())
return;
// Shutdown stream at SSL level
stream_.async_shutdown(
asio::bind_executor(strand_, std::bind(&ClusterConnection::on_shutdown, shared_from_this(),
std::placeholders::_1)));
shutting_down_ = true;
}
void ClusterConnection::on_shutdown(boost::system::error_code ec)
{
if (dropped_)
return;
if (ec)
{
if (!is_connection_reset_error(ec) && !is_connection_canceled_error(ec))
IAN_WARN(logger_, "Shutdown error for peer: {}:{} : {} {}", LOG_SOCKET_TUPLE, ec.message(),
ec.value());
}
IAN_INFO(logger_, "Peer disconnected: {}:{}", LOG_SOCKET_TUPLE);
// Abort stream at socket level
socket_.shutdown(socket_.shutdown_both, ec);
dropped_ = true;
}
void ClusterConnection::on_ssl_handshake(boost::system::error_code ec)
{
if (dropped_)
return;
if (ec)
{
IAN_WARN(logger_, "SSL handshake failed for peer: {}:{} : {} {}", LOG_SOCKET_TUPLE,
ec.message(), ec.value());
this->abort();
return;
}
IAN_TRACE(logger_, "SSL handshake complete for peer: {}:{}", LOG_SOCKET_TUPLE);
// Read IAN handshake
stream_.async_read_some(
read_buffer_.prepare(read_chunk_size),
asio::bind_executor(strand_,
std::bind(&ClusterConnection::on_ian_handshake, shared_from_this(),
std::placeholders::_1, std::placeholders::_2)));
}
void ClusterConnection::on_ian_handshake(boost::system::error_code ec, std::size_t readlen)
{
if (ec)
{
handle_read_error(ec);
return;
}
read_buffer_.commit(readlen);
if (message_len_ == -1U)
{
// Read handshake length
if (read_buffer_.size() < sizeof(message_len_))
{
// If first packet contains less than 4 bytes something is really wrong
IAN_ERROR(logger_, "Not enough data to read handshake length : {}:{} : {}", LOG_SOCKET_TUPLE,
read_buffer_.size());
shutdown();
return;
}
// Extract message length (little endian)
read_buffer_.consume(asio::buffer_copy(
asio::buffer((void *)&message_len_, sizeof(message_len_)), read_buffer_.data()));
boost::endian::little_to_native_inplace(message_len_);
}
if (read_buffer_.size() < message_len_)
{
IAN_DEBUG(logger_, "Not enough data to parse handshake : {}:{} : {} < {}", LOG_SOCKET_TUPLE,
read_buffer_.size(), message_len_);
// Not enough data (somehow), read again
stream_.async_read_some(
read_buffer_.prepare(read_chunk_size),
asio::bind_executor(strand_,
std::bind(&ClusterConnection::on_ian_handshake, shared_from_this(),
std::placeholders::_1, std::placeholders::_2)));
return;
}
// Flatten
boost::beast::flat_buffer buf;
buf.commit(asio::buffer_copy(buf.prepare(read_buffer_.size()), read_buffer_.data()));
// Verify handshake
{
flatbuffers::Verifier verifier((const uint8_t *)buf.data().data(), buf.size());
if (!proto::VerifyClusterHandshakeBuffer(verifier))
{
IAN_ERROR(logger_, "Cluster handshake verification failed : {}:{}", LOG_SOCKET_TUPLE);
shutdown();
return;
}
}
const proto::ClusterHandshake * handshake = proto::GetClusterHandshake(buf.data().data());
auto major = handshake->version_major();
auto minor = handshake->version_minor();
IAN_DEBUG(logger_, "Proto version for peer : {}:{} : {}.{}", LOG_SOCKET_TUPLE, major, minor);
safe_link_ = safe_link_ && handshake->safe_link();
if (safe_link_)
{
// TODO Downgrade to clear messages
}
else
{
// TODO Start reading messages over SSL
}
}
void ClusterConnection::handle_read_error(boost::system::error_code ec)
{
if (dropped_)
return;
if (is_connection_reset_error(ec))
{
this->abort();
return;
}
if (is_connection_canceled_error(ec))
return;
IAN_WARN(logger_, "Read failed for peer: {}:{} : {} {}", LOG_SOCKET_TUPLE, ec.message(),
ec.value());
shutdown();
}
void ClusterConnection::handle_write_error(boost::system::error_code ec)
{
if (dropped_)
return;
if (is_connection_reset_error(ec))
{
this->abort();
return;
}
if (is_connection_canceled_error(ec))
return;
IAN_WARN(logger_, "Write failed for peer: {}:{} : {} {}", LOG_SOCKET_TUPLE, ec.message(),
ec.value());
shutdown();
}
<|endoftext|> |
<commit_before>#include <product.hpp>
#include "helpers.hpp"
#include <vector>
#include <string>
#include <iterator>
#include "catch.hpp"
using iter::product;
using Vec = const std::vector<int>;
TEST_CASE("product: basic test, two sequences", "[product]") {
using TP = std::tuple<int, char>;
using ResType = std::vector<TP>;
Vec n1 = {0, 1};
const std::string s{"abc"};
auto p = product(n1, s);
ResType v(std::begin(p), std::end(p));
ResType vc = {TP{0,'a'}, TP{0,'b'}, TP{0,'c'},
TP{1,'a'}, TP{1,'b'}, TP{1,'c'}};
REQUIRE( v == vc );
}
TEST_CASE("product: three sequences", "[product]") {
using TP = std::tuple <int, char, int>;
using ResType = const std::vector<TP>;
Vec n1 = {0, 1};
const std::string s{"ab"};
Vec n2 = {2};
auto p = product(n1, s, n2);
ResType v(std::begin(p), std::end(p));
ResType vc = {
TP{0, 'a', 2},
TP{0, 'b', 2},
TP{1, 'a', 2},
TP{1, 'b', 2}
};
REQUIRE( v == vc );
}
TEST_CASE("product: empty when any iterable is empty", "[product]") {
Vec n1 = {0, 1};
Vec n2 = {0, 1, 2};
Vec emp = {};
SECTION("first iterable is empty") {
auto p = product(emp, n1, n2);
REQUIRE( std::begin(p) == std::end(p) );
}
SECTION("middle iterable is empty") {
auto p = product(n1, emp, n2);
REQUIRE( std::begin(p) == std::end(p) );
}
SECTION("last iterable is empty") {
auto p = product(n1, n2, emp);
REQUIRE( std::begin(p) == std::end(p) );
}
}
TEST_CASE("product: single iterable", "[product]") {
const std::string s{"ab"};
using TP = std::tuple<char>;
using ResType = const std::vector<TP>;
auto p = product(s);
ResType v(std::begin(p), std::end(p));
ResType vc = {TP{'a'}, TP{'b'}};
REQUIRE( v == vc );
}
TEST_CASE("product: binds to lvalues and moves rvalues", "[product]") {
itertest::BasicIterable<char> bi{'x', 'y'};
itertest::BasicIterable<int> bi2{0, 1};
SECTION("First ref'd, second moved") {
product(bi, std::move(bi2));
REQUIRE_FALSE( bi.was_moved_from() );
REQUIRE( bi2.was_moved_from() );
}
SECTION("First moved, second ref'd") {
product(std::move(bi), bi2);
REQUIRE( bi.was_moved_from() );
REQUIRE_FALSE( bi2.was_moved_from() );
}
}
TEST_CASE("product: doesn't move or copy elements of iterable", "[product]") {
constexpr itertest::SolidInt arr[] = {{1}, {0}, {2}};
for (auto&& t : product(arr)) {
(void)std::get<0>(t);
}
}
<commit_msg>tests empty product()<commit_after>#include <product.hpp>
#include "helpers.hpp"
#include <vector>
#include <string>
#include <iterator>
#include "catch.hpp"
using iter::product;
using Vec = const std::vector<int>;
TEST_CASE("product: basic test, two sequences", "[product]") {
using TP = std::tuple<int, char>;
using ResType = std::vector<TP>;
Vec n1 = {0, 1};
const std::string s{"abc"};
auto p = product(n1, s);
ResType v(std::begin(p), std::end(p));
ResType vc = {TP{0,'a'}, TP{0,'b'}, TP{0,'c'},
TP{1,'a'}, TP{1,'b'}, TP{1,'c'}};
REQUIRE( v == vc );
}
TEST_CASE("product: three sequences", "[product]") {
using TP = std::tuple <int, char, int>;
using ResType = const std::vector<TP>;
Vec n1 = {0, 1};
const std::string s{"ab"};
Vec n2 = {2};
auto p = product(n1, s, n2);
ResType v(std::begin(p), std::end(p));
ResType vc = {
TP{0, 'a', 2},
TP{0, 'b', 2},
TP{1, 'a', 2},
TP{1, 'b', 2}
};
REQUIRE( v == vc );
}
TEST_CASE("product: empty when any iterable is empty", "[product]") {
Vec n1 = {0, 1};
Vec n2 = {0, 1, 2};
Vec emp = {};
SECTION("first iterable is empty") {
auto p = product(emp, n1, n2);
REQUIRE( std::begin(p) == std::end(p) );
}
SECTION("middle iterable is empty") {
auto p = product(n1, emp, n2);
REQUIRE( std::begin(p) == std::end(p) );
}
SECTION("last iterable is empty") {
auto p = product(n1, n2, emp);
REQUIRE( std::begin(p) == std::end(p) );
}
}
TEST_CASE("product: single iterable", "[product]") {
const std::string s{"ab"};
using TP = std::tuple<char>;
using ResType = const std::vector<TP>;
auto p = product(s);
ResType v(std::begin(p), std::end(p));
ResType vc = {TP{'a'}, TP{'b'}};
REQUIRE( v == vc );
}
TEST_CASE("product: no arguments gives one empty tuple", "[product") {
auto p = product();
auto it = std::begin(p);
REQUIRE( it != std::end(p) );
REQUIRE( *it == std::make_tuple() );
++it;
REQUIRE( it == std::end(p) );
}
TEST_CASE("product: binds to lvalues and moves rvalues", "[product]") {
itertest::BasicIterable<char> bi{'x', 'y'};
itertest::BasicIterable<int> bi2{0, 1};
SECTION("First ref'd, second moved") {
product(bi, std::move(bi2));
REQUIRE_FALSE( bi.was_moved_from() );
REQUIRE( bi2.was_moved_from() );
}
SECTION("First moved, second ref'd") {
product(std::move(bi), bi2);
REQUIRE( bi.was_moved_from() );
REQUIRE_FALSE( bi2.was_moved_from() );
}
}
TEST_CASE("product: doesn't move or copy elements of iterable", "[product]") {
constexpr itertest::SolidInt arr[] = {{1}, {0}, {2}};
for (auto&& t : product(arr)) {
(void)std::get<0>(t);
}
}
<|endoftext|> |
<commit_before>// 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 "tink/util/validation.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "tink/util/test_matchers.h"
namespace crypto {
namespace tink {
namespace {
using crypto::tink::test::IsOk;
using crypto::tink::test::StatusIs;
TEST(ValidateKey, ValidKey) {
google::crypto::tink::Keyset::Key key;
key.set_key_id(100);
key.mutable_key_data()->set_value("some value");
key.set_output_prefix_type(google::crypto::tink::OutputPrefixType::TINK);
key.set_status(google::crypto::tink::KeyStatusType::ENABLED);
EXPECT_THAT(crypto::tink::ValidateKey(key), IsOk());
}
TEST(ValidateKey, MissingOutputPrefixType) {
google::crypto::tink::Keyset::Key key;
key.set_key_id(100);
key.mutable_key_data()->set_value("some value");
key.set_status(google::crypto::tink::KeyStatusType::ENABLED);
EXPECT_THAT(crypto::tink::ValidateKey(key),
StatusIs(util::error::INVALID_ARGUMENT));
}
TEST(ValidateKey, MissingKeyData) {
google::crypto::tink::Keyset::Key key;
key.set_key_id(100);
key.set_output_prefix_type(google::crypto::tink::OutputPrefixType::TINK);
key.set_status(google::crypto::tink::KeyStatusType::ENABLED);
EXPECT_THAT(crypto::tink::ValidateKey(key),
StatusIs(util::error::INVALID_ARGUMENT));
}
TEST(ValidateKey, MissingStatus) {
google::crypto::tink::Keyset::Key key;
key.set_key_id(100);
key.mutable_key_data()->set_value("some value");
key.set_output_prefix_type(google::crypto::tink::OutputPrefixType::TINK);
EXPECT_THAT(crypto::tink::ValidateKey(key),
StatusIs(util::error::INVALID_ARGUMENT));
}
TEST(ValidateKeyset, Valid) {
google::crypto::tink::Keyset keyset;
google::crypto::tink::Keyset::Key* key = keyset.add_key();
key->set_key_id(100);
key->mutable_key_data()->set_value("some value");
key->set_output_prefix_type(google::crypto::tink::OutputPrefixType::TINK);
key->set_status(google::crypto::tink::KeyStatusType::ENABLED);
keyset.set_primary_key_id(100);
EXPECT_THAT(crypto::tink::ValidateKeyset(keyset), IsOk());
}
TEST(ValidateKeyset, ValidMultipleKeys) {
google::crypto::tink::Keyset keyset;
google::crypto::tink::Keyset::Key* key = keyset.add_key();
key->set_key_id(32);
key->mutable_key_data()->set_value("some value");
key->set_output_prefix_type(google::crypto::tink::OutputPrefixType::TINK);
key->set_status(google::crypto::tink::KeyStatusType::ENABLED);
key = keyset.add_key();
key->set_key_id(100);
key->mutable_key_data()->set_value("some other value");
key->set_output_prefix_type(google::crypto::tink::OutputPrefixType::TINK);
key->set_status(google::crypto::tink::KeyStatusType::ENABLED);
key = keyset.add_key();
key->set_key_id(18);
key->mutable_key_data()->set_value("some third value");
key->set_output_prefix_type(google::crypto::tink::OutputPrefixType::TINK);
key->set_status(google::crypto::tink::KeyStatusType::ENABLED);
keyset.set_primary_key_id(100);
EXPECT_THAT(crypto::tink::ValidateKeyset(keyset), IsOk());
}
TEST(ValidateKeyset, PrimaryIdNonExistent) {
google::crypto::tink::Keyset keyset;
google::crypto::tink::Keyset::Key* key = keyset.add_key();
key->set_key_id(100);
key->mutable_key_data()->set_value("some value");
key->set_output_prefix_type(google::crypto::tink::OutputPrefixType::TINK);
key->set_status(google::crypto::tink::KeyStatusType::ENABLED);
keyset.set_primary_key_id(99);
EXPECT_THAT(crypto::tink::ValidateKeyset(keyset),
StatusIs(util::error::INVALID_ARGUMENT));
}
TEST(ValidateKeyset, ValidHighId) {
google::crypto::tink::Keyset keyset;
google::crypto::tink::Keyset::Key* key = keyset.add_key();
key->set_key_id(std::numeric_limits<uint32_t>::max());
key->mutable_key_data()->set_value("some value");
key->set_output_prefix_type(google::crypto::tink::OutputPrefixType::TINK);
key->set_status(google::crypto::tink::KeyStatusType::ENABLED);
keyset.set_primary_key_id(std::numeric_limits<uint32_t>::max());
EXPECT_THAT(crypto::tink::ValidateKeyset(keyset), IsOk());
}
} // namespace
} // namespace tink
} // namespace crypto
<commit_msg>Add some tests to validation_test<commit_after>// 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 "tink/util/validation.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "tink/util/test_matchers.h"
namespace crypto {
namespace tink {
namespace {
using crypto::tink::test::IsOk;
using crypto::tink::test::StatusIs;
using google::crypto::tink::KeyData;
using testing::Not;
TEST(ValidateKey, ValidKey) {
google::crypto::tink::Keyset::Key key;
key.set_key_id(100);
key.mutable_key_data()->set_value("some value");
key.set_output_prefix_type(google::crypto::tink::OutputPrefixType::TINK);
key.set_status(google::crypto::tink::KeyStatusType::ENABLED);
EXPECT_THAT(crypto::tink::ValidateKey(key), IsOk());
}
TEST(ValidateKey, MissingOutputPrefixType) {
google::crypto::tink::Keyset::Key key;
key.set_key_id(100);
key.mutable_key_data()->set_value("some value");
key.set_status(google::crypto::tink::KeyStatusType::ENABLED);
EXPECT_THAT(crypto::tink::ValidateKey(key),
StatusIs(util::error::INVALID_ARGUMENT));
}
TEST(ValidateKey, MissingKeyData) {
google::crypto::tink::Keyset::Key key;
key.set_key_id(100);
key.set_output_prefix_type(google::crypto::tink::OutputPrefixType::TINK);
key.set_status(google::crypto::tink::KeyStatusType::ENABLED);
EXPECT_THAT(crypto::tink::ValidateKey(key),
StatusIs(util::error::INVALID_ARGUMENT));
}
TEST(ValidateKey, MissingStatus) {
google::crypto::tink::Keyset::Key key;
key.set_key_id(100);
key.mutable_key_data()->set_value("some value");
key.set_output_prefix_type(google::crypto::tink::OutputPrefixType::TINK);
EXPECT_THAT(crypto::tink::ValidateKey(key),
StatusIs(util::error::INVALID_ARGUMENT));
}
TEST(ValidateKeyset, Valid) {
google::crypto::tink::Keyset keyset;
google::crypto::tink::Keyset::Key* key = keyset.add_key();
key->set_key_id(100);
key->mutable_key_data()->set_value("some value");
key->set_output_prefix_type(google::crypto::tink::OutputPrefixType::TINK);
key->set_status(google::crypto::tink::KeyStatusType::ENABLED);
keyset.set_primary_key_id(100);
EXPECT_THAT(crypto::tink::ValidateKeyset(keyset), IsOk());
}
TEST(ValidateKeyset, ValidMultipleKeys) {
google::crypto::tink::Keyset keyset;
google::crypto::tink::Keyset::Key* key = keyset.add_key();
key->set_key_id(32);
key->mutable_key_data()->set_value("some value");
key->set_output_prefix_type(google::crypto::tink::OutputPrefixType::TINK);
key->set_status(google::crypto::tink::KeyStatusType::ENABLED);
key = keyset.add_key();
key->set_key_id(100);
key->mutable_key_data()->set_value("some other value");
key->set_output_prefix_type(google::crypto::tink::OutputPrefixType::TINK);
key->set_status(google::crypto::tink::KeyStatusType::ENABLED);
key = keyset.add_key();
key->set_key_id(18);
key->mutable_key_data()->set_value("some third value");
key->set_output_prefix_type(google::crypto::tink::OutputPrefixType::TINK);
key->set_status(google::crypto::tink::KeyStatusType::ENABLED);
keyset.set_primary_key_id(100);
EXPECT_THAT(crypto::tink::ValidateKeyset(keyset), IsOk());
}
// Tests that a keyset with duplicate primary id is rejected
TEST(ValidateKeyset, DuplicatePrimaryId) {
google::crypto::tink::Keyset keyset;
google::crypto::tink::Keyset::Key* key = keyset.add_key();
key->set_key_id(100);
key->mutable_key_data()->set_value("some value");
key->set_output_prefix_type(google::crypto::tink::OutputPrefixType::TINK);
key->set_status(google::crypto::tink::KeyStatusType::ENABLED);
key = keyset.add_key();
key->set_key_id(100);
key->mutable_key_data()->set_value("some other value");
key->set_output_prefix_type(google::crypto::tink::OutputPrefixType::TINK);
key->set_status(google::crypto::tink::KeyStatusType::ENABLED);
keyset.set_primary_key_id(100);
EXPECT_THAT(crypto::tink::ValidateKeyset(keyset), Not(IsOk()));
}
// Tests that a keyset with public keys only doesn't need a primary id
TEST(ValidateKeyset, OnlyPublicKeys) {
google::crypto::tink::Keyset keyset;
google::crypto::tink::Keyset::Key* key = keyset.add_key();
key->set_key_id(32);
key->mutable_key_data()->set_value("some value");
key->mutable_key_data()->set_key_material_type(KeyData::ASYMMETRIC_PUBLIC);
key->set_output_prefix_type(google::crypto::tink::OutputPrefixType::TINK);
key->set_status(google::crypto::tink::KeyStatusType::ENABLED);
key = keyset.add_key();
key->set_key_id(100);
key->mutable_key_data()->set_value("some other value");
key->mutable_key_data()->set_key_material_type(KeyData::ASYMMETRIC_PUBLIC);
key->set_output_prefix_type(google::crypto::tink::OutputPrefixType::TINK);
key->set_status(google::crypto::tink::KeyStatusType::ENABLED);
key = keyset.add_key();
key->set_key_id(18);
key->mutable_key_data()->set_value("some third value");
key->mutable_key_data()->set_key_material_type(KeyData::ASYMMETRIC_PUBLIC);
key->set_output_prefix_type(google::crypto::tink::OutputPrefixType::TINK);
key->set_status(google::crypto::tink::KeyStatusType::ENABLED);
EXPECT_THAT(crypto::tink::ValidateKeyset(keyset), IsOk());
}
TEST(ValidateKeyset, PrimaryIdNonExistent) {
google::crypto::tink::Keyset keyset;
google::crypto::tink::Keyset::Key* key = keyset.add_key();
key->set_key_id(100);
key->mutable_key_data()->set_value("some value");
key->set_output_prefix_type(google::crypto::tink::OutputPrefixType::TINK);
key->set_status(google::crypto::tink::KeyStatusType::ENABLED);
keyset.set_primary_key_id(99);
EXPECT_THAT(crypto::tink::ValidateKeyset(keyset),
StatusIs(util::error::INVALID_ARGUMENT));
}
TEST(ValidateKeyset, ValidHighId) {
google::crypto::tink::Keyset keyset;
google::crypto::tink::Keyset::Key* key = keyset.add_key();
key->set_key_id(std::numeric_limits<uint32_t>::max());
key->mutable_key_data()->set_value("some value");
key->set_output_prefix_type(google::crypto::tink::OutputPrefixType::TINK);
key->set_status(google::crypto::tink::KeyStatusType::ENABLED);
keyset.set_primary_key_id(std::numeric_limits<uint32_t>::max());
EXPECT_THAT(crypto::tink::ValidateKeyset(keyset), IsOk());
}
} // namespace
} // namespace tink
} // namespace crypto
<|endoftext|> |
<commit_before>#include "oddlib/compressiontype3.hpp"
#include "oddlib/stream.hpp"
#include "logger.hpp"
#include <windows.h>
namespace Oddlib
{
static int Next6Bits(signed int& bitCounter, unsigned int& src_data, IStream& stream)
{
int ret = 0;
if (bitCounter > 0)
{
if (bitCounter == 14)
{
bitCounter = 30;
src_data = (ReadUint16(stream) << 14) | src_data;
ret = 2;
}
}
else
{
bitCounter = 32;
src_data = ReadUint32(stream);
ret = 4;
}
bitCounter -= 6;
return ret;
}
// Function 0x004031E0 in AO
std::vector<Uint8> CompressionType3::Decompress(IStream& stream, Uint32 finalW, Uint32 /*w*/, Uint32 h, Uint32 dataSize)
{
size_t dstPos = 0;
std::vector<unsigned char> buffer;
buffer.resize(finalW*h*4);
// const unsigned int whSize = w*h;
int numBytesInFrameCnt = dataSize;// whSize & 0xFFFFFFFC;
if (numBytesInFrameCnt > 0)
{
// unsigned int frame_data_index = 0;
unsigned int src_data = 0;
signed int bitCounter = 0;
do
{
/*numBytesInFrameCnt -=*/ Next6Bits(bitCounter, src_data, stream);
unsigned char bits = src_data & 0x3F;
src_data = src_data >> 6;
--numBytesInFrameCnt;
if (bits & 0x20)
{
// 0x20= 0b100000
// 0x3F= 0b111111
int numberOfBytes = (bits & 0x1F) + 1;
if (numberOfBytes)
{
do
{
if (numBytesInFrameCnt && dstPos < buffer.size())
{
/*numBytesInFrameCnt -=*/ Next6Bits(bitCounter, src_data, stream);
bits = src_data & 0x3F;
src_data = src_data >> 6;
--numBytesInFrameCnt;
}
else
{
// 6 bits from "other" source
bits = 0;// *srcPtr++ & 0x3F;
//--for_counter;
}
// if (dstPos < buffer.size())
{
buffer[dstPos++] = bits;
}
} while (--numberOfBytes != 0);
}
}
else
{
// literal flag isn't set, so we have up to 5 bits of "black" pixels
dstPos += bits + 1;
}
} while (numBytesInFrameCnt);
}
return buffer;
}
}
<commit_msg>final bit of tidy up<commit_after>#include "oddlib/compressiontype3.hpp"
#include "oddlib/stream.hpp"
#include "logger.hpp"
#include <windows.h>
namespace Oddlib
{
static void NextBits(signed int& bitCounter, unsigned int& src_data, IStream& stream)
{
if (bitCounter > 0)
{
if (bitCounter == 14)
{
bitCounter = 30;
src_data = (ReadUint16(stream) << 14) | src_data;
}
}
else
{
bitCounter = 32;
src_data = ReadUint32(stream);
}
bitCounter -= 6;
}
// Function 0x004031E0 in AO
// NOTE: A lot of the code in AbeWin.exe for this algorithm is dead, it attempts to gain some "other" buffer at the end of the
// animation data which actually doesn't exist. Thus all this "extra" code does is write black pixels to an already black canvas.
std::vector<Uint8> CompressionType3::Decompress(IStream& stream, Uint32 finalW, Uint32 /*w*/, Uint32 h, Uint32 dataSize)
{
size_t dstPos = 0;
std::vector<unsigned char> buffer;
buffer.resize(finalW*h);
int numBytesInFrameCnt = dataSize & 0xFFFFFFFC;
if (numBytesInFrameCnt > 0)
{
unsigned int src_data = 0;
signed int bitCounter = 0;
do
{
NextBits(bitCounter, src_data, stream);
unsigned char bits = src_data & 0x3F;
src_data = src_data >> 6;
--numBytesInFrameCnt;
if (bits & 0x20)
{
// 0x20 = 0b100000
// 0x3F = 0b111111
int numberOfBytes = (bits & 0x1F) + 1;
if (numberOfBytes)
{
do
{
if (numBytesInFrameCnt && dstPos < buffer.size())
{
NextBits(bitCounter, src_data, stream);
bits = src_data & 0x3F;
src_data = src_data >> 6;
--numBytesInFrameCnt;
}
else
{
bits = 0;
}
buffer[dstPos++] = bits;
} while (--numberOfBytes != 0);
}
}
else
{
// literal flag isn't set, so we have up to 5 bits of "black" pixels
dstPos += bits + 1;
}
} while (numBytesInFrameCnt);
}
return buffer;
}
}
<|endoftext|> |
<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2017. All rights reserved
*/
#include "../../StroikaPreComp.h"
#if qPlatform_Linux
#include <fcntl.h>
#include <poll.h>
#include <unistd.h>
#elif qPlatform_Windows
#include <Windows.h>
#include <winioctl.h>
#endif
#include "../../Characters/CString/Utilities.h"
#include "../../Characters/Format.h"
#include "../../Characters/String.h"
#include "../../Characters/StringBuilder.h"
#include "../../Characters/String_Constant.h"
#include "../../Characters/ToString.h"
#include "../../DataExchange/Variant/CharacterDelimitedLines/Reader.h"
#include "../../Execution/Finally.h"
#include "../../Execution/Synchronized.h"
#include "../../Memory/SmallStackBuffer.h"
#include "FileInputStream.h"
#include "FileSystem.h"
#include "MountedFilesystem.h"
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Characters;
using namespace Stroika::Foundation::Containers;
using namespace Stroika::Foundation::IO;
using namespace Stroika::Foundation::IO::FileSystem;
// Comment this in to turn on aggressive noisy DbgTrace in this module
//#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1
#if qPlatform_Linux
namespace {
// This is quirky, and only works for Linux, and /proc/mounts
struct Watcher_Proc_Mounts_ {
int mfd;
Watcher_Proc_Mounts_ (const String& fn)
: mfd (::open (fn.AsNarrowSDKString ().c_str (), O_RDONLY, 0))
{
}
~Watcher_Proc_Mounts_ ()
{
::close (mfd);
}
bool IsNewAvail () const
{
// according to http://stackoverflow.com/questions/5070801/monitoring-mount-point-changes-via-proc-mounts
// have to use poll with POLLPRI | POLLERR flags
//
// and from https://linux.die.net/man/5/proc
// /proc/[pid]/mounts (since Linux 2.4.19)...
// Since kernel version 2.6.15, this file is pollable: after opening the file for reading, a change in this file
// (i.e., a file system mount or unmount) causes select(2) to mark the file descriptor as readable, and poll(2)
// and epoll_wait(2) mark the file as having an error condition.
struct pollfd pfd;
int rv;
int changes = 0;
pfd.fd = mfd;
pfd.events = POLLERR | POLLPRI;
pfd.revents = 0;
if ((rv = poll (&pfd, 1, 0)) >= 0) {
if (pfd.revents & POLLERR) {
return true;
}
}
return false;
}
};
}
#endif
namespace {
/*
* Something like this is used on many unix systems.
*/
Collection<MountedFilesystemType> ReadMountInfo_MTabLikeFile_ (const Streams::InputStream<Memory::Byte>& readStream)
{
/*
* I haven't found this clearly documented yet, but it appears that a filesystem can be over-mounted.
* See https://www.kernel.org/doc/Documentation/filesystems/ramfs-rootfs-initramfs.txt
*
* So the last one with a given mount point in the file wins.
*/
Collection<MountedFilesystemType> results;
DataExchange::Variant::CharacterDelimitedLines::Reader reader{{' ', '\t'}};
for (Sequence<String> line : reader.ReadMatrix (readStream)) {
#if USE_NOISY_TRACE_IN_THIS_MODULE_
DbgTrace (L"in IO::FileSystem::{}::ReadMountInfo_MTabLikeFile_ linesize=%d, line[0]=%s", line.size (), line.empty () ? L"" : line[0].c_str ());
#endif
//
// https://www.centos.org/docs/5/html/5.2/Deployment_Guide/s2-proc-mounts.html
//
// 1 - device name
// 2 - mounted on
// 3 - fstype
//
if (line.size () >= 3) {
String devName = line[0];
// procfs/mounts often contains symbolic links to device files
// e.g. /dev/disk/by-uuid/e1d70192-1bb0-461d-b89f-b054e45bfa00
if (devName.StartsWith (L"/")) {
IgnoreExceptionsExceptThreadAbortForCall (devName = IO::FileSystem::FileSystem::Default ().CanonicalizeName (devName));
}
String mountedAt = line[1];
String fstype = line[2];
static const String_Constant kNone_{L"none"};
results.Add (MountedFilesystemType{mountedAt, devName == kNone_ ? Set<String>{} : Set<String>{devName}, fstype}); // special name none often used when there is no name
}
}
return results;
}
}
#if qPlatform_Linux
namespace {
Collection<MountedFilesystemType> ReadMountInfo_FromProcFSMounts_ ()
{
// Note - /procfs files always unseekable
static const String_Constant kUseFile2List_{L"/proc/mounts"};
constexpr bool kUseWatcher_{true}; // seems safe and much faster
if (kUseWatcher_) {
static const Watcher_Proc_Mounts_ sWatcher_{kUseFile2List_};
static Execution::Synchronized<Collection<MountedFilesystemType>> sLastResult_;
static bool sFirstTime_{true};
if (sFirstTime_ or sWatcher_.IsNewAvail ()) {
sLastResult_ = ReadMountInfo_MTabLikeFile_ (FileInputStream::mk (kUseFile2List_, FileInputStream::eNotSeekable));
sFirstTime_ = false;
}
return sLastResult_;
}
else {
return ReadMountInfo_MTabLikeFile_ (FileInputStream::mk (kUseFile2List_, FileInputStream::eNotSeekable));
}
}
}
#endif
#if qPlatform_Linux
namespace {
Collection<MountedFilesystemType> ReadMountInfo_ETC_MTAB_ ()
{
// Note - /procfs files always unseekable and this is sklink to /procfs
static const String_Constant kUseFile2List_{L"/etc/mtab"};
return ReadMountInfo_MTabLikeFile_ (FileInputStream::mk (kUseFile2List_, FileInputStream::eNotSeekable));
}
}
#endif
#if qPlatform_Windows
namespace {
using DynamicDiskIDType = String;
String GetPhysNameForDriveNumber_ (unsigned int i)
{
// This format is NOT super well documented, and was mostly derived from reading the remarks section
// of https://msdn.microsoft.com/en-us/library/windows/desktop/aa363216%28v=vs.85%29.aspx?f=255&MSPPError=-2147217396
// (DeviceIoControl function)
return Characters::Format (L"\\\\.\\PhysicalDrive%d", i);
}
Optional<Set<DynamicDiskIDType>> GetDisksForVolume_ (String volumeName)
{
wchar_t volPathsBuf[10 * 1024]; // intentionally uninitialized since we dont use it if GetVolumePathNamesForVolumeNameW () returns error, and its an OUT only parameter
DWORD retLen = 0;
DWORD x = ::GetVolumePathNamesForVolumeNameW (volumeName.c_str (), volPathsBuf, static_cast<DWORD> (NEltsOf (volPathsBuf)), &retLen);
if (x == 0) {
return {}; // missing - no known - not empty - answer
}
else if (retLen <= 1) {
return Set<DynamicDiskIDType>{};
}
Assert (1 <= Characters::CString::Length (volPathsBuf) and Characters::CString::Length (volPathsBuf) < NEltsOf (volPathsBuf));
volumeName = L"\\\\.\\" + String::FromSDKString (volPathsBuf).CircularSubString (0, -1);
// @todo - rewrite this - must somehow otherwise callocate this to be large enuf (dynamic alloc) - if we want more disk exents, but not sure when that happens...
VOLUME_DISK_EXTENTS volumeDiskExtents;
{
/*
* For reasons I don't understand (maybe a hit at http://superuser.com/questions/733687/give-regular-user-permission-to-access-physical-drive-on-windows)
* this only works with admin privilges
*/
HANDLE hHandle = ::CreateFileW (volumeName.c_str (), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
if (hHandle == INVALID_HANDLE_VALUE) {
return {};
}
DWORD dwBytesReturned = 0;
BOOL bResult = ::DeviceIoControl (hHandle, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, nullptr, 0, &volumeDiskExtents, sizeof (volumeDiskExtents), &dwBytesReturned, NULL);
::CloseHandle (hHandle);
if (not bResult) {
return {};
}
}
Set<DynamicDiskIDType> result;
for (DWORD n = 0; n < volumeDiskExtents.NumberOfDiskExtents; ++n) {
result.Add (GetPhysNameForDriveNumber_ (volumeDiskExtents.Extents[n].DiskNumber));
}
return result;
}
Collection<MountedFilesystemType> GetMountedFilesystems_Windows_ ()
{
Collection<MountedFilesystemType> results{};
TCHAR volumeNameBuf[1024]; // intentionally uninitialized since OUT parameter and not used unless FindFirstVolume success
HANDLE hVol = INVALID_HANDLE_VALUE;
auto&& cleanup = Execution::Finally ([&]() noexcept { if (hVol != INVALID_HANDLE_VALUE) { ::CloseHandle (hVol); } });
for (HANDLE hVol = ::FindFirstVolume (volumeNameBuf, static_cast<DWORD> (NEltsOf (volumeNameBuf))); hVol != INVALID_HANDLE_VALUE;) {
DWORD lpMaximumComponentLength;
DWORD dwSysFlags;
TCHAR fileSysNameBuf[1024];
if (::GetVolumeInformation (volumeNameBuf, nullptr, static_cast<DWORD> (NEltsOf (volumeNameBuf)), nullptr, &lpMaximumComponentLength, &dwSysFlags, fileSysNameBuf, static_cast<DWORD> (NEltsOf (fileSysNameBuf)))) {
MountedFilesystemType v;
v.fFileSystemType = String::FromSDKString (fileSysNameBuf);
v.fVolumeID = String::FromSDKString (volumeNameBuf);
v.fDevicePaths = GetDisksForVolume_ (volumeNameBuf);
TCHAR volPathsBuf[10 * 1024]; // intentionally uninitialized
DWORD retLen = 0;
DWORD x = ::GetVolumePathNamesForVolumeName (volumeNameBuf, volPathsBuf, static_cast<DWORD> (NEltsOf (volPathsBuf)), &retLen);
if (x == 0) {
DbgTrace (SDKSTR ("Ignoring error getting paths (volume='%s')"), volumeNameBuf);
}
else if (volPathsBuf[0] == 0) {
// Ignore - unmounted!
DbgTrace (SDKSTR ("Ignoring unmounted filesystem (volume='%s')"), volumeNameBuf);
}
else {
for (const TCHAR* NameIdx = volPathsBuf; NameIdx[0] != L'\0'; NameIdx += Characters::CString::Length (NameIdx) + 1) {
v.fMountedOn = String::FromSDKString (NameIdx);
results.Add (v);
}
}
}
// find next
if (not::FindNextVolume (hVol, volumeNameBuf, static_cast<DWORD> (NEltsOf (volumeNameBuf)))) {
::FindVolumeClose (hVol);
hVol = INVALID_HANDLE_VALUE;
}
}
return results;
}
}
#endif
/*
********************************************************************************
******************** IO::FileSystem::MountedFilesystemType *********************
********************************************************************************
*/
String MountedFilesystemType::ToString () const
{
StringBuilder sb;
sb += L"{";
sb += L"Mounted-On: '" + fMountedOn + L"', ";
if (fDevicePaths) {
sb += L"Device-Paths: " + Characters::ToString (*fDevicePaths) + L", ";
}
if (fFileSystemType) {
sb += L"FileSystem-Type: '" + *fFileSystemType + L"', ";
}
if (fVolumeID) {
sb += L"Volume-ID: '" + *fVolumeID + L"', ";
}
sb += L"}";
return sb.str ();
}
/*
********************************************************************************
******************** IO::FileSystem::GetMountedFilesystems *********************
********************************************************************************
*/
Containers::Collection<MountedFilesystemType> IO::FileSystem::GetMountedFilesystems ()
{
#if qPlatform_Linux
return ReadMountInfo_FromProcFSMounts_ ();
#elif qPlatform_Windows
return GetMountedFilesystems_Windows_ ();
#else
AssertNotImplemented ();
return {};
#endif
}
<commit_msg>for macos - use IO::FileSystem::GetMountedFilesystems () WeakAssert<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2017. All rights reserved
*/
#include "../../StroikaPreComp.h"
#if qPlatform_Linux
#include <fcntl.h>
#include <poll.h>
#include <unistd.h>
#elif qPlatform_Windows
#include <Windows.h>
#include <winioctl.h>
#endif
#include "../../Characters/CString/Utilities.h"
#include "../../Characters/Format.h"
#include "../../Characters/String.h"
#include "../../Characters/StringBuilder.h"
#include "../../Characters/String_Constant.h"
#include "../../Characters/ToString.h"
#include "../../DataExchange/Variant/CharacterDelimitedLines/Reader.h"
#include "../../Execution/Finally.h"
#include "../../Execution/Synchronized.h"
#include "../../Memory/SmallStackBuffer.h"
#include "FileInputStream.h"
#include "FileSystem.h"
#include "MountedFilesystem.h"
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Characters;
using namespace Stroika::Foundation::Containers;
using namespace Stroika::Foundation::IO;
using namespace Stroika::Foundation::IO::FileSystem;
// Comment this in to turn on aggressive noisy DbgTrace in this module
//#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1
#if qPlatform_Linux
namespace {
// This is quirky, and only works for Linux, and /proc/mounts
struct Watcher_Proc_Mounts_ {
int mfd;
Watcher_Proc_Mounts_ (const String& fn)
: mfd (::open (fn.AsNarrowSDKString ().c_str (), O_RDONLY, 0))
{
}
~Watcher_Proc_Mounts_ ()
{
::close (mfd);
}
bool IsNewAvail () const
{
// according to http://stackoverflow.com/questions/5070801/monitoring-mount-point-changes-via-proc-mounts
// have to use poll with POLLPRI | POLLERR flags
//
// and from https://linux.die.net/man/5/proc
// /proc/[pid]/mounts (since Linux 2.4.19)...
// Since kernel version 2.6.15, this file is pollable: after opening the file for reading, a change in this file
// (i.e., a file system mount or unmount) causes select(2) to mark the file descriptor as readable, and poll(2)
// and epoll_wait(2) mark the file as having an error condition.
struct pollfd pfd;
int rv;
int changes = 0;
pfd.fd = mfd;
pfd.events = POLLERR | POLLPRI;
pfd.revents = 0;
if ((rv = poll (&pfd, 1, 0)) >= 0) {
if (pfd.revents & POLLERR) {
return true;
}
}
return false;
}
};
}
#endif
namespace {
/*
* Something like this is used on many unix systems.
*/
Collection<MountedFilesystemType> ReadMountInfo_MTabLikeFile_ (const Streams::InputStream<Memory::Byte>& readStream)
{
/*
* I haven't found this clearly documented yet, but it appears that a filesystem can be over-mounted.
* See https://www.kernel.org/doc/Documentation/filesystems/ramfs-rootfs-initramfs.txt
*
* So the last one with a given mount point in the file wins.
*/
Collection<MountedFilesystemType> results;
DataExchange::Variant::CharacterDelimitedLines::Reader reader{{' ', '\t'}};
for (Sequence<String> line : reader.ReadMatrix (readStream)) {
#if USE_NOISY_TRACE_IN_THIS_MODULE_
DbgTrace (L"in IO::FileSystem::{}::ReadMountInfo_MTabLikeFile_ linesize=%d, line[0]=%s", line.size (), line.empty () ? L"" : line[0].c_str ());
#endif
//
// https://www.centos.org/docs/5/html/5.2/Deployment_Guide/s2-proc-mounts.html
//
// 1 - device name
// 2 - mounted on
// 3 - fstype
//
if (line.size () >= 3) {
String devName = line[0];
// procfs/mounts often contains symbolic links to device files
// e.g. /dev/disk/by-uuid/e1d70192-1bb0-461d-b89f-b054e45bfa00
if (devName.StartsWith (L"/")) {
IgnoreExceptionsExceptThreadAbortForCall (devName = IO::FileSystem::FileSystem::Default ().CanonicalizeName (devName));
}
String mountedAt = line[1];
String fstype = line[2];
static const String_Constant kNone_{L"none"};
results.Add (MountedFilesystemType{mountedAt, devName == kNone_ ? Set<String>{} : Set<String>{devName}, fstype}); // special name none often used when there is no name
}
}
return results;
}
}
#if qPlatform_Linux
namespace {
Collection<MountedFilesystemType> ReadMountInfo_FromProcFSMounts_ ()
{
// Note - /procfs files always unseekable
static const String_Constant kUseFile2List_{L"/proc/mounts"};
constexpr bool kUseWatcher_{true}; // seems safe and much faster
if (kUseWatcher_) {
static const Watcher_Proc_Mounts_ sWatcher_{kUseFile2List_};
static Execution::Synchronized<Collection<MountedFilesystemType>> sLastResult_;
static bool sFirstTime_{true};
if (sFirstTime_ or sWatcher_.IsNewAvail ()) {
sLastResult_ = ReadMountInfo_MTabLikeFile_ (FileInputStream::mk (kUseFile2List_, FileInputStream::eNotSeekable));
sFirstTime_ = false;
}
return sLastResult_;
}
else {
return ReadMountInfo_MTabLikeFile_ (FileInputStream::mk (kUseFile2List_, FileInputStream::eNotSeekable));
}
}
}
#endif
#if qPlatform_Linux
namespace {
Collection<MountedFilesystemType> ReadMountInfo_ETC_MTAB_ ()
{
// Note - /procfs files always unseekable and this is sklink to /procfs
static const String_Constant kUseFile2List_{L"/etc/mtab"};
return ReadMountInfo_MTabLikeFile_ (FileInputStream::mk (kUseFile2List_, FileInputStream::eNotSeekable));
}
}
#endif
#if qPlatform_Windows
namespace {
using DynamicDiskIDType = String;
String GetPhysNameForDriveNumber_ (unsigned int i)
{
// This format is NOT super well documented, and was mostly derived from reading the remarks section
// of https://msdn.microsoft.com/en-us/library/windows/desktop/aa363216%28v=vs.85%29.aspx?f=255&MSPPError=-2147217396
// (DeviceIoControl function)
return Characters::Format (L"\\\\.\\PhysicalDrive%d", i);
}
Optional<Set<DynamicDiskIDType>> GetDisksForVolume_ (String volumeName)
{
wchar_t volPathsBuf[10 * 1024]; // intentionally uninitialized since we dont use it if GetVolumePathNamesForVolumeNameW () returns error, and its an OUT only parameter
DWORD retLen = 0;
DWORD x = ::GetVolumePathNamesForVolumeNameW (volumeName.c_str (), volPathsBuf, static_cast<DWORD> (NEltsOf (volPathsBuf)), &retLen);
if (x == 0) {
return {}; // missing - no known - not empty - answer
}
else if (retLen <= 1) {
return Set<DynamicDiskIDType>{};
}
Assert (1 <= Characters::CString::Length (volPathsBuf) and Characters::CString::Length (volPathsBuf) < NEltsOf (volPathsBuf));
volumeName = L"\\\\.\\" + String::FromSDKString (volPathsBuf).CircularSubString (0, -1);
// @todo - rewrite this - must somehow otherwise callocate this to be large enuf (dynamic alloc) - if we want more disk exents, but not sure when that happens...
VOLUME_DISK_EXTENTS volumeDiskExtents;
{
/*
* For reasons I don't understand (maybe a hit at http://superuser.com/questions/733687/give-regular-user-permission-to-access-physical-drive-on-windows)
* this only works with admin privilges
*/
HANDLE hHandle = ::CreateFileW (volumeName.c_str (), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
if (hHandle == INVALID_HANDLE_VALUE) {
return {};
}
DWORD dwBytesReturned = 0;
BOOL bResult = ::DeviceIoControl (hHandle, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, nullptr, 0, &volumeDiskExtents, sizeof (volumeDiskExtents), &dwBytesReturned, NULL);
::CloseHandle (hHandle);
if (not bResult) {
return {};
}
}
Set<DynamicDiskIDType> result;
for (DWORD n = 0; n < volumeDiskExtents.NumberOfDiskExtents; ++n) {
result.Add (GetPhysNameForDriveNumber_ (volumeDiskExtents.Extents[n].DiskNumber));
}
return result;
}
Collection<MountedFilesystemType> GetMountedFilesystems_Windows_ ()
{
Collection<MountedFilesystemType> results{};
TCHAR volumeNameBuf[1024]; // intentionally uninitialized since OUT parameter and not used unless FindFirstVolume success
HANDLE hVol = INVALID_HANDLE_VALUE;
auto&& cleanup = Execution::Finally ([&]() noexcept { if (hVol != INVALID_HANDLE_VALUE) { ::CloseHandle (hVol); } });
for (HANDLE hVol = ::FindFirstVolume (volumeNameBuf, static_cast<DWORD> (NEltsOf (volumeNameBuf))); hVol != INVALID_HANDLE_VALUE;) {
DWORD lpMaximumComponentLength;
DWORD dwSysFlags;
TCHAR fileSysNameBuf[1024];
if (::GetVolumeInformation (volumeNameBuf, nullptr, static_cast<DWORD> (NEltsOf (volumeNameBuf)), nullptr, &lpMaximumComponentLength, &dwSysFlags, fileSysNameBuf, static_cast<DWORD> (NEltsOf (fileSysNameBuf)))) {
MountedFilesystemType v;
v.fFileSystemType = String::FromSDKString (fileSysNameBuf);
v.fVolumeID = String::FromSDKString (volumeNameBuf);
v.fDevicePaths = GetDisksForVolume_ (volumeNameBuf);
TCHAR volPathsBuf[10 * 1024]; // intentionally uninitialized
DWORD retLen = 0;
DWORD x = ::GetVolumePathNamesForVolumeName (volumeNameBuf, volPathsBuf, static_cast<DWORD> (NEltsOf (volPathsBuf)), &retLen);
if (x == 0) {
DbgTrace (SDKSTR ("Ignoring error getting paths (volume='%s')"), volumeNameBuf);
}
else if (volPathsBuf[0] == 0) {
// Ignore - unmounted!
DbgTrace (SDKSTR ("Ignoring unmounted filesystem (volume='%s')"), volumeNameBuf);
}
else {
for (const TCHAR* NameIdx = volPathsBuf; NameIdx[0] != L'\0'; NameIdx += Characters::CString::Length (NameIdx) + 1) {
v.fMountedOn = String::FromSDKString (NameIdx);
results.Add (v);
}
}
}
// find next
if (not::FindNextVolume (hVol, volumeNameBuf, static_cast<DWORD> (NEltsOf (volumeNameBuf)))) {
::FindVolumeClose (hVol);
hVol = INVALID_HANDLE_VALUE;
}
}
return results;
}
}
#endif
/*
********************************************************************************
******************** IO::FileSystem::MountedFilesystemType *********************
********************************************************************************
*/
String MountedFilesystemType::ToString () const
{
StringBuilder sb;
sb += L"{";
sb += L"Mounted-On: '" + fMountedOn + L"', ";
if (fDevicePaths) {
sb += L"Device-Paths: " + Characters::ToString (*fDevicePaths) + L", ";
}
if (fFileSystemType) {
sb += L"FileSystem-Type: '" + *fFileSystemType + L"', ";
}
if (fVolumeID) {
sb += L"Volume-ID: '" + *fVolumeID + L"', ";
}
sb += L"}";
return sb.str ();
}
/*
********************************************************************************
******************** IO::FileSystem::GetMountedFilesystems *********************
********************************************************************************
*/
Containers::Collection<MountedFilesystemType> IO::FileSystem::GetMountedFilesystems ()
{
#if qPlatform_Linux
return ReadMountInfo_FromProcFSMounts_ ();
#elif qPlatform_Windows
return GetMountedFilesystems_Windows_ ();
#else
// @todo - maybe a start on macos would be to walk the directory /Volumes
WeakAssertNotImplemented ();
return {};
#endif
}
<|endoftext|> |
<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2011. All rights reserved
*/
#include "../../StroikaPreComp.h"
#include "../../Execution/Exceptions.h"
#include "../../Execution/ErrNoException.h"
#include "FStreamSupport.h"
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Streams;
using namespace Stroika::Foundation::Streams::iostream;
/*
********************************************************************************
********************** iostream::OpenInputFileStream ***************************
********************************************************************************
*/
void Streams::iostream::OpenInputFileStream (ifstream* ifStream, const TString& fileName, ios_base::openmode _Mode)
{
RequireNotNull (ifStream);
ifStream->open (fileName.c_str (), _Mode);
if (!(*ifStream)) {
#if qPlatform_Windows
Execution::ThrowIfNotERROR_SUCCESS (::GetLastError ());
#elif qPlatform_POSIX
Execution::ThrowIfError_errno_t ();
AssertNotReached ();// errno sb set
#else
AssertNotImplemented ();
#endif
}
}
/*
********************************************************************************
****************** StreamUtils::OpenOutputFileStream ***************************
********************************************************************************
*/
void Streams::iostream::OpenOutputFileStream (ofstream* ofStream, const TString& fileName, ios_base::openmode _Mode)
{
RequireNotNull (ofStream);
ofStream->open (fileName.c_str (), _Mode);
if (!(*ofStream)) {
#if qPlatform_Windows
Execution::ThrowIfNotERROR_SUCCESS (::GetLastError ());
#elif qPlatform_POSIX
Execution::ThrowIfError_errno_t ();
AssertNotReached ();// errno sb set
#else
AssertNotImplemented ();
#endif
}
}
<commit_msg>fix Streams::iostream::Open-READ/WRITE Streams now use CATCH_REBIND_FILENAMES_HELPER_() to include filename in exceptions<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2011. All rights reserved
*/
#include "../../StroikaPreComp.h"
#include "../../Execution/Exceptions.h"
#include "../../Execution/ErrNoException.h"
#include "../../IO/FileAccessException.h"
#include "../../IO/FileBusyException.h"
#include "../../IO/FileFormatException.h"
#include "FStreamSupport.h"
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Streams;
using namespace Stroika::Foundation::Streams::iostream;
using namespace Stroika::Foundation::IO;
/*
* Stuff INSIDE try section raises exceptions. Catch and rethow SOME binding in a new filename (if none was known).
* Otehr exceptions just ignore (so they auto-propagate)
*/
#define CATCH_REBIND_FILENAMES_HELPER_(USEFILENAME) \
catch (const FileBusyException& e) { \
if (e.fFileName.empty ()) {\
Execution::DoThrow (FileBusyException (USEFILENAME));\
}\
Execution::DoReThrow ();\
}\
catch (const FileAccessException& e) { \
if (e.fFileName.empty ()) {\
Execution::DoThrow (FileAccessException (USEFILENAME, e.fFileAccessMode));\
}\
Execution::DoReThrow ();\
}\
catch (const FileFormatException& e) { \
if (e.fFileName.empty ()) {\
Execution::DoThrow (FileFormatException (USEFILENAME));\
}\
Execution::DoReThrow ();\
}\
/*
********************************************************************************
********************** iostream::OpenInputFileStream ***************************
********************************************************************************
*/
void Streams::iostream::OpenInputFileStream (ifstream* ifStream, const TString& fileName, ios_base::openmode _Mode)
{
RequireNotNull (ifStream);
try {
ifStream->open (fileName.c_str (), _Mode);
if (!(*ifStream)) {
#if qPlatform_Windows
Execution::ThrowIfNotERROR_SUCCESS (::GetLastError ());
#elif qPlatform_POSIX
Execution::ThrowIfError_errno_t ();
AssertNotReached ();// errno sb set
#else
AssertNotImplemented ();
#endif
}
}
CATCH_REBIND_FILENAMES_HELPER_(fileName);
}
/*
********************************************************************************
****************** StreamUtils::OpenOutputFileStream ***************************
********************************************************************************
*/
void Streams::iostream::OpenOutputFileStream (ofstream* ofStream, const TString& fileName, ios_base::openmode _Mode)
{
RequireNotNull (ofStream);
try {
ofStream->open (fileName.c_str (), _Mode);
if (!(*ofStream)) {
#if qPlatform_Windows
Execution::ThrowIfNotERROR_SUCCESS (::GetLastError ());
#elif qPlatform_POSIX
Execution::ThrowIfError_errno_t ();
AssertNotReached ();// errno sb set
#else
AssertNotImplemented ();
#endif
}
}
CATCH_REBIND_FILENAMES_HELPER_(fileName);
}
<|endoftext|> |
<commit_before>/*
* LootManagerImplementation.cpp
*
* Created on: Jun 20, 2011
* Author: Kyle
*/
#include "engine/engine.h"
#include "LootManager.h"
#include "server/zone/objects/scene/SceneObject.h"
#include "server/zone/objects/creature/CreatureObject.h"
#include "server/zone/objects/creature/AiAgent.h"
#include "server/zone/managers/crafting/CraftingManager.h"
#include "server/zone/managers/templates/TemplateManager.h"
#include "server/zone/templates/LootItemTemplate.h"
#include "server/zone/templates/LootGroupTemplate.h"
#include "server/zone/ZoneServer.h"
#include "server/zone/managers/stringid/StringIdManager.h"
#include "LootGroupMap.h"
void LootManagerImplementation::initialize() {
lua = new Lua();
lua->init();
info("Loading configuration.");
if(!loadConfigData()) {
loadDefaultConfig();
info("Failed to load configuration values. Using default.");
}
lootGroupMap = LootGroupMap::instance();
lootGroupMap->initialize();
info("Loaded " + String::valueOf(lootableMods.size()) + " lootable stat mods.", true);
info("Loaded " + String::valueOf(lootGroupMap->countLootItemTemplates()) + " loot items.", true);
info("Loaded " + String::valueOf(lootGroupMap->countLootGroupTemplates()) + " loot groups.", true);
info("Initialized.");
}
bool LootManagerImplementation::loadConfigFile() {
return lua->runFile("scripts/managers/loot_manager.lua");
}
bool LootManagerImplementation::loadConfigData() {
if (!loadConfigFile())
return false;
exceptionalChance = lua->getGlobalFloat("exceptionalChance");
exceptionalModifier = lua->getGlobalFloat("exceptionalModifier");
legendaryChance = lua->getGlobalFloat("legendaryChance");
legendaryModifier = lua->getGlobalFloat("legendaryModifier");
LuaObject lootableModsTable = lua->getGlobalObject("lootableStatMods");
if (!lootableModsTable.isValidTable())
return false;
for (int i = 1; i <= lootableModsTable.getTableSize(); ++i) {
String mod = lootableModsTable.getStringAt(i);
lootableMods.put(mod);
}
lootableModsTable.pop();
return true;
}
void LootManagerImplementation::loadDefaultConfig() {
}
void LootManagerImplementation::setInitialObjectStats(LootItemTemplate* templateObject, CraftingValues* craftingValues, TangibleObject* prototype) {
SharedTangibleObjectTemplate* tanoTemplate = dynamic_cast<SharedTangibleObjectTemplate*>(prototype->getObjectTemplate());
if (tanoTemplate != NULL) {
Vector<String>* titles = tanoTemplate->getExperimentalGroupTitles();
Vector<String>* props = tanoTemplate->getExperimentalSubGroupTitles();
Vector<float>* mins = tanoTemplate->getExperimentalMin();
Vector<float>* maxs = tanoTemplate->getExperimentalMax();
Vector<short>* prec = tanoTemplate->getExperimentalPrecision();
for (int i = 0; i < props->size(); ++i) {
String title = titles->get(i);
String property = props->get(i);
if (craftingValues->hasProperty(property))
continue;
craftingValues->addExperimentalProperty(property, property, mins->get(i), maxs->get(i), prec->get(i), false);
if(title == "null")
craftingValues->setHidden(property);
}
}
Vector<String>* customizationData = templateObject->getCustomizationStringNames();
Vector<Vector<int> >* customizationValues = templateObject->getCustomizationValues();
for (int i = 0; i < customizationData->size(); ++i) {
String customizationString = customizationData->get(i);
Vector<int>* values = &customizationValues->get(i);
int idx = customizationString.lastIndexOf("/");
if (idx != -1)
customizationString = customizationString.subString(idx + 1);
if (values->size() > 0) {
int randomValue = values->get(System::random(values->size() - 1));
prototype->setCustomizationVariable(customizationString, randomValue, false);
}
}
}
void LootManagerImplementation::setCustomObjectName(TangibleObject* object, LootItemTemplate* templateObject) {
String customName = templateObject->getCustomObjectName();
if (!customName.isEmpty()) {
if (customName.charAt(0) == '@') {
StringId stringId(customName);
object->setObjectName(stringId);
} else {
object->setCustomObjectName(customName, false);
}
}
}
int LootManagerImplementation::calculateLootCredits(int level) {
int maxcredits = (int) round((.03f * level * level) + (3 * level) + 50);
int mincredits = (int) round((((float) maxcredits) * .5f) + (2.0f * level));
int credits = mincredits + System::random(maxcredits - mincredits);
return credits;
}
TangibleObject* LootManagerImplementation::createLootObject(LootItemTemplate* templateObject, int level) {
if(level > 300)
level = 300;
String directTemplateObject = templateObject->getDirectObjectTemplate();
ManagedReference<TangibleObject*> prototype = dynamic_cast<TangibleObject*> (zoneServer->createObject(directTemplateObject.hashCode(), 2));
if (prototype == NULL)
return NULL;
prototype->createChildObjects();
String serial = craftingManager->generateSerial();
prototype->setSerialNumber(serial);
CraftingValues craftingValues = templateObject->getCraftingValuesCopy();
setInitialObjectStats(templateObject, &craftingValues, prototype);
setCustomObjectName(prototype, templateObject);
float excMod = 1.0;
if (System::random(exceptionalChance) == exceptionalChance) {
UnicodeString objectName = prototype->getCustomObjectName();
uint32 bitmask = prototype->getOptionsBitmask() | OptionBitmask::YELLOW;
if (objectName.isEmpty())
objectName = StringIdManager::instance()->getStringId(prototype->getObjectName()->getFullPath().hashCode());
UnicodeString newName = objectName + " (Exceptional)";
prototype->setCustomObjectName(newName, false);
excMod = exceptionalModifier;
prototype->setOptionsBitmask(bitmask, false);
} else if (System::random(legendaryChance) == legendaryChance) {
UnicodeString objectName = prototype->getCustomObjectName();
uint32 bitmask = prototype->getOptionsBitmask() | OptionBitmask::YELLOW;
if (objectName.isEmpty())
objectName = StringIdManager::instance()->getStringId(prototype->getObjectName()->getFullPath().hashCode());
UnicodeString newName = objectName + " (Legendary)";
prototype->setCustomObjectName(newName, false);
excMod = legendaryModifier;
prototype->setOptionsBitmask(bitmask, false);
}
String subtitle;
float percentage = System::random(10000) / 10000.f; //Generate a base percentage. We will deviate slightly from this on each stat.
for (int i = 0; i < craftingValues.getExperimentalPropertySubtitleSize(); ++i) {
subtitle = craftingValues.getExperimentalPropertySubtitle(i);
if (subtitle == "hitpoints")
continue;
float min = craftingValues.getMinValue(subtitle);
float max = craftingValues.getMaxValue(subtitle);
if(min == max)
continue;
if (subtitle != "useCount" &&
subtitle != "quantity" &&
subtitle != "charges" &&
subtitle != "uses" &&
subtitle != "charge") {
float minMod = (max >= min) ? 2000.f : -2000.f;
float maxMod = (max >= min) ? 500.f : -500.f;
min = (min * level / minMod) + min;
max = (max * level / maxMod) + max;
if (max >= min) {
min *= excMod;
max *= excMod;
} else {
min /= excMod;
max /= excMod;
}
craftingValues.setMinValue(subtitle, min);
craftingValues.setMaxValue(subtitle, max);
}
float deviation = (((float) System::random(400)) - 200) / 1000.f; //Deviate up to 2%
craftingValues.setCurrentPercentage(subtitle, percentage + deviation);
}
// Use percentages to recalculate the values
craftingValues.recalculateValues(false);
craftingValues.addExperimentalProperty("creatureLevel", "creatureLevel", level, level, 0, false);
craftingValues.setHidden("creatureLevel");
// Update the Tano with new values
prototype->updateCraftingValues(&craftingValues, true);
return prototype;
}
bool LootManagerImplementation::createLoot(SceneObject* container, AiAgent* creature) {
LootGroupCollection* lootCollection = creature->getLootGroups();
if (lootCollection == NULL)
return false;
for (int i = 0; i < lootCollection->count(); ++i) {
LootGroupCollectionEntry* entry = lootCollection->get(i);
int lootChance = entry->getLootChance();
if (lootChance <= 0)
continue;
int roll = System::random(10000000);
if (roll > lootChance)
continue;
int tempChance = 0; //Start at 0.
LootGroups* lootGroups = entry->getLootGroups();
//Select the loot group to use.
for (int i = 0; i < lootGroups->count(); ++i) {
LootGroupEntry* entry = lootGroups->get(i);
tempChance += entry->getLootChance();
//Is this entry lower than the roll? If yes, then we want to try the next entry.
if (tempChance < roll)
continue;
createLoot(container, entry->getLootGroupName(), creature->getLevel());
break;
}
}
return true;
}
bool LootManagerImplementation::createLoot(SceneObject* container, const String& lootGroup, int level) {
if (container->hasFullContainerObjects())
return false;
Reference<LootGroupTemplate*> group = lootGroupMap->getLootGroupTemplate(lootGroup);
if (group == NULL) {
warning("Loot group template requested does not exist: " + lootGroup);
return false;
}
//Now we do the second roll for the item out of the group.
int roll = System::random(10000000);
Reference<LootItemTemplate*> itemTemplate = lootGroupMap->getLootItemTemplate(group->getLootItemTemplateForRoll(roll));
if (itemTemplate == NULL) {
warning("Loot item template requested does not exist: " + group->getLootItemTemplateForRoll(roll) + " for templateName: " + group->getTemplateName());
return false;
}
TangibleObject* obj = createLootObject(itemTemplate, level);
if (obj == NULL)
return false;
if (container->transferObject(obj, -1, false))
container->broadcastObject(obj, true);
return true;
}
<commit_msg>[added] debug message when creating unexistent loot<commit_after>/*
* LootManagerImplementation.cpp
*
* Created on: Jun 20, 2011
* Author: Kyle
*/
#include "engine/engine.h"
#include "LootManager.h"
#include "server/zone/objects/scene/SceneObject.h"
#include "server/zone/objects/creature/CreatureObject.h"
#include "server/zone/objects/creature/AiAgent.h"
#include "server/zone/managers/crafting/CraftingManager.h"
#include "server/zone/managers/templates/TemplateManager.h"
#include "server/zone/templates/LootItemTemplate.h"
#include "server/zone/templates/LootGroupTemplate.h"
#include "server/zone/ZoneServer.h"
#include "server/zone/managers/stringid/StringIdManager.h"
#include "LootGroupMap.h"
void LootManagerImplementation::initialize() {
lua = new Lua();
lua->init();
info("Loading configuration.");
if(!loadConfigData()) {
loadDefaultConfig();
info("Failed to load configuration values. Using default.");
}
lootGroupMap = LootGroupMap::instance();
lootGroupMap->initialize();
info("Loaded " + String::valueOf(lootableMods.size()) + " lootable stat mods.", true);
info("Loaded " + String::valueOf(lootGroupMap->countLootItemTemplates()) + " loot items.", true);
info("Loaded " + String::valueOf(lootGroupMap->countLootGroupTemplates()) + " loot groups.", true);
info("Initialized.");
}
bool LootManagerImplementation::loadConfigFile() {
return lua->runFile("scripts/managers/loot_manager.lua");
}
bool LootManagerImplementation::loadConfigData() {
if (!loadConfigFile())
return false;
exceptionalChance = lua->getGlobalFloat("exceptionalChance");
exceptionalModifier = lua->getGlobalFloat("exceptionalModifier");
legendaryChance = lua->getGlobalFloat("legendaryChance");
legendaryModifier = lua->getGlobalFloat("legendaryModifier");
LuaObject lootableModsTable = lua->getGlobalObject("lootableStatMods");
if (!lootableModsTable.isValidTable())
return false;
for (int i = 1; i <= lootableModsTable.getTableSize(); ++i) {
String mod = lootableModsTable.getStringAt(i);
lootableMods.put(mod);
}
lootableModsTable.pop();
return true;
}
void LootManagerImplementation::loadDefaultConfig() {
}
void LootManagerImplementation::setInitialObjectStats(LootItemTemplate* templateObject, CraftingValues* craftingValues, TangibleObject* prototype) {
SharedTangibleObjectTemplate* tanoTemplate = dynamic_cast<SharedTangibleObjectTemplate*>(prototype->getObjectTemplate());
if (tanoTemplate != NULL) {
Vector<String>* titles = tanoTemplate->getExperimentalGroupTitles();
Vector<String>* props = tanoTemplate->getExperimentalSubGroupTitles();
Vector<float>* mins = tanoTemplate->getExperimentalMin();
Vector<float>* maxs = tanoTemplate->getExperimentalMax();
Vector<short>* prec = tanoTemplate->getExperimentalPrecision();
for (int i = 0; i < props->size(); ++i) {
String title = titles->get(i);
String property = props->get(i);
if (craftingValues->hasProperty(property))
continue;
craftingValues->addExperimentalProperty(property, property, mins->get(i), maxs->get(i), prec->get(i), false);
if(title == "null")
craftingValues->setHidden(property);
}
}
Vector<String>* customizationData = templateObject->getCustomizationStringNames();
Vector<Vector<int> >* customizationValues = templateObject->getCustomizationValues();
for (int i = 0; i < customizationData->size(); ++i) {
String customizationString = customizationData->get(i);
Vector<int>* values = &customizationValues->get(i);
int idx = customizationString.lastIndexOf("/");
if (idx != -1)
customizationString = customizationString.subString(idx + 1);
if (values->size() > 0) {
int randomValue = values->get(System::random(values->size() - 1));
prototype->setCustomizationVariable(customizationString, randomValue, false);
}
}
}
void LootManagerImplementation::setCustomObjectName(TangibleObject* object, LootItemTemplate* templateObject) {
String customName = templateObject->getCustomObjectName();
if (!customName.isEmpty()) {
if (customName.charAt(0) == '@') {
StringId stringId(customName);
object->setObjectName(stringId);
} else {
object->setCustomObjectName(customName, false);
}
}
}
int LootManagerImplementation::calculateLootCredits(int level) {
int maxcredits = (int) round((.03f * level * level) + (3 * level) + 50);
int mincredits = (int) round((((float) maxcredits) * .5f) + (2.0f * level));
int credits = mincredits + System::random(maxcredits - mincredits);
return credits;
}
TangibleObject* LootManagerImplementation::createLootObject(LootItemTemplate* templateObject, int level) {
if(level > 300)
level = 300;
String directTemplateObject = templateObject->getDirectObjectTemplate();
ManagedReference<TangibleObject*> prototype = dynamic_cast<TangibleObject*> (zoneServer->createObject(directTemplateObject.hashCode(), 2));
if (prototype == NULL) {
error("could not create loot object: " + directTemplateObject);
return NULL;
}
prototype->createChildObjects();
String serial = craftingManager->generateSerial();
prototype->setSerialNumber(serial);
CraftingValues craftingValues = templateObject->getCraftingValuesCopy();
setInitialObjectStats(templateObject, &craftingValues, prototype);
setCustomObjectName(prototype, templateObject);
float excMod = 1.0;
if (System::random(exceptionalChance) == exceptionalChance) {
UnicodeString objectName = prototype->getCustomObjectName();
uint32 bitmask = prototype->getOptionsBitmask() | OptionBitmask::YELLOW;
if (objectName.isEmpty())
objectName = StringIdManager::instance()->getStringId(prototype->getObjectName()->getFullPath().hashCode());
UnicodeString newName = objectName + " (Exceptional)";
prototype->setCustomObjectName(newName, false);
excMod = exceptionalModifier;
prototype->setOptionsBitmask(bitmask, false);
} else if (System::random(legendaryChance) == legendaryChance) {
UnicodeString objectName = prototype->getCustomObjectName();
uint32 bitmask = prototype->getOptionsBitmask() | OptionBitmask::YELLOW;
if (objectName.isEmpty())
objectName = StringIdManager::instance()->getStringId(prototype->getObjectName()->getFullPath().hashCode());
UnicodeString newName = objectName + " (Legendary)";
prototype->setCustomObjectName(newName, false);
excMod = legendaryModifier;
prototype->setOptionsBitmask(bitmask, false);
}
String subtitle;
float percentage = System::random(10000) / 10000.f; //Generate a base percentage. We will deviate slightly from this on each stat.
for (int i = 0; i < craftingValues.getExperimentalPropertySubtitleSize(); ++i) {
subtitle = craftingValues.getExperimentalPropertySubtitle(i);
if (subtitle == "hitpoints")
continue;
float min = craftingValues.getMinValue(subtitle);
float max = craftingValues.getMaxValue(subtitle);
if(min == max)
continue;
if (subtitle != "useCount" &&
subtitle != "quantity" &&
subtitle != "charges" &&
subtitle != "uses" &&
subtitle != "charge") {
float minMod = (max >= min) ? 2000.f : -2000.f;
float maxMod = (max >= min) ? 500.f : -500.f;
min = (min * level / minMod) + min;
max = (max * level / maxMod) + max;
if (max >= min) {
min *= excMod;
max *= excMod;
} else {
min /= excMod;
max /= excMod;
}
craftingValues.setMinValue(subtitle, min);
craftingValues.setMaxValue(subtitle, max);
}
float deviation = (((float) System::random(400)) - 200) / 1000.f; //Deviate up to 2%
craftingValues.setCurrentPercentage(subtitle, percentage + deviation);
}
// Use percentages to recalculate the values
craftingValues.recalculateValues(false);
craftingValues.addExperimentalProperty("creatureLevel", "creatureLevel", level, level, 0, false);
craftingValues.setHidden("creatureLevel");
// Update the Tano with new values
prototype->updateCraftingValues(&craftingValues, true);
return prototype;
}
bool LootManagerImplementation::createLoot(SceneObject* container, AiAgent* creature) {
LootGroupCollection* lootCollection = creature->getLootGroups();
if (lootCollection == NULL)
return false;
for (int i = 0; i < lootCollection->count(); ++i) {
LootGroupCollectionEntry* entry = lootCollection->get(i);
int lootChance = entry->getLootChance();
if (lootChance <= 0)
continue;
int roll = System::random(10000000);
if (roll > lootChance)
continue;
int tempChance = 0; //Start at 0.
LootGroups* lootGroups = entry->getLootGroups();
//Select the loot group to use.
for (int i = 0; i < lootGroups->count(); ++i) {
LootGroupEntry* entry = lootGroups->get(i);
tempChance += entry->getLootChance();
//Is this entry lower than the roll? If yes, then we want to try the next entry.
if (tempChance < roll)
continue;
createLoot(container, entry->getLootGroupName(), creature->getLevel());
break;
}
}
return true;
}
bool LootManagerImplementation::createLoot(SceneObject* container, const String& lootGroup, int level) {
if (container->hasFullContainerObjects())
return false;
Reference<LootGroupTemplate*> group = lootGroupMap->getLootGroupTemplate(lootGroup);
if (group == NULL) {
warning("Loot group template requested does not exist: " + lootGroup);
return false;
}
//Now we do the second roll for the item out of the group.
int roll = System::random(10000000);
Reference<LootItemTemplate*> itemTemplate = lootGroupMap->getLootItemTemplate(group->getLootItemTemplateForRoll(roll));
if (itemTemplate == NULL) {
warning("Loot item template requested does not exist: " + group->getLootItemTemplateForRoll(roll) + " for templateName: " + group->getTemplateName());
return false;
}
TangibleObject* obj = createLootObject(itemTemplate, level);
if (obj == NULL)
return false;
if (container->transferObject(obj, -1, false))
container->broadcastObject(obj, true);
return true;
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "otbWrapperCommandLineLauncher.h"
#include "otb_tinyxml.h"
#include <vector>
#ifdef OTB_USE_MPI
#include "otbMPIConfig.h"
#endif
const std::string GetChildNodeTextOf(TiXmlElement *parentElement, std::string key);
std::string PrepareExpressionFromXML(std::string filename);
std::vector<std::string> PrepareVectorExpressionFromXML(std::string filename);
std::string CleanWord(const std::string & word);
std::string PrepareExpressionFromXML(std::string filename)
{
std::string expression;
if(filename.empty())
{
std::cerr <<"Input XML Filename is empty" << std::endl;
return expression;
}
std::string ext = filename.substr(filename.size()-4,filename.size());
if(ext != ".xml" )
std::cerr << ext << " is a wrong extension: Expected .xml " << __FILE__ << std::endl;
// Open the xml file
TiXmlDocument doc;
//Use itksys::SystemTools::FOpen() and close it below because
//TiXmlDocument::TiXmlFileOpen( ) is not exposed from tinyXML library. Even
//though its available in the TiXmlDocument::SaveFile().
FILE* fp = itksys::SystemTools::Fopen(filename.c_str(), "rb");
if (!doc.LoadFile(fp , TIXML_ENCODING_UTF8))
{
std::cerr << "Can't open file " << filename << std::endl;
fclose(fp);
exit(1);
}
TiXmlHandle handle(&doc);
TiXmlElement *n_OTB;
n_OTB = handle.FirstChild("OTB").Element();
if(!n_OTB)
{
std::string info = "Input XML file " + filename + " is invalid.";
std::cerr << info << std::endl;
fclose(fp);
exit(1);
}
TiXmlElement *n_AppNode = n_OTB->FirstChildElement("application");
std::string moduleName;
moduleName = GetChildNodeTextOf(n_AppNode, "name");
/*
AddMetaData("appname", app_Name);
app_Descr = this_->GetChildNodeTextOf(n_AppNode, "descr");
AddMetaData("appdescr", app_Descr);
TiXmlElement* n_Doc = n_AppNode->FirstChildElement("doc");
std::string doc_Name, doc_Descr, doc_Author, doc_Limitation, doc_SeeAlso;
doc_Name = this_->GetChildNodeTextOf(n_Doc, "name");
AddMetaData("docname", doc_Name);
doc_Descr = this_->GetChildNodeTextOf(n_Doc, "longdescr");
AddMetaData("doclongdescr", doc_Descr);
doc_Author = this_->GetChildNodeTextOf(n_Doc, "authors");
AddMetaData("docauthors", doc_Author);
doc_Limitation = this_->GetChildNodeTextOf(n_Doc, "limitations");
AddMetaData("doclimitations", doc_Limitation);
doc_SeeAlso = this_->GetChildNodeTextOf(n_Doc, "seealso");
AddMetaData("docseealso", doc_SeeAlso);
*/
expression.append(moduleName);
for( TiXmlElement* n_Parameter = n_AppNode->FirstChildElement("parameter"); n_Parameter != ITK_NULLPTR;
n_Parameter = n_Parameter->NextSiblingElement() )
{
std::string key="-";
key.append(GetChildNodeTextOf(n_Parameter, "key"));
TiXmlElement* n_Values = ITK_NULLPTR;
n_Values = n_Parameter->FirstChildElement("values");
if(n_Values)
{
std::string values;
for(TiXmlElement* n_Value = n_Values->FirstChildElement("value"); n_Value != ITK_NULLPTR;
n_Value = n_Value->NextSiblingElement())
{
values.append(n_Value->GetText());
values.append(" ");
}
values = values.substr(0,values.size()-1);
expression.append(" ");
expression.append(key);
expression.append(" ");
expression.append(values);
}
else
{
std::string value;
value = GetChildNodeTextOf(n_Parameter, "value");
expression.append(" ");
expression.append(key);
expression.append(" ");
expression.append(value);
std::string type = GetChildNodeTextOf(n_Parameter, "type");
if (type == "OutputImage")
{
std::string t = GetChildNodeTextOf(n_Parameter, "pixtype");
expression.append(" ");
expression.append(t);
}
}
}
fclose(fp);
return expression;
}
std::vector<std::string> PrepareVectorExpressionFromXML(std::string filename)
{
std::vector<std::string> expression;
if(filename.empty())
{
std::cerr <<"Input XML Filename is empty" << std::endl;
return expression;
}
std::string ext = filename.substr(filename.size()-4,filename.size());
if(ext != ".xml" )
std::cerr << ext << " is a wrong extension: Expected .xml " << __FILE__ << std::endl;
// Open the xml file
TiXmlDocument doc;
//Use itksys::SystemTools::FOpen() and close it below because
//TiXmlDocument::TiXmlFileOpen( ) is not exposed from tinyXML library. Even
//though its available in the TiXmlDocument::SaveFile().
FILE* fp = itksys::SystemTools::Fopen(filename.c_str(), "rb");
if (!doc.LoadFile(fp , TIXML_ENCODING_UTF8))
{
std::cerr << "Can't open file " << filename << std::endl;
fclose(fp);
exit(1);
}
TiXmlHandle handle(&doc);
TiXmlElement *n_OTB;
n_OTB = handle.FirstChild("OTB").Element();
if(!n_OTB)
{
std::string info = "Input XML file " + filename + " is invalid.";
std::cerr << info << std::endl;
fclose(fp);
exit(1);
}
TiXmlElement *n_AppNode = n_OTB->FirstChildElement("application");
std::string moduleName;
moduleName = GetChildNodeTextOf(n_AppNode, "name");
expression.push_back(CleanWord(moduleName));
for( TiXmlElement* n_Parameter = n_AppNode->FirstChildElement("parameter"); n_Parameter != ITK_NULLPTR;
n_Parameter = n_Parameter->NextSiblingElement() )
{
std::string key="-";
key.append(GetChildNodeTextOf(n_Parameter, "key"));
expression.push_back(CleanWord(key));
TiXmlElement* n_Values = ITK_NULLPTR;
n_Values = n_Parameter->FirstChildElement("values");
if(n_Values)
{
std::string values;
for(TiXmlElement* n_Value = n_Values->FirstChildElement("value"); n_Value != ITK_NULLPTR;
n_Value = n_Value->NextSiblingElement())
{
expression.push_back(CleanWord(n_Value->GetText()));
}
}
else
{
std::string value;
value = GetChildNodeTextOf(n_Parameter, "value");
expression.push_back(CleanWord(value));
std::string type = GetChildNodeTextOf(n_Parameter, "type");
if (type == "OutputImage")
{
std::string t = GetChildNodeTextOf(n_Parameter, "pixtype");
expression.push_back(CleanWord(t));
}
}
}
fclose(fp);
return expression;
}
std::string CleanWord(const std::string & word)
{
std::string res("");
// Suppress whitespace characters at the beginning and ending of the string
std::string::size_type cleanStart = word.find_first_not_of(" \t");
std::string::size_type cleanEnd = word.find_last_not_of(" \t\f\v\n\r");
if (cleanEnd != std::string::npos)
{
res = word.substr(cleanStart,cleanEnd+1);
}
return res;
}
int main(int argc, char* argv[])
{
#ifdef OTB_USE_MPI
otb::MPIConfig::Instance()->Init(argc,argv);
#endif
if (argc < 2)
{
std::cerr << "Usage : " << argv[0] << " module_name [MODULEPATH] [arguments]" << std::endl;
return EXIT_FAILURE;
}
std::vector<std::string> vexp;
std::string exp;
if (strcmp(argv[1], "-inxml") == 0)
{
//exp = PrepareExpressionFromXML(argv[2]);
vexp = PrepareVectorExpressionFromXML(argv[2]);
}
else
{
// Construct the string expression
for (int i = 1; i < argc; i++)
{
/*if (i != argc - 1)
{
exp.append(argv[i]);
exp.append(" ");
}
else
{
exp.append(argv[i]);
}*/
std::string strarg(argv[i]);
std::string cleanArg = CleanWord(strarg);
if (cleanArg.empty())
{
// Empty argument !
continue;
}
vexp.push_back(cleanArg);
}
}
// std::cerr << exp << ":\n";
typedef otb::Wrapper::CommandLineLauncher LauncherType;
LauncherType::Pointer launcher = LauncherType::New();
//if (launcher->Load(exp) == true)
if (launcher->Load(vexp) == true)
{
if (launcher->ExecuteAndWriteOutput() == false)
{
return EXIT_FAILURE;
}
}
else
{
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
const std::string GetChildNodeTextOf(TiXmlElement *parentElement, std::string key)
{
std::string value="";
if(parentElement)
{
TiXmlElement* childElement = ITK_NULLPTR;
childElement = parentElement->FirstChildElement(key.c_str());
//same as childElement->GetText() does but that call is failing if there is
//no such node.
//but the below code works and is a replacement for GetText()
if(childElement)
{
const TiXmlNode* child = childElement->FirstChild();
if ( child )
{
const TiXmlText* childText = child->ToText();
if ( childText )
{
value = childText->Value();
}
}
}
}
return value;
}
<commit_msg>BUG: Fix trailing whitespace trimming in otbApplicationLauncherCommandLine (kindly provided by Laurentiu Nicola)<commit_after>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "otbWrapperCommandLineLauncher.h"
#include "otb_tinyxml.h"
#include <vector>
#ifdef OTB_USE_MPI
#include "otbMPIConfig.h"
#endif
const std::string GetChildNodeTextOf(TiXmlElement *parentElement, std::string key);
std::string PrepareExpressionFromXML(std::string filename);
std::vector<std::string> PrepareVectorExpressionFromXML(std::string filename);
std::string CleanWord(const std::string & word);
std::string PrepareExpressionFromXML(std::string filename)
{
std::string expression;
if(filename.empty())
{
std::cerr <<"Input XML Filename is empty" << std::endl;
return expression;
}
std::string ext = filename.substr(filename.size()-4,filename.size());
if(ext != ".xml" )
std::cerr << ext << " is a wrong extension: Expected .xml " << __FILE__ << std::endl;
// Open the xml file
TiXmlDocument doc;
//Use itksys::SystemTools::FOpen() and close it below because
//TiXmlDocument::TiXmlFileOpen( ) is not exposed from tinyXML library. Even
//though its available in the TiXmlDocument::SaveFile().
FILE* fp = itksys::SystemTools::Fopen(filename.c_str(), "rb");
if (!doc.LoadFile(fp , TIXML_ENCODING_UTF8))
{
std::cerr << "Can't open file " << filename << std::endl;
fclose(fp);
exit(1);
}
TiXmlHandle handle(&doc);
TiXmlElement *n_OTB;
n_OTB = handle.FirstChild("OTB").Element();
if(!n_OTB)
{
std::string info = "Input XML file " + filename + " is invalid.";
std::cerr << info << std::endl;
fclose(fp);
exit(1);
}
TiXmlElement *n_AppNode = n_OTB->FirstChildElement("application");
std::string moduleName;
moduleName = GetChildNodeTextOf(n_AppNode, "name");
/*
AddMetaData("appname", app_Name);
app_Descr = this_->GetChildNodeTextOf(n_AppNode, "descr");
AddMetaData("appdescr", app_Descr);
TiXmlElement* n_Doc = n_AppNode->FirstChildElement("doc");
std::string doc_Name, doc_Descr, doc_Author, doc_Limitation, doc_SeeAlso;
doc_Name = this_->GetChildNodeTextOf(n_Doc, "name");
AddMetaData("docname", doc_Name);
doc_Descr = this_->GetChildNodeTextOf(n_Doc, "longdescr");
AddMetaData("doclongdescr", doc_Descr);
doc_Author = this_->GetChildNodeTextOf(n_Doc, "authors");
AddMetaData("docauthors", doc_Author);
doc_Limitation = this_->GetChildNodeTextOf(n_Doc, "limitations");
AddMetaData("doclimitations", doc_Limitation);
doc_SeeAlso = this_->GetChildNodeTextOf(n_Doc, "seealso");
AddMetaData("docseealso", doc_SeeAlso);
*/
expression.append(moduleName);
for( TiXmlElement* n_Parameter = n_AppNode->FirstChildElement("parameter"); n_Parameter != ITK_NULLPTR;
n_Parameter = n_Parameter->NextSiblingElement() )
{
std::string key="-";
key.append(GetChildNodeTextOf(n_Parameter, "key"));
TiXmlElement* n_Values = ITK_NULLPTR;
n_Values = n_Parameter->FirstChildElement("values");
if(n_Values)
{
std::string values;
for(TiXmlElement* n_Value = n_Values->FirstChildElement("value"); n_Value != ITK_NULLPTR;
n_Value = n_Value->NextSiblingElement())
{
values.append(n_Value->GetText());
values.append(" ");
}
values = values.substr(0,values.size()-1);
expression.append(" ");
expression.append(key);
expression.append(" ");
expression.append(values);
}
else
{
std::string value;
value = GetChildNodeTextOf(n_Parameter, "value");
expression.append(" ");
expression.append(key);
expression.append(" ");
expression.append(value);
std::string type = GetChildNodeTextOf(n_Parameter, "type");
if (type == "OutputImage")
{
std::string t = GetChildNodeTextOf(n_Parameter, "pixtype");
expression.append(" ");
expression.append(t);
}
}
}
fclose(fp);
return expression;
}
std::vector<std::string> PrepareVectorExpressionFromXML(std::string filename)
{
std::vector<std::string> expression;
if(filename.empty())
{
std::cerr <<"Input XML Filename is empty" << std::endl;
return expression;
}
std::string ext = filename.substr(filename.size()-4,filename.size());
if(ext != ".xml" )
std::cerr << ext << " is a wrong extension: Expected .xml " << __FILE__ << std::endl;
// Open the xml file
TiXmlDocument doc;
//Use itksys::SystemTools::FOpen() and close it below because
//TiXmlDocument::TiXmlFileOpen( ) is not exposed from tinyXML library. Even
//though its available in the TiXmlDocument::SaveFile().
FILE* fp = itksys::SystemTools::Fopen(filename.c_str(), "rb");
if (!doc.LoadFile(fp , TIXML_ENCODING_UTF8))
{
std::cerr << "Can't open file " << filename << std::endl;
fclose(fp);
exit(1);
}
TiXmlHandle handle(&doc);
TiXmlElement *n_OTB;
n_OTB = handle.FirstChild("OTB").Element();
if(!n_OTB)
{
std::string info = "Input XML file " + filename + " is invalid.";
std::cerr << info << std::endl;
fclose(fp);
exit(1);
}
TiXmlElement *n_AppNode = n_OTB->FirstChildElement("application");
std::string moduleName;
moduleName = GetChildNodeTextOf(n_AppNode, "name");
expression.push_back(CleanWord(moduleName));
for( TiXmlElement* n_Parameter = n_AppNode->FirstChildElement("parameter"); n_Parameter != ITK_NULLPTR;
n_Parameter = n_Parameter->NextSiblingElement() )
{
std::string key="-";
key.append(GetChildNodeTextOf(n_Parameter, "key"));
expression.push_back(CleanWord(key));
TiXmlElement* n_Values = ITK_NULLPTR;
n_Values = n_Parameter->FirstChildElement("values");
if(n_Values)
{
std::string values;
for(TiXmlElement* n_Value = n_Values->FirstChildElement("value"); n_Value != ITK_NULLPTR;
n_Value = n_Value->NextSiblingElement())
{
expression.push_back(CleanWord(n_Value->GetText()));
}
}
else
{
std::string value;
value = GetChildNodeTextOf(n_Parameter, "value");
expression.push_back(CleanWord(value));
std::string type = GetChildNodeTextOf(n_Parameter, "type");
if (type == "OutputImage")
{
std::string t = GetChildNodeTextOf(n_Parameter, "pixtype");
expression.push_back(CleanWord(t));
}
}
}
fclose(fp);
return expression;
}
std::string CleanWord(const std::string & word)
{
std::string res("");
// Suppress whitespace characters at the beginning and ending of the string
std::string::size_type cleanStart = word.find_first_not_of(" \t");
std::string::size_type cleanEnd = word.find_last_not_of(" \t\f\v\n\r");
// cleanStart == npos implies cleanEnd == npos
if (cleanEnd != std::string::npos)
{
res = word.substr(cleanStart, cleanEnd - cleanStart + 1);
}
return res;
}
int main(int argc, char* argv[])
{
#ifdef OTB_USE_MPI
otb::MPIConfig::Instance()->Init(argc,argv);
#endif
if (argc < 2)
{
std::cerr << "Usage : " << argv[0] << " module_name [MODULEPATH] [arguments]" << std::endl;
return EXIT_FAILURE;
}
std::vector<std::string> vexp;
std::string exp;
if (strcmp(argv[1], "-inxml") == 0)
{
//exp = PrepareExpressionFromXML(argv[2]);
vexp = PrepareVectorExpressionFromXML(argv[2]);
}
else
{
// Construct the string expression
for (int i = 1; i < argc; i++)
{
/*if (i != argc - 1)
{
exp.append(argv[i]);
exp.append(" ");
}
else
{
exp.append(argv[i]);
}*/
std::string strarg(argv[i]);
std::string cleanArg = CleanWord(strarg);
if (cleanArg.empty())
{
// Empty argument !
continue;
}
vexp.push_back(cleanArg);
}
}
// std::cerr << exp << ":\n";
typedef otb::Wrapper::CommandLineLauncher LauncherType;
LauncherType::Pointer launcher = LauncherType::New();
//if (launcher->Load(exp) == true)
if (launcher->Load(vexp) == true)
{
if (launcher->ExecuteAndWriteOutput() == false)
{
return EXIT_FAILURE;
}
}
else
{
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
const std::string GetChildNodeTextOf(TiXmlElement *parentElement, std::string key)
{
std::string value="";
if(parentElement)
{
TiXmlElement* childElement = ITK_NULLPTR;
childElement = parentElement->FirstChildElement(key.c_str());
//same as childElement->GetText() does but that call is failing if there is
//no such node.
//but the below code works and is a replacement for GetText()
if(childElement)
{
const TiXmlNode* child = childElement->FirstChild();
if ( child )
{
const TiXmlText* childText = child->ToText();
if ( childText )
{
value = childText->Value();
}
}
}
}
return value;
}
<|endoftext|> |
<commit_before>/* -*- mode: c++; c-default-style: "google"; indent-tabs-mode: nil -*- */
/* -------------------------------------------------------------------------
ATS
License: see $ATS_DIR/COPYRIGHT
Author: Ethan Coon
Standard base for most PKs, this combines both domains/meshes of
PKPhysicalBase and BDF methods of PKBDFBase.
------------------------------------------------------------------------- */
#include "boost/math/special_functions/fpclassify.hpp"
#include "pk_physical_bdf_base.hh"
namespace Amanzi {
// -----------------------------------------------------------------------------
// Setup
// -----------------------------------------------------------------------------
void PKPhysicalBDFBase::setup(const Teuchos::Ptr<State>& S) {
// call the meat of the base constructurs via Setup methods
PKPhysicalBase::setup(S);
PKBDFBase::setup(S);
// convergence criteria
atol_ = plist_.get<double>("absolute error tolerance",1.0);
rtol_ = plist_.get<double>("relative error tolerance",1.0);
atol0_ = atol_;
rtol0_ = rtol_;
// adapt the tolerances to fit the timestep
adapt_tols_to_h_ = plist_.get<bool>("adapt tolerances to timestep", "false");
if (adapt_tols_to_h_) {
min_tol_h_ = plist_.get<double>("cutoff timestep for adaptive tolerance", 100.0);
}
// continuation to steady state enables a gradually shrinking atol/rtol
continuation_to_ss_ = plist_.get<bool>("continuation to steady state", false);
};
// -----------------------------------------------------------------------------
// initialize. Note both BDFBase and PhysicalBase have initialize()
// methods, so we need a unique overrider.
// -----------------------------------------------------------------------------
void PKPhysicalBDFBase::initialize(const Teuchos::Ptr<State>& S) {
// Just calls both subclass's initialize. NOTE - order is important here --
// PhysicalBase grabs the primary variable and stuffs it into the solution,
// which must be done prior to BDFBase initializing the timestepper.
PKPhysicalBase::initialize(S);
PKBDFBase::initialize(S);
}
// -----------------------------------------------------------------------------
// Default enorm that uses an abs and rel tolerance to monitor convergence.
// -----------------------------------------------------------------------------
double PKPhysicalBDFBase::enorm(Teuchos::RCP<const TreeVector> u,
Teuchos::RCP<const TreeVector> du) {
// VerboseObject stuff.
Teuchos::OSTab tab = getOSTab();
if (out_.get() && includesVerbLevel(verbosity_, Teuchos::VERB_HIGH, true)) {
*out_ << "ENorm (Infnorm) of: " << name_ << ": ";
}
// adapt tolerances if needed
if (adapt_tols_to_h_) {
double h = S_next_->time() - S_inter_->time();
atol_ = atol0_ / h;
rtol_ = rtol0_ / h;
}
// continue tolerances if needed
if (continuation_to_ss_) {
atol_ = atol0_ + 1.e5*atol0_/(1.0 + S_next_->time());
rtol_ = rtol0_ + 1.e5*rtol0_/(1.0 + S_next_->time());
}
Teuchos::RCP<const CompositeVector> vec = u->data();
Teuchos::RCP<const CompositeVector> dvec = du->data();
double enorm_val = 0.0;
for (CompositeVector::name_iterator comp=vec->begin();
comp!=vec->end(); ++comp) {
double enorm_comp = 0.0;
double infnorm_comp = 0.0;
for (int id=0; id!=vec->size(*comp,false); ++id) {
if (boost::math::isnan<double>((*dvec)(*comp,id))) {
std::cout << "Cutting time step due to NaN in correction." << std::endl;
Errors::Message m("Cut time step");
Exceptions::amanzi_throw(m);
}
double tmp = abs((*dvec)(*comp,id)) / (atol_+rtol_*abs((*vec)(*comp,id)));
enorm_comp = std::max<double>(enorm_comp, tmp);
infnorm_comp = std::max<double>(infnorm_comp, abs((*dvec)(*comp,id)));
}
if (out_.get() && includesVerbLevel(verbosity_, Teuchos::VERB_HIGH, true)) {
*out_ << *comp << " = " << enorm_comp << " (" << infnorm_comp << ") ";
}
enorm_val = std::max<double>(enorm_val, enorm_comp);
}
if (out_.get() && includesVerbLevel(verbosity_, Teuchos::VERB_HIGH, true)) {
*out_ << std::endl;
}
#ifdef HAVE_MPI
double buf = enorm_val;
MPI_Allreduce(&buf, &enorm_val, 1, MPI_DOUBLE, MPI_MAX, MPI_COMM_WORLD);
#endif
return enorm_val;
};
// -----------------------------------------------------------------------------
// Experimental approach -- we must pull out S_next_'s solution_evaluator_ to
// stay current for changed_solution()
// -----------------------------------------------------------------------------
void PKPhysicalBDFBase::set_states(const Teuchos::RCP<const State>& S,
const Teuchos::RCP<State>& S_inter,
const Teuchos::RCP<State>& S_next) {
PKDefaultBase::set_states(S, S_inter, S_next);
Teuchos::RCP<FieldEvaluator> fm = S_next->GetFieldEvaluator(key_);
#if ENABLE_DBC
solution_evaluator_ = Teuchos::rcp_dynamic_cast<PrimaryVariableFieldEvaluator>(fm);
ASSERT(solution_evaluator_ != Teuchos::null);
#else
solution_evaluator_ = Teuchos::rcp_static_cast<PrimaryVariableFieldEvaluator>(fm);
#endif
changed_solution();
};
// -----------------------------------------------------------------------------
// Experimental approach -- calling this indicates that the time
// integration scheme is changing the value of the solution in
// state.
// -----------------------------------------------------------------------------
void PKPhysicalBDFBase::changed_solution() {
solution_evaluator_->SetFieldAsChanged();
};
} // namespace
<commit_msg>cleanup for reporting norms in parallel case<commit_after>/* -*- mode: c++; c-default-style: "google"; indent-tabs-mode: nil -*- */
/* -------------------------------------------------------------------------
ATS
License: see $ATS_DIR/COPYRIGHT
Author: Ethan Coon
Standard base for most PKs, this combines both domains/meshes of
PKPhysicalBase and BDF methods of PKBDFBase.
------------------------------------------------------------------------- */
#include "boost/math/special_functions/fpclassify.hpp"
#include "pk_physical_bdf_base.hh"
namespace Amanzi {
// -----------------------------------------------------------------------------
// Setup
// -----------------------------------------------------------------------------
void PKPhysicalBDFBase::setup(const Teuchos::Ptr<State>& S) {
// call the meat of the base constructurs via Setup methods
PKPhysicalBase::setup(S);
PKBDFBase::setup(S);
// convergence criteria
atol_ = plist_.get<double>("absolute error tolerance",1.0);
rtol_ = plist_.get<double>("relative error tolerance",1.0);
atol0_ = atol_;
rtol0_ = rtol_;
// adapt the tolerances to fit the timestep
adapt_tols_to_h_ = plist_.get<bool>("adapt tolerances to timestep", "false");
if (adapt_tols_to_h_) {
min_tol_h_ = plist_.get<double>("cutoff timestep for adaptive tolerance", 100.0);
}
// continuation to steady state enables a gradually shrinking atol/rtol
continuation_to_ss_ = plist_.get<bool>("continuation to steady state", false);
};
// -----------------------------------------------------------------------------
// initialize. Note both BDFBase and PhysicalBase have initialize()
// methods, so we need a unique overrider.
// -----------------------------------------------------------------------------
void PKPhysicalBDFBase::initialize(const Teuchos::Ptr<State>& S) {
// Just calls both subclass's initialize. NOTE - order is important here --
// PhysicalBase grabs the primary variable and stuffs it into the solution,
// which must be done prior to BDFBase initializing the timestepper.
PKPhysicalBase::initialize(S);
PKBDFBase::initialize(S);
}
// -----------------------------------------------------------------------------
// Default enorm that uses an abs and rel tolerance to monitor convergence.
// -----------------------------------------------------------------------------
double PKPhysicalBDFBase::enorm(Teuchos::RCP<const TreeVector> u,
Teuchos::RCP<const TreeVector> du) {
// VerboseObject stuff.
Teuchos::OSTab tab = getOSTab();
if (out_.get() && includesVerbLevel(verbosity_, Teuchos::VERB_HIGH, true)) {
*out_ << "ENorm (Infnorm) of: " << name_ << ": ";
}
// adapt tolerances if needed
if (adapt_tols_to_h_) {
double h = S_next_->time() - S_inter_->time();
atol_ = atol0_ / h;
rtol_ = rtol0_ / h;
}
// continue tolerances if needed
if (continuation_to_ss_) {
atol_ = atol0_ + 1.e5*atol0_/(1.0 + S_next_->time());
rtol_ = rtol0_ + 1.e5*rtol0_/(1.0 + S_next_->time());
}
Teuchos::RCP<const CompositeVector> vec = u->data();
Teuchos::RCP<const CompositeVector> dvec = du->data();
double enorm_val = 0.0;
for (CompositeVector::name_iterator comp=vec->begin();
comp!=vec->end(); ++comp) {
double enorm_comp = 0.0;
for (int id=0; id!=vec->size(*comp,false); ++id) {
if (boost::math::isnan<double>((*dvec)(*comp,id))) {
std::cout << "Cutting time step due to NaN in correction." << std::endl;
Errors::Message m("Cut time step");
Exceptions::amanzi_throw(m);
}
double tmp = abs((*dvec)(*comp,id)) / (atol_+rtol_*abs((*vec)(*comp,id)));
enorm_comp = std::max<double>(enorm_comp, tmp);
}
if (out_.get() && includesVerbLevel(verbosity_, Teuchos::VERB_HIGH, true)) {
double buf(0.);
MPI_Allreduce(&enorm_comp, &buf, 1, MPI_DOUBLE, MPI_MAX, MPI_COMM_WORLD);
double infnorm_comp;
dvec->ViewComponent(*comp,false)->NormInf(&infnorm_comp);
*out_ << *comp << " = " << buf << " (" << infnorm_comp << ") ";
}
enorm_val = std::max<double>(enorm_val, enorm_comp);
}
if (out_.get() && includesVerbLevel(verbosity_, Teuchos::VERB_HIGH, true)) {
*out_ << std::endl;
}
#ifdef HAVE_MPI
double buf = enorm_val;
MPI_Allreduce(&buf, &enorm_val, 1, MPI_DOUBLE, MPI_MAX, MPI_COMM_WORLD);
#endif
return enorm_val;
};
// -----------------------------------------------------------------------------
// Experimental approach -- we must pull out S_next_'s solution_evaluator_ to
// stay current for changed_solution()
// -----------------------------------------------------------------------------
void PKPhysicalBDFBase::set_states(const Teuchos::RCP<const State>& S,
const Teuchos::RCP<State>& S_inter,
const Teuchos::RCP<State>& S_next) {
PKDefaultBase::set_states(S, S_inter, S_next);
Teuchos::RCP<FieldEvaluator> fm = S_next->GetFieldEvaluator(key_);
#if ENABLE_DBC
solution_evaluator_ = Teuchos::rcp_dynamic_cast<PrimaryVariableFieldEvaluator>(fm);
ASSERT(solution_evaluator_ != Teuchos::null);
#else
solution_evaluator_ = Teuchos::rcp_static_cast<PrimaryVariableFieldEvaluator>(fm);
#endif
changed_solution();
};
// -----------------------------------------------------------------------------
// Experimental approach -- calling this indicates that the time
// integration scheme is changing the value of the solution in
// state.
// -----------------------------------------------------------------------------
void PKPhysicalBDFBase::changed_solution() {
solution_evaluator_->SetFieldAsChanged();
};
} // namespace
<|endoftext|> |
<commit_before>#include "stdafx.h"
#include "LocalTables.h"
using namespace std;
void LocalTables::init(std::function<int(const Motif&)> fn, double LB)
{
fnGetNParents = fn;
lowerBound = LB;
candidateTables.reserve(16);
nActLevel.reserve(16);
nActLevelTotal.reserve(16);
}
void LocalTables::update(const Motif & m, const double newUB, const int num)
{
int l = m.getnEdge();
lock_guard<mutex> lg(mct);
// add new level
if(static_cast<int>(candidateTables.size()) <= l ) {
size_t len = max(candidateTables.size(), nActLevel.size());
len = max<size_t>(len, l + 1);
candidateTables.resize(len);
lock_guard<mutex> lga(mat);
nActLevel.resize(len);
nActLevelTotal.resize(len);
}
// update the num. left for activation
CT_t& ct = candidateTables[l];
auto it = ct.find(m);
if(it == ct.end()) {
// the max(0,...) here is for the special case where fnGetNParents(m)-num < 0
int np = max(0, fnGetNParents(m) - num);
it = ct.insert(make_pair(move(m), make_pair(newUB, np))).first;
} else {
it->second.first = min(it->second.first, newUB);
it->second.second -= num;
}
// move a motif from candiate to active
if(it->second.second == 0) {
if(it->second.first >= lowerBound) {
lock_guard<mutex> lga(mat);
activatedTable.push_back(make_pair(move(it->first), it->second.first));
++nActLevel[l];
++nActLevelTotal[l];
}
// Special Case: when using estimated num. parents algorithm:
// #-left may be negative. If remove it the first time, it may be activated again.
// Therefore, instead of remove it, I set its #-left to a very large number.
// TODO: distinguish the method for calculating num. partents, exact type & estimated type
//ct.erase(it);
it->second.second = numeric_limits<int>::max();
}
}
void LocalTables::addToActivated(const Motif & m, const double newUB)
{
int l = m.getnEdge();
lock_guard<mutex> lga(mat);
// add new level
if(static_cast<int>(nActLevel.size()) <= l) {
size_t len = max<size_t>(nActLevel.size(), l + 1);
nActLevel.resize(len);
nActLevelTotal.resize(len);
}
activatedTable.push_back(make_pair(m, newUB));
++nActLevel[l];
++nActLevelTotal[l];
}
void LocalTables::sortUp(const int l)
{
lock_guard<mutex> lg(mct);
size_t end = min(static_cast<size_t>(l + 1 + 1), candidateTables.size());
// first +1 : clear the CT of level l+1 ; second +1 : loop in [x,x) manner
for(size_t i = 1; i < end; ++i) {
candidateTables[i].clear();
}
}
int LocalTables::updateLowerBound(double newLB)
{
if(lowerBound >= newLB)
return 0;
lowerBound = newLB;
lock_guard<mutex> lg(mat);
size_t s0 = activatedTable.size();
auto it = activatedTable.begin();
while(it != activatedTable.end()) {
if(it->second < lowerBound) {
--nActLevel[it->first.getnEdge()];
it = activatedTable.erase(it);
} else {
++it;
}
}
return s0 - activatedTable.size();
}
std::pair<bool, std::pair<Motif, double>> LocalTables::getOne()
{
if(activatedTable.empty()) {
return make_pair(false, make_pair(Motif(), 0.0));
}
lock_guard<mutex> lg(mat);
if(activatedTable.empty()) {
return make_pair(false, make_pair(Motif(), 0.0));
}
auto mu = move(activatedTable.front());
--nActLevel[mu.first.getnEdge()];
activatedTable.pop_front();
return make_pair(true, move(mu));
}
int LocalTables::mostRecentLevel() const
{
return candidateTables.size() - 1;
}
bool LocalTables::emptyCandidate() const
{
for(size_t i = 0; i < candidateTables.size(); ++i) {
if(emptyCandidate(i))
return true;
}
return false;
}
bool LocalTables::emptyCandidate(const int level) const
{
return static_cast<int>(candidateTables.size()) > level
&& candidateTables[level].empty();
}
bool LocalTables::emptyActivated() const
{
return activatedTable.empty();
}
bool LocalTables::emptyActivated(const int level) const
{
return static_cast<int>(nActLevel.size()) > level
&& nActLevel[level] == 0;
}
int LocalTables::getNumCandidate() const
{
int res = 0;
size_t n = candidateTables.size();
for(size_t i = 0; i < n; ++i)
res += candidateTables[i].size();
return res;
}
std::vector<int> LocalTables::getNumCandidates() const
{
size_t n = candidateTables.size();
std::vector<int> res(n);
for(size_t i = 0; i < n; ++i)
res[i] = candidateTables[i].size();
return res;
}
int LocalTables::getNumCandidate(const int level) const
{
return static_cast<int>(candidateTables.size()) > level
? candidateTables[level].size() : 0;
}
int LocalTables::getNumActive() const
{
return activatedTable.size();
}
std::vector<int> LocalTables::getNumActives() const
{
return nActLevel;
}
int LocalTables::getNumActive(const int level) const
{
return static_cast<int>(nActLevel.size()) > level
? nActLevel[level] : 0;
}
int LocalTables::getNumEverActive(const int level) const
{
return static_cast<int>(nActLevelTotal.size()) > level ?
nActLevelTotal[level] : 0;
}
bool LocalTables::empty() const
{
unique_lock<mutex> ulc(mct, defer_lock);
unique_lock<mutex> ula(mat, defer_lock);
lock(ulc, ula);
if(activatedTable.empty()) {
for(auto& ct : candidateTables)
if(!ct.empty())
return false;
return true;
}
return false;
}
bool LocalTables::empty(const int level) const
{
unique_lock<mutex> ulc(mct, defer_lock);
unique_lock<mutex> ula(mat, defer_lock);
lock(ulc, ula);
return candidateTables[level].empty() && nActLevel[level] == 0;
}
<commit_msg>fix an over optimization in local table<commit_after>#include "stdafx.h"
#include "LocalTables.h"
using namespace std;
void LocalTables::init(std::function<int(const Motif&)> fn, double LB)
{
fnGetNParents = fn;
lowerBound = LB;
candidateTables.reserve(16);
nActLevel.reserve(16);
nActLevelTotal.reserve(16);
}
void LocalTables::update(const Motif & m, const double newUB, const int num)
{
int l = m.getnEdge();
lock_guard<mutex> lg(mct);
// add new level
if(static_cast<int>(candidateTables.size()) <= l ) {
size_t len = max(candidateTables.size(), nActLevel.size());
len = max<size_t>(len, l + 1);
candidateTables.resize(len);
lock_guard<mutex> lga(mat);
nActLevel.resize(len);
nActLevelTotal.resize(len);
}
// update the num. left for activation
CT_t& ct = candidateTables[l];
auto it = ct.find(m);
if(it == ct.end()) {
// the max(0,...) here is for the special case where fnGetNParents(m)-num < 0
int np = max(0, fnGetNParents(m) - num);
it = ct.insert(make_pair(move(m), make_pair(newUB, np))).first;
} else {
it->second.first = min(it->second.first, newUB);
it->second.second -= num;
}
// move a motif from candiate to active
if(it->second.second == 0) {
if(it->second.first >= lowerBound) {
lock_guard<mutex> lga(mat);
activatedTable.push_back(make_pair(move(it->first), it->second.first));
++nActLevel[l];
++nActLevelTotal[l];
}
// Special Case: when using estimated num. parents algorithm:
// #-left may be negative. If remove it the first time, it may be activated again.
// Therefore, instead of remove it, I set its #-left to a very large number.
// TODO: distinguish the method for calculating num. partents, exact type & estimated type
//ct.erase(it);
it->second.second = numeric_limits<int>::max();
}
}
void LocalTables::addToActivated(const Motif & m, const double newUB)
{
int l = m.getnEdge();
lock_guard<mutex> lga(mat);
// add new level
if(static_cast<int>(nActLevel.size()) <= l) {
size_t len = max<size_t>(nActLevel.size(), l + 1);
nActLevel.resize(len);
nActLevelTotal.resize(len);
}
activatedTable.push_back(make_pair(m, newUB));
++nActLevel[l];
++nActLevelTotal[l];
}
void LocalTables::sortUp(const int l)
{
lock_guard<mutex> lg(mct);
size_t end = min(static_cast<size_t>(l + 1), candidateTables.size());
// l+1 : loop in [x,x) manner
for(size_t i = 1; i < end; ++i) {
candidateTables[i].clear();
}
}
int LocalTables::updateLowerBound(double newLB)
{
if(lowerBound >= newLB)
return 0;
lowerBound = newLB;
lock_guard<mutex> lg(mat);
size_t s0 = activatedTable.size();
auto it = activatedTable.begin();
while(it != activatedTable.end()) {
if(it->second < lowerBound) {
--nActLevel[it->first.getnEdge()];
it = activatedTable.erase(it);
} else {
++it;
}
}
return s0 - activatedTable.size();
}
std::pair<bool, std::pair<Motif, double>> LocalTables::getOne()
{
if(activatedTable.empty()) {
return make_pair(false, make_pair(Motif(), 0.0));
}
lock_guard<mutex> lg(mat);
if(activatedTable.empty()) {
return make_pair(false, make_pair(Motif(), 0.0));
}
auto mu = move(activatedTable.front());
--nActLevel[mu.first.getnEdge()];
activatedTable.pop_front();
return make_pair(true, move(mu));
}
int LocalTables::mostRecentLevel() const
{
return candidateTables.size() - 1;
}
bool LocalTables::emptyCandidate() const
{
for(size_t i = 0; i < candidateTables.size(); ++i) {
if(emptyCandidate(i))
return true;
}
return false;
}
bool LocalTables::emptyCandidate(const int level) const
{
return static_cast<int>(candidateTables.size()) > level
&& candidateTables[level].empty();
}
bool LocalTables::emptyActivated() const
{
return activatedTable.empty();
}
bool LocalTables::emptyActivated(const int level) const
{
return static_cast<int>(nActLevel.size()) > level
&& nActLevel[level] == 0;
}
int LocalTables::getNumCandidate() const
{
int res = 0;
size_t n = candidateTables.size();
for(size_t i = 0; i < n; ++i)
res += candidateTables[i].size();
return res;
}
std::vector<int> LocalTables::getNumCandidates() const
{
size_t n = candidateTables.size();
std::vector<int> res(n);
for(size_t i = 0; i < n; ++i)
res[i] = candidateTables[i].size();
return res;
}
int LocalTables::getNumCandidate(const int level) const
{
return static_cast<int>(candidateTables.size()) > level
? candidateTables[level].size() : 0;
}
int LocalTables::getNumActive() const
{
return activatedTable.size();
}
std::vector<int> LocalTables::getNumActives() const
{
return nActLevel;
}
int LocalTables::getNumActive(const int level) const
{
return static_cast<int>(nActLevel.size()) > level
? nActLevel[level] : 0;
}
int LocalTables::getNumEverActive(const int level) const
{
return static_cast<int>(nActLevelTotal.size()) > level ?
nActLevelTotal[level] : 0;
}
bool LocalTables::empty() const
{
unique_lock<mutex> ulc(mct, defer_lock);
unique_lock<mutex> ula(mat, defer_lock);
lock(ulc, ula);
if(activatedTable.empty()) {
for(auto& ct : candidateTables)
if(!ct.empty())
return false;
return true;
}
return false;
}
bool LocalTables::empty(const int level) const
{
unique_lock<mutex> ulc(mct, defer_lock);
unique_lock<mutex> ula(mat, defer_lock);
lock(ulc, ula);
return candidateTables[level].empty() && nActLevel[level] == 0;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: syshelp.cxx,v $
*
* $Revision: 1.12 $
*
* last change: $Author: hr $ $Date: 2007-11-02 12:55:32 $
*
* 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 <syshelp.hxx>
// NOT FULLY DEFINED SERVICES
#include <string.h>
#include "sistr.hxx"
#include "list.hxx"
#ifdef WNT
#include <io.h>
#elif defined(UNX) || defined(OS2)
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#define stricmp strcasecmp
#else
#error Must run under unix or windows, please define UNX or WNT.
#endif
char C_sSpaceInName[] = " ";
void
WriteName( std::ostream & o_rFile,
const Simstr & i_rIdlDocuBaseDir,
const Simstr & i_rName,
E_LinkType i_eLinkType )
{
if (i_rName.l() == 0)
return;
const char * pNameEnd = strstr( i_rName.str(), " in " );
// No link:
if ( i_eLinkType == lt_nolink )
{
if ( pNameEnd != 0 )
{
const char * pStart = i_rName.str();
o_rFile.write( pStart, pNameEnd - pStart );
WriteStr( o_rFile, C_sSpaceInName );
WriteStr( o_rFile, pNameEnd );
}
else
{
WriteStr( o_rFile, i_rName );
}
return;
}
if ( i_eLinkType == lt_idl )
{
Simstr sPath(i_rName);
sPath.replace_all('.','/');
int nNameEnd = sPath.pos_first(' ');
int nPathStart = sPath.pos_last(' ');
WriteStr( o_rFile, "<A HREF=\"" );
if ( nNameEnd > -1 )
{
WriteStr( o_rFile, "file:///" );
WriteStr( o_rFile, i_rIdlDocuBaseDir );
WriteStr( o_rFile, "/" );
WriteStr( o_rFile, sPath.str() + 1 + nPathStart );
WriteStr( o_rFile, "/" );
o_rFile.write( sPath.str(), nNameEnd );
WriteStr( o_rFile, ".html\">" );
}
else
{ // Should not be reached:
WriteStr(o_rFile, i_rName);
return;
}
}
else if ( i_eLinkType == lt_html )
{
int nKomma = i_rName.pos_first(',');
int nEnd = i_rName.pos_first(' ');
if ( nKomma > -1 )
{
o_rFile.write( i_rName.str(), nKomma );
WriteStr( o_rFile, ": " );
WriteStr( o_rFile, "<A HREF=\"" );
o_rFile.write( i_rName.str(), nKomma );
WriteStr( o_rFile, ".html#" );
if ( nEnd > -1 )
o_rFile.write( i_rName.str() + nKomma + 1, nEnd - nKomma );
else
WriteStr( o_rFile, i_rName.str() + nKomma + 1 );
WriteStr( o_rFile, "\">" );
o_rFile.write( i_rName.str() + nKomma + 1, nEnd - nKomma );
}
else
{
WriteStr( o_rFile, "<A HREF=\"" );
WriteStr( o_rFile, i_rName );
WriteStr( o_rFile, ".html\">" );
WriteStr( o_rFile, i_rName );
}
WriteStr( o_rFile, "</A>" );
return;
}
if ( pNameEnd != 0 )
{
const char * pStart = i_rName.str();
if ( pNameEnd > pStart )
o_rFile.write( pStart, pNameEnd - pStart );
WriteStr( o_rFile, "</A>" );
WriteStr( o_rFile, C_sSpaceInName );
WriteStr( o_rFile, pNameEnd );
}
else
{
WriteStr( o_rFile, i_rName );
WriteStr( o_rFile, "</A>" );
}
}
void
WriteStr( std::ostream & o_rFile,
const char * i_sStr )
{
o_rFile.write( i_sStr, (int) strlen(i_sStr) );
}
void
WriteStr( std::ostream & o_rFile,
const Simstr & i_sStr )
{
o_rFile.write( i_sStr.str(), i_sStr.l() );
}
const char C_sXML_END[] = "\\*.xml";
void
GatherFileNames( List<Simstr> & o_sFiles,
const char * i_sSrcDirectory )
{
static int nAliveCounter = 0;
char * sNextDir = 0;
Simstr sNew = 0;
#ifdef WNT
struct _finddata_t aEntry;
long hFile = 0;
int bFindMore = 0;
char * sFilter = new char[ strlen(i_sSrcDirectory) + sizeof C_sXML_END ];
// Stayingalive sign
if (++nAliveCounter % 100 == 1)
std::cout << "." << std::flush;
strcpy(sFilter, i_sSrcDirectory); // STRCPY SAFE HERE
strcat(sFilter,C_sXML_END); // STRCAT SAFE HERE
hFile = _findfirst( sFilter, &aEntry );
for ( bFindMore = hFile == -1;
bFindMore == 0;
bFindMore = _findnext( hFile, &aEntry ) )
{
sNew = i_sSrcDirectory;
sNew += "\\";
sNew += aEntry.name;
o_sFiles.push_back(sNew);
} // end for
_findclose(hFile);
delete [] sFilter;
#elif defined(UNX) || defined(OS2)
DIR * pDir = opendir( i_sSrcDirectory );
dirent * pEntry = 0;
char * sEnding;
// Stayingalive sign
if (++nAliveCounter % 100 == 1)
std::cout << "." << std::flush;
while ( (pEntry = readdir(pDir)) != 0 )
{
sEnding = strrchr(pEntry->d_name,'.');
if (sEnding != 0 ? stricmp(sEnding,".xml") == 0 : 0 )
{
sNew = i_sSrcDirectory;
sNew += "/";
sNew += pEntry->d_name;
o_sFiles.push_back(sNew);
}
} // end while
closedir( pDir );
#else
#error Must run on unix or windows, please define UNX or WNT.
#endif
// gathering from subdirectories:
List<Simstr> aSubDirectories;
GatherSubDirectories( aSubDirectories, i_sSrcDirectory );
unsigned d_max = aSubDirectories.size();
for ( unsigned d = 0; d < d_max; ++d )
{
sNextDir = new char[ strlen(i_sSrcDirectory) + 2 + aSubDirectories[d].l() ];
strcpy(sNextDir, i_sSrcDirectory);
strcat(sNextDir, C_sSLASH);
strcat(sNextDir, aSubDirectories[d].str());
GatherFileNames(o_sFiles, sNextDir);
delete [] sNextDir;
}
}
const char * C_sANYDIR = "\\*.*";
void
GatherSubDirectories( List<Simstr> & o_sSubDirectories,
const char * i_sParentdDirectory )
{
Simstr sNew;
#ifdef WNT
struct _finddata_t aEntry;
long hFile = 0;
int bFindMore = 0;
char * sFilter = new char[strlen(i_sParentdDirectory) + sizeof C_sANYDIR];
strcpy(sFilter, i_sParentdDirectory);
strcat(sFilter,C_sANYDIR);
hFile = _findfirst( sFilter, &aEntry );
for ( bFindMore = hFile == -1;
bFindMore == 0;
bFindMore = _findnext( hFile, &aEntry ) )
{
if (aEntry.attrib == _A_SUBDIR)
{
// Do not gather . .. and outputtree directories
if ( strchr(aEntry.name,'.') == 0
&& strncmp(aEntry.name, "wnt", 3) != 0
&& strncmp(aEntry.name, "unx", 3) != 0 )
{
sNew = aEntry.name;
o_sSubDirectories.push_back(sNew);
}
} // endif (aEntry.attrib == _A_SUBDIR)
} // end for
_findclose(hFile);
delete [] sFilter;
#elif defined(UNX) || defined(OS2)
DIR * pDir = opendir( i_sParentdDirectory );
dirent * pEntry = 0;
struct stat aEntryStatus;
while ( ( pEntry = readdir(pDir) ) != 0 )
{
stat(pEntry->d_name, &aEntryStatus);
if ( ( aEntryStatus.st_mode & S_IFDIR ) == S_IFDIR )
{
// Do not gather . .. and outputtree directories
if ( strchr(pEntry->d_name,'.') == 0
&& strncmp(pEntry->d_name, "wnt", 3) != 0
&& strncmp(pEntry->d_name, "unx", 3) != 0 )
{
sNew = pEntry->d_name;
o_sSubDirectories.push_back(sNew);
}
} // endif (aEntry.attrib == _A_SUBDIR)
} // end while
closedir( pDir );
#else
#error Must run on unix or windows, please define UNX or WNT.
#endif
}
<commit_msg>INTEGRATION: CWS changefileheader (1.12.12); FILE MERGED 2008/03/31 13:06:36 rt 1.12.12.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: syshelp.cxx,v $
* $Revision: 1.13 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#include <syshelp.hxx>
// NOT FULLY DEFINED SERVICES
#include <string.h>
#include "sistr.hxx"
#include "list.hxx"
#ifdef WNT
#include <io.h>
#elif defined(UNX) || defined(OS2)
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#define stricmp strcasecmp
#else
#error Must run under unix or windows, please define UNX or WNT.
#endif
char C_sSpaceInName[] = " ";
void
WriteName( std::ostream & o_rFile,
const Simstr & i_rIdlDocuBaseDir,
const Simstr & i_rName,
E_LinkType i_eLinkType )
{
if (i_rName.l() == 0)
return;
const char * pNameEnd = strstr( i_rName.str(), " in " );
// No link:
if ( i_eLinkType == lt_nolink )
{
if ( pNameEnd != 0 )
{
const char * pStart = i_rName.str();
o_rFile.write( pStart, pNameEnd - pStart );
WriteStr( o_rFile, C_sSpaceInName );
WriteStr( o_rFile, pNameEnd );
}
else
{
WriteStr( o_rFile, i_rName );
}
return;
}
if ( i_eLinkType == lt_idl )
{
Simstr sPath(i_rName);
sPath.replace_all('.','/');
int nNameEnd = sPath.pos_first(' ');
int nPathStart = sPath.pos_last(' ');
WriteStr( o_rFile, "<A HREF=\"" );
if ( nNameEnd > -1 )
{
WriteStr( o_rFile, "file:///" );
WriteStr( o_rFile, i_rIdlDocuBaseDir );
WriteStr( o_rFile, "/" );
WriteStr( o_rFile, sPath.str() + 1 + nPathStart );
WriteStr( o_rFile, "/" );
o_rFile.write( sPath.str(), nNameEnd );
WriteStr( o_rFile, ".html\">" );
}
else
{ // Should not be reached:
WriteStr(o_rFile, i_rName);
return;
}
}
else if ( i_eLinkType == lt_html )
{
int nKomma = i_rName.pos_first(',');
int nEnd = i_rName.pos_first(' ');
if ( nKomma > -1 )
{
o_rFile.write( i_rName.str(), nKomma );
WriteStr( o_rFile, ": " );
WriteStr( o_rFile, "<A HREF=\"" );
o_rFile.write( i_rName.str(), nKomma );
WriteStr( o_rFile, ".html#" );
if ( nEnd > -1 )
o_rFile.write( i_rName.str() + nKomma + 1, nEnd - nKomma );
else
WriteStr( o_rFile, i_rName.str() + nKomma + 1 );
WriteStr( o_rFile, "\">" );
o_rFile.write( i_rName.str() + nKomma + 1, nEnd - nKomma );
}
else
{
WriteStr( o_rFile, "<A HREF=\"" );
WriteStr( o_rFile, i_rName );
WriteStr( o_rFile, ".html\">" );
WriteStr( o_rFile, i_rName );
}
WriteStr( o_rFile, "</A>" );
return;
}
if ( pNameEnd != 0 )
{
const char * pStart = i_rName.str();
if ( pNameEnd > pStart )
o_rFile.write( pStart, pNameEnd - pStart );
WriteStr( o_rFile, "</A>" );
WriteStr( o_rFile, C_sSpaceInName );
WriteStr( o_rFile, pNameEnd );
}
else
{
WriteStr( o_rFile, i_rName );
WriteStr( o_rFile, "</A>" );
}
}
void
WriteStr( std::ostream & o_rFile,
const char * i_sStr )
{
o_rFile.write( i_sStr, (int) strlen(i_sStr) );
}
void
WriteStr( std::ostream & o_rFile,
const Simstr & i_sStr )
{
o_rFile.write( i_sStr.str(), i_sStr.l() );
}
const char C_sXML_END[] = "\\*.xml";
void
GatherFileNames( List<Simstr> & o_sFiles,
const char * i_sSrcDirectory )
{
static int nAliveCounter = 0;
char * sNextDir = 0;
Simstr sNew = 0;
#ifdef WNT
struct _finddata_t aEntry;
long hFile = 0;
int bFindMore = 0;
char * sFilter = new char[ strlen(i_sSrcDirectory) + sizeof C_sXML_END ];
// Stayingalive sign
if (++nAliveCounter % 100 == 1)
std::cout << "." << std::flush;
strcpy(sFilter, i_sSrcDirectory); // STRCPY SAFE HERE
strcat(sFilter,C_sXML_END); // STRCAT SAFE HERE
hFile = _findfirst( sFilter, &aEntry );
for ( bFindMore = hFile == -1;
bFindMore == 0;
bFindMore = _findnext( hFile, &aEntry ) )
{
sNew = i_sSrcDirectory;
sNew += "\\";
sNew += aEntry.name;
o_sFiles.push_back(sNew);
} // end for
_findclose(hFile);
delete [] sFilter;
#elif defined(UNX) || defined(OS2)
DIR * pDir = opendir( i_sSrcDirectory );
dirent * pEntry = 0;
char * sEnding;
// Stayingalive sign
if (++nAliveCounter % 100 == 1)
std::cout << "." << std::flush;
while ( (pEntry = readdir(pDir)) != 0 )
{
sEnding = strrchr(pEntry->d_name,'.');
if (sEnding != 0 ? stricmp(sEnding,".xml") == 0 : 0 )
{
sNew = i_sSrcDirectory;
sNew += "/";
sNew += pEntry->d_name;
o_sFiles.push_back(sNew);
}
} // end while
closedir( pDir );
#else
#error Must run on unix or windows, please define UNX or WNT.
#endif
// gathering from subdirectories:
List<Simstr> aSubDirectories;
GatherSubDirectories( aSubDirectories, i_sSrcDirectory );
unsigned d_max = aSubDirectories.size();
for ( unsigned d = 0; d < d_max; ++d )
{
sNextDir = new char[ strlen(i_sSrcDirectory) + 2 + aSubDirectories[d].l() ];
strcpy(sNextDir, i_sSrcDirectory);
strcat(sNextDir, C_sSLASH);
strcat(sNextDir, aSubDirectories[d].str());
GatherFileNames(o_sFiles, sNextDir);
delete [] sNextDir;
}
}
const char * C_sANYDIR = "\\*.*";
void
GatherSubDirectories( List<Simstr> & o_sSubDirectories,
const char * i_sParentdDirectory )
{
Simstr sNew;
#ifdef WNT
struct _finddata_t aEntry;
long hFile = 0;
int bFindMore = 0;
char * sFilter = new char[strlen(i_sParentdDirectory) + sizeof C_sANYDIR];
strcpy(sFilter, i_sParentdDirectory);
strcat(sFilter,C_sANYDIR);
hFile = _findfirst( sFilter, &aEntry );
for ( bFindMore = hFile == -1;
bFindMore == 0;
bFindMore = _findnext( hFile, &aEntry ) )
{
if (aEntry.attrib == _A_SUBDIR)
{
// Do not gather . .. and outputtree directories
if ( strchr(aEntry.name,'.') == 0
&& strncmp(aEntry.name, "wnt", 3) != 0
&& strncmp(aEntry.name, "unx", 3) != 0 )
{
sNew = aEntry.name;
o_sSubDirectories.push_back(sNew);
}
} // endif (aEntry.attrib == _A_SUBDIR)
} // end for
_findclose(hFile);
delete [] sFilter;
#elif defined(UNX) || defined(OS2)
DIR * pDir = opendir( i_sParentdDirectory );
dirent * pEntry = 0;
struct stat aEntryStatus;
while ( ( pEntry = readdir(pDir) ) != 0 )
{
stat(pEntry->d_name, &aEntryStatus);
if ( ( aEntryStatus.st_mode & S_IFDIR ) == S_IFDIR )
{
// Do not gather . .. and outputtree directories
if ( strchr(pEntry->d_name,'.') == 0
&& strncmp(pEntry->d_name, "wnt", 3) != 0
&& strncmp(pEntry->d_name, "unx", 3) != 0 )
{
sNew = pEntry->d_name;
o_sSubDirectories.push_back(sNew);
}
} // endif (aEntry.attrib == _A_SUBDIR)
} // end while
closedir( pDir );
#else
#error Must run on unix or windows, please define UNX or WNT.
#endif
}
<|endoftext|> |
<commit_before>/* Copyright 2019 The TensorFlow Authors. 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 "tensorflow/lite/delegates/gpu/cl/kernels/work_group_picking.h"
#include <algorithm>
#include <limits>
#include <set>
#include <vector>
#include "tensorflow/lite/delegates/gpu/common/util.h"
namespace tflite {
namespace gpu {
namespace cl {
namespace {
std::vector<int2> Get2DWorkgroupsEqualTo128() {
return {{128, 1}, {64, 2}, {32, 4}, {16, 8},
{8, 16}, {4, 32}, {2, 64}, {1, 128}};
}
std::vector<int3> GenerateWorkGroupSizesXY128(
int3 grid, int max_work_group_size, WorkGroupSizeAlignment z_alignment) {
std::vector<int3> work_groups;
work_groups.reserve(32);
std::vector<int> possible_z_sizes = GetPossibleSizes(grid.z, z_alignment);
for (int x = 1; x <= max_work_group_size; x *= 2) {
for (int y = 1; y <= max_work_group_size; y *= 2) {
int work_group_size_xy = x * y;
if (work_group_size_xy % 128 != 0 ||
work_group_size_xy > max_work_group_size) {
continue;
}
for (auto z : possible_z_sizes) {
if (work_group_size_xy * z > max_work_group_size) {
continue;
}
work_groups.push_back({x, y, z});
}
}
}
return work_groups;
}
std::vector<int3> GenerateWorkGroupSizesXY128Linear(
int3 grid, int max_work_group_size, WorkGroupSizeAlignment z_alignment) {
std::vector<int3> work_groups;
work_groups.reserve(32);
std::vector<int> possible_z_sizes = GetPossibleSizes(grid.z, z_alignment);
for (int x = 128; x <= max_work_group_size && x < grid.x + 128; x += 128) {
for (auto z : possible_z_sizes) {
if (x * z <= max_work_group_size) {
work_groups.push_back({x, 1, z});
}
}
}
return work_groups;
}
Status GetBestWorkGroupAlignedToGrid(const TuningParameters& params,
const CLKernel& kernel, const int3& grid,
int3* best_work_group) {
std::vector<int3> work_groups;
RETURN_IF_ERROR(GenerateWorkGroupSizesAlignedToGrid(
grid, params.info->max_work_group_sizes, kernel.GetMaxWorkGroupSize(),
&work_groups));
int best_work_group_index;
RETURN_IF_ERROR(params.queue->GetBestWorkGroupIndex(
kernel, *params.info, grid, work_groups, &best_work_group_index));
*best_work_group = work_groups[best_work_group_index];
return OkStatus();
}
int GetPenalty(int grid_size, int group_size) {
const int reminder = grid_size % group_size;
return reminder == 0 ? 0 : group_size - reminder;
}
int GetPenalty(int2 grid_size, int2 group_size) {
const int p_x = GetPenalty(grid_size.x, group_size.x);
const int p_y = GetPenalty(grid_size.y, group_size.y);
return p_x * grid_size.y + p_y * grid_size.x + p_x * p_y;
}
int GetMaxSizeWithMinPenalty(int size, int max_size) {
int best_size = 128;
int min_penalty = GetPenalty(size, best_size);
for (int i = 2; i * 128 <= max_size; ++i) {
if (GetPenalty(size, i * 128) == min_penalty) {
best_size = i * 128;
}
}
return best_size;
}
int2 GetMaxSizeWithMinPenalty(int2 size, int max_size) {
std::vector<int2> base_groups = Get2DWorkgroupsEqualTo128();
int min_penalty = std::numeric_limits<int>::max();
for (auto group : base_groups) {
min_penalty = std::min(GetPenalty(size, group), min_penalty);
}
for (auto group : base_groups) {
for (int y = 1; y * group.y <= max_size; ++y) {
int new_group_y = y * group.y;
for (int x = 1; x * group.x <= max_size; ++x) {
int new_group_x = x * group.x;
if (new_group_x * new_group_y > max_size) {
break;
}
if (GetPenalty(size, int2(new_group_x, new_group_y)) == min_penalty) {
return int2(new_group_x, new_group_y);
}
}
}
}
return int2(0, 0);
}
int GetBiggestDividerWithPriority(int number, int max_divider) {
if (number % 8 == 0 && 8 <= max_divider) {
return 8;
}
if (number % 4 == 0 && 4 <= max_divider) {
return 4;
}
if (number % 2 == 0 && 2 <= max_divider) {
return 2;
}
for (int i = max_divider; i != 0; i--) {
if (number % i == 0) {
return i;
}
}
return 1;
}
int GetBiggestDivider(int number, int max_divider) {
for (int i = max_divider; i != 0; i--) {
if (number % i == 0) {
return i;
}
}
return 1;
}
} // namespace
int3 GetWorkGroupXY128ConvLinear(const int3& grid) {
int grid_z = GetBiggestDividerWithPriority(grid.z, 4);
if (grid.x <= 128) {
return int3(128, 1, grid_z);
}
int grid_x = GetMaxSizeWithMinPenalty(grid.x, 512 / grid_z);
return {grid_x, 1, grid_z};
}
int3 GetWorkGroupXY128Conv(const int3& grid) {
int grid_z = GetBiggestDividerWithPriority(grid.z, 4);
if (grid.x <= 16 && grid.y <= 8) {
return int3(16, 8, grid_z);
}
int2 grid_xy = GetMaxSizeWithMinPenalty(int2(grid.x, grid.y), 512 / grid_z);
return int3(grid_xy.x, grid_xy.y, grid_z);
}
int3 GetWorkGroupXY128Simple(const int3& grid) { return int3(16, 8, 1); }
int3 GetWorkGroup(const int3& grid, int max_size) {
int wg_z = GetBiggestDividerWithPriority(grid.z, 8);
int wg_xy_size = max_size / wg_z;
int wg_x = std::min(IntegralDivideRoundUp(grid.x, 2), wg_xy_size);
int wg_y = std::min(wg_xy_size / wg_x, grid.y);
return int3(wg_x, wg_y, wg_z);
}
int3 GetWorkGroupConv(const int3& grid, int max_size, int max_z_size) {
int wg_z = GetBiggestDivider(grid.z, max_z_size);
int wg_xy_size = std::min(256, max_size) / wg_z;
int wg_x = std::min(grid.x, wg_xy_size);
int wg_y = std::min(wg_xy_size / wg_x, grid.y);
if (wg_y == grid.y && grid.y % 2 == 0) {
wg_y = grid.y / 2;
}
return int3(wg_x, wg_y, wg_z);
}
Status GetBestWorkGroupXY128(const TuningParameters& params,
const CLKernel& kernel, const int3& grid,
WorkGroupSizeAlignment z_alignment,
int3* best_work_group) {
std::vector<int3> work_groups = GenerateWorkGroupSizesXY128(
grid, kernel.GetMaxWorkGroupSize(), z_alignment);
int best_work_group_index;
RETURN_IF_ERROR(params.queue->GetBestWorkGroupIndex(
kernel, *params.info, grid, work_groups, &best_work_group_index));
*best_work_group = work_groups[best_work_group_index];
return OkStatus();
}
Status GetBestWorkGroupXY128Linear(const TuningParameters& params,
const CLKernel& kernel, const int3& grid,
WorkGroupSizeAlignment z_alignment,
int3* best_work_group) {
std::vector<int3> work_groups = GenerateWorkGroupSizesXY128Linear(
grid, kernel.GetMaxWorkGroupSize(), z_alignment);
int best_work_group_index;
RETURN_IF_ERROR(params.queue->GetBestWorkGroupIndex(
kernel, *params.info, grid, work_groups, &best_work_group_index));
*best_work_group = work_groups[best_work_group_index];
return OkStatus();
}
bool XY128RequiresMoreWorkGroupsThenXY128Linear(int width, int height) {
int planar_work_groups = IntegralDivideRoundUp(width * height, 128);
auto base_work_groups = Get2DWorkgroupsEqualTo128();
bool have_equal_work_groups = false;
for (auto& work_group : base_work_groups) {
int x_groups = IntegralDivideRoundUp(width, work_group.x);
int y_groups = IntegralDivideRoundUp(height, work_group.y);
int xy_groups = x_groups * y_groups;
if (xy_groups == planar_work_groups) {
have_equal_work_groups = true;
break;
}
}
return !have_equal_work_groups;
}
Status GetBestWorkGroup(const TuningParameters& params, const CLKernel& kernel,
const int3& grid, int3* best_work_group) {
switch (params.tuning_type) {
case TuningType::FAST:
if (params.info->vendor != Vendor::QUALCOMM) {
*best_work_group = int3(8, 4, 1);
return OkStatus();
} else {
*best_work_group = GetWorkGroup(grid, kernel.GetMaxWorkGroupSize());
return OkStatus();
}
case TuningType::EXHAUSTIVE:
return GetBestWorkGroupAlignedToGrid(params, kernel, grid,
best_work_group);
default:
*best_work_group = {8, 4, 1};
return OkStatus();
}
}
Status GetBestWorkGroupConv(const TuningParameters& params,
const CLKernel& kernel, const int3& grid,
int3* best_work_group) {
switch (params.tuning_type) {
case TuningType::FAST:
if (params.info->vendor != Vendor::QUALCOMM) {
*best_work_group = int3(8, 4, 1);
return OkStatus();
} else {
int max_z_size = params.info->adreno_info.gpu_version < 400 ? 16 : 64;
*best_work_group =
GetWorkGroupConv(grid, kernel.GetMaxWorkGroupSize(), max_z_size);
return OkStatus();
}
case TuningType::EXHAUSTIVE:
return GetBestWorkGroupAlignedToGrid(params, kernel, grid,
best_work_group);
default:
*best_work_group = {8, 4, 1};
return OkStatus();
}
}
} // namespace cl
} // namespace gpu
} // namespace tflite
<commit_msg>Enabling non trivial fast tuning for all vendors.<commit_after>/* Copyright 2019 The TensorFlow Authors. 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 "tensorflow/lite/delegates/gpu/cl/kernels/work_group_picking.h"
#include <algorithm>
#include <limits>
#include <set>
#include <vector>
#include "tensorflow/lite/delegates/gpu/common/util.h"
namespace tflite {
namespace gpu {
namespace cl {
namespace {
std::vector<int2> Get2DWorkgroupsEqualTo128() {
return {{128, 1}, {64, 2}, {32, 4}, {16, 8},
{8, 16}, {4, 32}, {2, 64}, {1, 128}};
}
std::vector<int3> GenerateWorkGroupSizesXY128(
int3 grid, int max_work_group_size, WorkGroupSizeAlignment z_alignment) {
std::vector<int3> work_groups;
work_groups.reserve(32);
std::vector<int> possible_z_sizes = GetPossibleSizes(grid.z, z_alignment);
for (int x = 1; x <= max_work_group_size; x *= 2) {
for (int y = 1; y <= max_work_group_size; y *= 2) {
int work_group_size_xy = x * y;
if (work_group_size_xy % 128 != 0 ||
work_group_size_xy > max_work_group_size) {
continue;
}
for (auto z : possible_z_sizes) {
if (work_group_size_xy * z > max_work_group_size) {
continue;
}
work_groups.push_back({x, y, z});
}
}
}
return work_groups;
}
std::vector<int3> GenerateWorkGroupSizesXY128Linear(
int3 grid, int max_work_group_size, WorkGroupSizeAlignment z_alignment) {
std::vector<int3> work_groups;
work_groups.reserve(32);
std::vector<int> possible_z_sizes = GetPossibleSizes(grid.z, z_alignment);
for (int x = 128; x <= max_work_group_size && x < grid.x + 128; x += 128) {
for (auto z : possible_z_sizes) {
if (x * z <= max_work_group_size) {
work_groups.push_back({x, 1, z});
}
}
}
return work_groups;
}
Status GetBestWorkGroupAlignedToGrid(const TuningParameters& params,
const CLKernel& kernel, const int3& grid,
int3* best_work_group) {
std::vector<int3> work_groups;
RETURN_IF_ERROR(GenerateWorkGroupSizesAlignedToGrid(
grid, params.info->max_work_group_sizes, kernel.GetMaxWorkGroupSize(),
&work_groups));
int best_work_group_index;
RETURN_IF_ERROR(params.queue->GetBestWorkGroupIndex(
kernel, *params.info, grid, work_groups, &best_work_group_index));
*best_work_group = work_groups[best_work_group_index];
return OkStatus();
}
int GetPenalty(int grid_size, int group_size) {
const int reminder = grid_size % group_size;
return reminder == 0 ? 0 : group_size - reminder;
}
int GetPenalty(int2 grid_size, int2 group_size) {
const int p_x = GetPenalty(grid_size.x, group_size.x);
const int p_y = GetPenalty(grid_size.y, group_size.y);
return p_x * grid_size.y + p_y * grid_size.x + p_x * p_y;
}
int GetMaxSizeWithMinPenalty(int size, int max_size) {
int best_size = 128;
int min_penalty = GetPenalty(size, best_size);
for (int i = 2; i * 128 <= max_size; ++i) {
if (GetPenalty(size, i * 128) == min_penalty) {
best_size = i * 128;
}
}
return best_size;
}
int2 GetMaxSizeWithMinPenalty(int2 size, int max_size) {
std::vector<int2> base_groups = Get2DWorkgroupsEqualTo128();
int min_penalty = std::numeric_limits<int>::max();
for (auto group : base_groups) {
min_penalty = std::min(GetPenalty(size, group), min_penalty);
}
for (auto group : base_groups) {
for (int y = 1; y * group.y <= max_size; ++y) {
int new_group_y = y * group.y;
for (int x = 1; x * group.x <= max_size; ++x) {
int new_group_x = x * group.x;
if (new_group_x * new_group_y > max_size) {
break;
}
if (GetPenalty(size, int2(new_group_x, new_group_y)) == min_penalty) {
return int2(new_group_x, new_group_y);
}
}
}
}
return int2(0, 0);
}
int GetBiggestDividerWithPriority(int number, int max_divider) {
if (number % 8 == 0 && 8 <= max_divider) {
return 8;
}
if (number % 4 == 0 && 4 <= max_divider) {
return 4;
}
if (number % 2 == 0 && 2 <= max_divider) {
return 2;
}
for (int i = max_divider; i != 0; i--) {
if (number % i == 0) {
return i;
}
}
return 1;
}
int GetBiggestDivider(int number, int max_divider) {
for (int i = max_divider; i != 0; i--) {
if (number % i == 0) {
return i;
}
}
return 1;
}
} // namespace
int3 GetWorkGroupXY128ConvLinear(const int3& grid) {
int grid_z = GetBiggestDividerWithPriority(grid.z, 4);
if (grid.x <= 128) {
return int3(128, 1, grid_z);
}
int grid_x = GetMaxSizeWithMinPenalty(grid.x, 512 / grid_z);
return {grid_x, 1, grid_z};
}
int3 GetWorkGroupXY128Conv(const int3& grid) {
int grid_z = GetBiggestDividerWithPriority(grid.z, 4);
if (grid.x <= 16 && grid.y <= 8) {
return int3(16, 8, grid_z);
}
int2 grid_xy = GetMaxSizeWithMinPenalty(int2(grid.x, grid.y), 512 / grid_z);
return int3(grid_xy.x, grid_xy.y, grid_z);
}
int3 GetWorkGroupXY128Simple(const int3& grid) { return int3(16, 8, 1); }
int3 GetWorkGroup(const int3& grid, int max_size) {
int wg_z = GetBiggestDividerWithPriority(grid.z, 8);
int wg_xy_size = max_size / wg_z;
int wg_x = std::min(IntegralDivideRoundUp(grid.x, 2), wg_xy_size);
int wg_y = std::min(wg_xy_size / wg_x, grid.y);
return int3(wg_x, wg_y, wg_z);
}
int3 GetWorkGroupConv(const int3& grid, int max_size, int max_z_size) {
int wg_z = GetBiggestDivider(grid.z, max_z_size);
int wg_xy_size = std::min(256, max_size) / wg_z;
int wg_x = std::min(grid.x, wg_xy_size);
int wg_y = std::min(wg_xy_size / wg_x, grid.y);
if (wg_y == grid.y && grid.y % 2 == 0) {
wg_y = grid.y / 2;
}
return int3(wg_x, wg_y, wg_z);
}
Status GetBestWorkGroupXY128(const TuningParameters& params,
const CLKernel& kernel, const int3& grid,
WorkGroupSizeAlignment z_alignment,
int3* best_work_group) {
std::vector<int3> work_groups = GenerateWorkGroupSizesXY128(
grid, kernel.GetMaxWorkGroupSize(), z_alignment);
int best_work_group_index;
RETURN_IF_ERROR(params.queue->GetBestWorkGroupIndex(
kernel, *params.info, grid, work_groups, &best_work_group_index));
*best_work_group = work_groups[best_work_group_index];
return OkStatus();
}
Status GetBestWorkGroupXY128Linear(const TuningParameters& params,
const CLKernel& kernel, const int3& grid,
WorkGroupSizeAlignment z_alignment,
int3* best_work_group) {
std::vector<int3> work_groups = GenerateWorkGroupSizesXY128Linear(
grid, kernel.GetMaxWorkGroupSize(), z_alignment);
int best_work_group_index;
RETURN_IF_ERROR(params.queue->GetBestWorkGroupIndex(
kernel, *params.info, grid, work_groups, &best_work_group_index));
*best_work_group = work_groups[best_work_group_index];
return OkStatus();
}
bool XY128RequiresMoreWorkGroupsThenXY128Linear(int width, int height) {
int planar_work_groups = IntegralDivideRoundUp(width * height, 128);
auto base_work_groups = Get2DWorkgroupsEqualTo128();
bool have_equal_work_groups = false;
for (auto& work_group : base_work_groups) {
int x_groups = IntegralDivideRoundUp(width, work_group.x);
int y_groups = IntegralDivideRoundUp(height, work_group.y);
int xy_groups = x_groups * y_groups;
if (xy_groups == planar_work_groups) {
have_equal_work_groups = true;
break;
}
}
return !have_equal_work_groups;
}
Status GetBestWorkGroup(const TuningParameters& params, const CLKernel& kernel,
const int3& grid, int3* best_work_group) {
switch (params.tuning_type) {
case TuningType::FAST:
*best_work_group = GetWorkGroup(grid, kernel.GetMaxWorkGroupSize());
return OkStatus();
case TuningType::EXHAUSTIVE:
return GetBestWorkGroupAlignedToGrid(params, kernel, grid,
best_work_group);
default:
*best_work_group = {8, 4, 1};
return OkStatus();
}
}
Status GetBestWorkGroupConv(const TuningParameters& params,
const CLKernel& kernel, const int3& grid,
int3* best_work_group) {
switch (params.tuning_type) {
case TuningType::FAST: {
int max_z_size = 16;
if (params.info->vendor == Vendor::QUALCOMM) {
max_z_size = params.info->adreno_info.gpu_version < 400 ? 16 : 64;
}
max_z_size = std::min(max_z_size, params.info->max_work_group_sizes.z);
*best_work_group =
GetWorkGroupConv(grid, kernel.GetMaxWorkGroupSize(), max_z_size);
return OkStatus();
}
case TuningType::EXHAUSTIVE:
return GetBestWorkGroupAlignedToGrid(params, kernel, grid,
best_work_group);
default:
*best_work_group = {8, 4, 1};
return OkStatus();
}
}
} // namespace cl
} // namespace gpu
} // namespace tflite
<|endoftext|> |
<commit_before>#include <vector>
#include <algorithm> /* heap operations, std::sort */
#include <iostream>
#include <shogun/converter/LocallyLinearEmbedding.h>
#include <shogun/distance/EuclideanDistance.h>
#include <shogun/features/DenseFeatures.h>
#include <shogun/features/DataGenerator.h>
#include <gtest/gtest.h>
using namespace shogun;
#ifdef HAVE_EIGEN3
struct index_and_distance_struct
{
float64_t distance;
index_t neighbor_index;
} ;
struct heap_comparator
{
bool operator() (const index_and_distance_struct& first, const index_and_distance_struct& second)
{
return first.distance > second.distance;
}
} comparator;
std::vector<index_t> get_neighbors_indices(CDistance* distance_object, index_t feature_vector_index, index_t n_neighbors);
TEST(LocallyLinearEmbeddingTest,neighbors_preserving)
{
const index_t n_samples = 100;
const index_t n_gaussians = 1;
const index_t n_dimensions = 4;
const index_t n_target_dimensions = 3;
const index_t n_neighbors = 30;
CDenseFeatures<float64_t>* high_dimensional_features =
new CDenseFeatures<float64_t>(CDataGenerator::generate_gaussians(n_samples, n_gaussians, n_dimensions));
CDistance* high_dimensional_dist =
new CEuclideanDistance(high_dimensional_features, high_dimensional_features);
std::vector<std::vector<index_t> > neighbors_for_vectors;
/* Find n_neighbors nearest eighbours for each vector */
for (index_t i=0; i<n_samples; ++i)
{
neighbors_for_vectors.push_back(get_neighbors_indices(high_dimensional_dist, i, n_neighbors));
}
CLocallyLinearEmbedding* lleEmbedder =
new CLocallyLinearEmbedding();
lleEmbedder->set_k(n_neighbors);
lleEmbedder->set_target_dim(n_target_dimensions);
EXPECT_EQ(n_target_dimensions, lleEmbedder->get_target_dim());
CDenseFeatures<float64_t>* low_dimensional_features =
lleEmbedder->embed(high_dimensional_features);
EXPECT_EQ(n_target_dimensions,low_dimensional_features->get_dim_feature_space());
EXPECT_EQ(high_dimensional_features->get_num_vectors(),low_dimensional_features->get_num_vectors());
CDistance* low_dimensional_dist =
new CEuclideanDistance(low_dimensional_features, low_dimensional_features);
for (index_t i=0; i<n_samples; ++i)
{
ASSERT_EQ(neighbors_for_vectors[i], get_neighbors_indices(low_dimensional_dist, i, n_neighbors));
}
SG_UNREF(lleEmbedder);
SG_UNREF(high_dimensional_dist);
SG_UNREF(low_dimensional_dist);
}
std::vector<index_t> get_neighbors_indices(CDistance* distance_object, index_t feature_vector_index, index_t n_neighbors)
{
index_t n_vectors = distance_object->get_num_vec_lhs();
EXPECT_EQ(n_vectors, distance_object->get_num_vec_rhs());
EXPECT_LE(n_neighbors, n_vectors - 1) << "Number of neigbors can not be greater than total number of vectors minus 1";
EXPECT_LE(feature_vector_index, n_vectors - 1);
std::vector<index_and_distance_struct> distances_and_indices;
for (index_t j = 0; j<n_vectors; ++j)
{
if (j == feature_vector_index)
/* To avoid adding itself to the neighbors list */
continue;
index_and_distance_struct current;
current.distance = distance_object->distance(feature_vector_index, j);
current.neighbor_index = j;
distances_and_indices.push_back(current);
}
/* Heapify, and then extract n_neighbors nearest neighbors*/
std::make_heap(distances_and_indices.begin(), distances_and_indices.end(), comparator);
std::vector<index_t> neighbors_for_current_vector;
for (index_t j = 0; j < n_neighbors; ++j)
{
neighbors_for_current_vector.push_back(distances_and_indices[0].neighbor_index);
std::pop_heap(distances_and_indices.begin(), distances_and_indices.end(), comparator);
distances_and_indices.pop_back();
}
std::sort(neighbors_for_current_vector.begin(), neighbors_for_current_vector.end());
return neighbors_for_current_vector;
}
#endif
<commit_msg>Modified unit test for Locally Linear Embedding, so that it allows 'misses' of neighbors before and after the dimensionality reduction.<commit_after>#include <vector>
#include <set>
#include <algorithm> /* heap operations, std::sort */
#include <iostream>
#include <shogun/converter/LocallyLinearEmbedding.h>
#include <shogun/distance/EuclideanDistance.h>
#include <shogun/features/DenseFeatures.h>
#include <shogun/features/DataGenerator.h>
#include <gtest/gtest.h>
using namespace shogun;
#ifdef HAVE_EIGEN3
struct index_and_distance_struct
{
float64_t distance;
index_t neighbor_index;
} ;
struct heap_comparator
{
bool operator() (const index_and_distance_struct& first, const index_and_distance_struct& second)
{
return first.distance > second.distance;
}
} comparator;
std::set<index_t> get_neighbors_indices(CDistance* distance_object, index_t feature_vector_index, index_t n_neighbors);
void check_similarity_of_sets(const std::set<index_t>& first_set,const std::set<index_t>& second_set, float min_similarity_level);
TEST(LocallyLinearEmbeddingTest,neighbors_preserving)
{
const index_t n_samples = 100;
const index_t n_gaussians = 1;
const index_t n_dimensions = 4;
const index_t n_target_dimensions = 3;
const index_t n_neighbors = 40;
const float required_similarity_level = 0.5; /*hope we will get rid of this*/
CDenseFeatures<float64_t>* high_dimensional_features =
new CDenseFeatures<float64_t>(CDataGenerator::generate_gaussians(n_samples, n_gaussians, n_dimensions));
CDistance* high_dimensional_dist =
new CEuclideanDistance(high_dimensional_features, high_dimensional_features);
std::vector<std::set<index_t> > high_dimensional_neighbors_for_vectors;
/* Find n_neighbors nearest eighbours for each vector */
for (index_t i=0; i<n_samples; ++i)
{
high_dimensional_neighbors_for_vectors.push_back(get_neighbors_indices(high_dimensional_dist, i, n_neighbors));
}
CLocallyLinearEmbedding* lleEmbedder =
new CLocallyLinearEmbedding();
lleEmbedder->set_k(n_neighbors);
lleEmbedder->set_target_dim(n_target_dimensions);
EXPECT_EQ(n_target_dimensions, lleEmbedder->get_target_dim());
CDenseFeatures<float64_t>* low_dimensional_features =
lleEmbedder->embed(high_dimensional_features);
EXPECT_EQ(n_target_dimensions,low_dimensional_features->get_dim_feature_space());
EXPECT_EQ(high_dimensional_features->get_num_vectors(),low_dimensional_features->get_num_vectors());
CDistance* low_dimensional_dist =
new CEuclideanDistance(low_dimensional_features, low_dimensional_features);
for (index_t i=0; i<n_samples; ++i)
{
std::set<index_t> low_dimensional_neighbors = get_neighbors_indices(low_dimensional_dist, i, n_neighbors);
check_similarity_of_sets(high_dimensional_neighbors_for_vectors[i], low_dimensional_neighbors, required_similarity_level);
}
SG_UNREF(lleEmbedder);
SG_UNREF(high_dimensional_dist);
SG_UNREF(low_dimensional_dist);
}
std::set<index_t> get_neighbors_indices(CDistance* distance_object, index_t feature_vector_index, index_t n_neighbors)
{
index_t n_vectors = distance_object->get_num_vec_lhs();
EXPECT_EQ(n_vectors, distance_object->get_num_vec_rhs());
EXPECT_LE(n_neighbors, n_vectors - 1) << "Number of neigbors can not be greater than total number of vectors minus 1";
EXPECT_LE(feature_vector_index, n_vectors - 1);
std::vector<index_and_distance_struct> distances_and_indices;
for (index_t j = 0; j<n_vectors; ++j)
{
if (j == feature_vector_index)
/* To avoid adding itself to the neighbors list */
continue;
index_and_distance_struct current;
current.distance = distance_object->distance(feature_vector_index, j);
current.neighbor_index = j;
distances_and_indices.push_back(current);
}
/* Heapify, and then extract n_neighbors nearest neighbors*/
std::make_heap(distances_and_indices.begin(), distances_and_indices.end(), comparator);
std::set<index_t> neighbors_for_current_vector;
for (index_t j = 0; j < n_neighbors; ++j)
{
neighbors_for_current_vector.insert(distances_and_indices[0].neighbor_index);
std::pop_heap(distances_and_indices.begin(), distances_and_indices.end(), comparator);
distances_and_indices.pop_back();
}
return neighbors_for_current_vector;
}
void check_similarity_of_sets(const std::set<index_t>& first_set,const std::set<index_t>& second_set, float min_similarity_level)
{
index_t total_elements_count = first_set.size();
ASSERT_EQ(total_elements_count, second_set.size()) << "Can not compare sets of different size.";
ASSERT_LE(min_similarity_level, 1.0) << "Similarity level can not be greater than 1.";
ASSERT_GE(min_similarity_level, 0) << "Similarity level can not be less than 0.";
if (min_similarity_level == 0)
/*Nothing to do*/
return;
index_t similar_elements_count = 0;
std::set<index_t>::iterator first_iter = first_set.begin(), second_iter = second_set.begin();
while (first_iter != first_set.end() && second_iter != second_set.end())
{
if (*first_iter < *second_iter)
++first_iter;
else if (*second_iter < *first_iter)
++second_iter;
else
{
++similar_elements_count; ++first_iter; ++second_iter;
}
}
EXPECT_GE((float) similar_elements_count /(float) total_elements_count, min_similarity_level)<<"#similarElements/#total < minimal similarity level.";
}
#endif
<|endoftext|> |
<commit_before>/*
* Copyright 2007-2021 CM4all GmbH
* All rights reserved.
*
* author: Max Kellermann <[email protected]>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* FOUNDATION 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 "CommandLine.hxx"
#include "Config.hxx"
#include "net/Parser.hxx"
#include "io/Logger.hxx"
#include "util/StringView.hxx"
#include "util/IterableSplitString.hxx"
#include "version.h"
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <getopt.h>
#include <string.h>
static void
PrintUsage()
{
puts("usage: cm4all-beng-proxy [options]\n\n"
"valid options:\n"
#ifdef __GLIBC__
" --help\n"
#endif
" -h help (this text)\n"
#ifdef __GLIBC__
" --version\n"
#endif
" -V show cm4all-beng-proxy version\n"
#ifdef __GLIBC__
" --verbose\n"
#endif
" -v be more verbose\n"
#ifdef __GLIBC__
" --quiet\n"
#endif
" -q be quiet\n"
#ifdef __GLIBC__
" --config-file file\n"
#endif
" -f file load this configuration file\n"
#ifdef __GLIBC__
" --logger-user name\n"
#endif
" -U name execute the error logger program with this user id\n"
#ifdef __GLIBC__
" --document-root DIR\n"
#endif
" -r DIR set the document root\n"
#ifdef __GLIBC__
" --translation-socket PATH\n"
#endif
" -t PATH set the path to the translation server socket\n"
#ifdef __GLIBC__
" --cluster-size N\n"
#endif
" -C N set the size of the beng-lb cluster\n"
#ifdef __GLIBC__
" --cluster-node N\n"
#endif
" -N N set the index of this node in the beng-lb cluster\n"
#ifdef __GLIBC__
" --ua-classes PATH\n"
#endif
" -a PATH load the User-Agent classification rules from this file\n"
#ifdef __GLIBC__
" --set NAME=VALUE tweak an internal variable, see manual for details\n"
#endif
" -s NAME=VALUE \n"
"\n"
);
}
static void arg_error(const char *argv0, const char *fmt, ...)
__attribute__ ((noreturn))
__attribute__((format(printf,2,3)));
static void arg_error(const char *argv0, const char *fmt, ...) {
if (fmt != nullptr) {
va_list ap;
fputs(argv0, stderr);
fputs(": ", stderr);
va_start(ap, fmt);
vfprintf(stderr, fmt, ap);
va_end(ap);
putc('\n', stderr);
}
fprintf(stderr, "Try '%s --help' for more information.\n",
argv0);
exit(1);
}
template<typename F>
static void
SplitForEach(const char *p, char separator, F &&f)
{
for (auto value : IterableSplitString(p, separator))
if (!value.empty())
f(std::string(value.data, value.size).c_str());
}
static void
HandleSet(BpConfig &config,
const char *argv0, const char *p)
{
const char *eq;
eq = strchr(p, '=');
if (eq == nullptr)
arg_error(argv0, "No '=' found in --set argument");
if (eq == p)
arg_error(argv0, "No name found in --set argument");
const StringView name(p, eq - p);
const char *const value = eq + 1;
try {
config.HandleSet(name, value);
} catch (const std::runtime_error &e) {
arg_error(argv0, "Error while parsing \"--set %.*s\": %s",
(int)name.size, name.data, e.what());
}
}
/** read configuration options from the command line */
void
ParseCommandLine(BpCmdLine &cmdline, BpConfig &config, int argc, char **argv)
{
int ret;
char *endptr;
#ifdef __GLIBC__
static constexpr struct option long_options[] = {
{"help", 0, nullptr, 'h'},
{"version", 0, nullptr, 'V'},
{"verbose", 0, nullptr, 'v'},
{"quiet", 0, nullptr, 'q'},
{"config-file", 1, nullptr, 'f'},
{"user", 1, nullptr, 'u'},
{"logger-user", 1, nullptr, 'U'},
{"translation-socket", 1, nullptr, 't'},
{"cluster-size", 1, nullptr, 'C'},
{"cluster-node", 1, nullptr, 'N'},
{"ua-classes", 1, nullptr, 'a'},
{"set", 1, nullptr, 's'},
{"debug-listener-tag", 1, nullptr, 'L'},
{nullptr, 0, nullptr, 0}
};
#endif
unsigned verbose = 1;
while (1) {
#ifdef __GLIBC__
int option_index = 0;
ret = getopt_long(argc, argv,
"hVvqf:U:t:B:C:N:s:",
long_options, &option_index);
#else
ret = getopt(argc, argv,
"hVvqf:U:t:B:C:N:s:");
#endif
if (ret == -1)
break;
switch (ret) {
case 'h':
PrintUsage();
exit(0);
case 'V':
printf("cm4all-beng-proxy v%s\n", VERSION);
exit(0);
case 'v':
++verbose;
break;
case 'q':
verbose = 0;
break;
case 'f':
cmdline.config_file = optarg;
break;
case 'U':
cmdline.logger_user.Lookup(optarg);
break;
case 't':
config.translation_sockets.emplace_front(ParseSocketAddress(optarg, 0, false));
break;
case 'C':
config.cluster_size = strtoul(optarg, &endptr, 10);
if (endptr == optarg || *endptr != 0 ||
config.cluster_size > 1024)
arg_error(argv[0], "Invalid cluster size number");
if (config.cluster_node >= config.cluster_size)
config.cluster_node = 0;
break;
case 'N':
config.cluster_node = strtoul(optarg, &endptr, 10);
if (endptr == optarg || *endptr != 0)
arg_error(argv[0], "Invalid cluster size number");
if ((config.cluster_node != 0 || config.cluster_size != 0) &&
config.cluster_node >= config.cluster_size)
arg_error(argv[0], "Cluster node too large");
break;
case 'a':
cmdline.ua_classification_file = optarg;
break;
case 's':
HandleSet(config, argv[0], optarg);
break;
case 'L':
cmdline.debug_listener_tag = optarg;
break;
case '?':
arg_error(argv[0], nullptr);
default:
exit(1);
}
}
SetLogLevel(verbose);
/* check non-option arguments */
if (optind < argc)
arg_error(argv[0], "unrecognized argument: %s", argv[optind]);
}
<commit_msg>bp/CommandLine: remove obsolete --user option<commit_after>/*
* Copyright 2007-2021 CM4all GmbH
* All rights reserved.
*
* author: Max Kellermann <[email protected]>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* FOUNDATION 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 "CommandLine.hxx"
#include "Config.hxx"
#include "net/Parser.hxx"
#include "io/Logger.hxx"
#include "util/StringView.hxx"
#include "util/IterableSplitString.hxx"
#include "version.h"
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <getopt.h>
#include <string.h>
static void
PrintUsage()
{
puts("usage: cm4all-beng-proxy [options]\n\n"
"valid options:\n"
#ifdef __GLIBC__
" --help\n"
#endif
" -h help (this text)\n"
#ifdef __GLIBC__
" --version\n"
#endif
" -V show cm4all-beng-proxy version\n"
#ifdef __GLIBC__
" --verbose\n"
#endif
" -v be more verbose\n"
#ifdef __GLIBC__
" --quiet\n"
#endif
" -q be quiet\n"
#ifdef __GLIBC__
" --config-file file\n"
#endif
" -f file load this configuration file\n"
#ifdef __GLIBC__
" --logger-user name\n"
#endif
" -U name execute the error logger program with this user id\n"
#ifdef __GLIBC__
" --document-root DIR\n"
#endif
" -r DIR set the document root\n"
#ifdef __GLIBC__
" --translation-socket PATH\n"
#endif
" -t PATH set the path to the translation server socket\n"
#ifdef __GLIBC__
" --cluster-size N\n"
#endif
" -C N set the size of the beng-lb cluster\n"
#ifdef __GLIBC__
" --cluster-node N\n"
#endif
" -N N set the index of this node in the beng-lb cluster\n"
#ifdef __GLIBC__
" --ua-classes PATH\n"
#endif
" -a PATH load the User-Agent classification rules from this file\n"
#ifdef __GLIBC__
" --set NAME=VALUE tweak an internal variable, see manual for details\n"
#endif
" -s NAME=VALUE \n"
"\n"
);
}
static void arg_error(const char *argv0, const char *fmt, ...)
__attribute__ ((noreturn))
__attribute__((format(printf,2,3)));
static void arg_error(const char *argv0, const char *fmt, ...) {
if (fmt != nullptr) {
va_list ap;
fputs(argv0, stderr);
fputs(": ", stderr);
va_start(ap, fmt);
vfprintf(stderr, fmt, ap);
va_end(ap);
putc('\n', stderr);
}
fprintf(stderr, "Try '%s --help' for more information.\n",
argv0);
exit(1);
}
template<typename F>
static void
SplitForEach(const char *p, char separator, F &&f)
{
for (auto value : IterableSplitString(p, separator))
if (!value.empty())
f(std::string(value.data, value.size).c_str());
}
static void
HandleSet(BpConfig &config,
const char *argv0, const char *p)
{
const char *eq;
eq = strchr(p, '=');
if (eq == nullptr)
arg_error(argv0, "No '=' found in --set argument");
if (eq == p)
arg_error(argv0, "No name found in --set argument");
const StringView name(p, eq - p);
const char *const value = eq + 1;
try {
config.HandleSet(name, value);
} catch (const std::runtime_error &e) {
arg_error(argv0, "Error while parsing \"--set %.*s\": %s",
(int)name.size, name.data, e.what());
}
}
/** read configuration options from the command line */
void
ParseCommandLine(BpCmdLine &cmdline, BpConfig &config, int argc, char **argv)
{
int ret;
char *endptr;
#ifdef __GLIBC__
static constexpr struct option long_options[] = {
{"help", 0, nullptr, 'h'},
{"version", 0, nullptr, 'V'},
{"verbose", 0, nullptr, 'v'},
{"quiet", 0, nullptr, 'q'},
{"config-file", 1, nullptr, 'f'},
{"logger-user", 1, nullptr, 'U'},
{"translation-socket", 1, nullptr, 't'},
{"cluster-size", 1, nullptr, 'C'},
{"cluster-node", 1, nullptr, 'N'},
{"ua-classes", 1, nullptr, 'a'},
{"set", 1, nullptr, 's'},
{"debug-listener-tag", 1, nullptr, 'L'},
{nullptr, 0, nullptr, 0}
};
#endif
unsigned verbose = 1;
while (1) {
#ifdef __GLIBC__
int option_index = 0;
ret = getopt_long(argc, argv,
"hVvqf:U:t:B:C:N:s:",
long_options, &option_index);
#else
ret = getopt(argc, argv,
"hVvqf:U:t:B:C:N:s:");
#endif
if (ret == -1)
break;
switch (ret) {
case 'h':
PrintUsage();
exit(0);
case 'V':
printf("cm4all-beng-proxy v%s\n", VERSION);
exit(0);
case 'v':
++verbose;
break;
case 'q':
verbose = 0;
break;
case 'f':
cmdline.config_file = optarg;
break;
case 'U':
cmdline.logger_user.Lookup(optarg);
break;
case 't':
config.translation_sockets.emplace_front(ParseSocketAddress(optarg, 0, false));
break;
case 'C':
config.cluster_size = strtoul(optarg, &endptr, 10);
if (endptr == optarg || *endptr != 0 ||
config.cluster_size > 1024)
arg_error(argv[0], "Invalid cluster size number");
if (config.cluster_node >= config.cluster_size)
config.cluster_node = 0;
break;
case 'N':
config.cluster_node = strtoul(optarg, &endptr, 10);
if (endptr == optarg || *endptr != 0)
arg_error(argv[0], "Invalid cluster size number");
if ((config.cluster_node != 0 || config.cluster_size != 0) &&
config.cluster_node >= config.cluster_size)
arg_error(argv[0], "Cluster node too large");
break;
case 'a':
cmdline.ua_classification_file = optarg;
break;
case 's':
HandleSet(config, argv[0], optarg);
break;
case 'L':
cmdline.debug_listener_tag = optarg;
break;
case '?':
arg_error(argv[0], nullptr);
default:
exit(1);
}
}
SetLogLevel(verbose);
/* check non-option arguments */
if (optind < argc)
arg_error(argv[0], "unrecognized argument: %s", argv[optind]);
}
<|endoftext|> |
<commit_before><commit_msg>11995 - I Can Guess the Data Structure!<commit_after><|endoftext|> |
<commit_before>#include <tests/lib/test.h>
#include <tests/lib/glib-helpers/test-conn-helper.h>
#include <tests/lib/glib/contacts-conn.h>
#include <TelepathyQt4/Connection>
#include <TelepathyQt4/Contact>
#include <TelepathyQt4/ContactManager>
#include <TelepathyQt4/PendingContacts>
#include <TelepathyQt4/PendingContactInfo>
#include <telepathy-glib/debug.h>
using namespace Tp;
class TestContactsInfo : public Test
{
Q_OBJECT
public:
TestContactsInfo(QObject *parent = 0)
: Test(parent), mConn(0), mContactsInfoFieldsUpdated(0)
{ }
protected Q_SLOTS:
void onContactInfoFieldsChanged(const Tp::Contact::InfoFields &);
private Q_SLOTS:
void initTestCase();
void init();
void testInfo();
void cleanup();
void cleanupTestCase();
private:
TestConnHelper *mConn;
int mContactsInfoFieldsUpdated;
};
void TestContactsInfo::onContactInfoFieldsChanged(const Tp::Contact::InfoFields &info)
{
Q_UNUSED(info);
mContactsInfoFieldsUpdated++;
mLoop->exit(0);
}
void TestContactsInfo::initTestCase()
{
initTestCaseImpl();
g_type_init();
g_set_prgname("contacts-info");
tp_debug_set_flags("all");
dbus_g_bus_get(DBUS_BUS_STARTER, 0);
mConn = new TestConnHelper(this,
TP_TESTS_TYPE_CONTACTS_CONNECTION,
"account", "[email protected]",
"protocol", "foo",
NULL);
QCOMPARE(mConn->connect(), true);
}
void TestContactsInfo::init()
{
initImpl();
mContactsInfoFieldsUpdated = 0;
}
void TestContactsInfo::testInfo()
{
ContactManagerPtr contactManager = mConn->client()->contactManager();
QVERIFY(contactManager->supportedFeatures().contains(Contact::FeatureInfo));
QStringList validIDs = QStringList() << QLatin1String("foo")
<< QLatin1String("bar");
QList<ContactPtr> contacts = mConn->contacts(validIDs, Contact::FeatureInfo);
QCOMPARE(contacts.size(), validIDs.size());
for (int i = 0; i < contacts.size(); i++) {
ContactPtr contact = contacts[i];
QCOMPARE(contact->requestedFeatures().contains(Contact::FeatureInfo), true);
QCOMPARE(contact->actualFeatures().contains(Contact::FeatureInfo), true);
QVERIFY(contact->infoFields().allFields().isEmpty());
QVERIFY(connect(contact.data(),
SIGNAL(infoFieldsChanged(const Tp::Contact::InfoFields &)),
SLOT(onContactInfoFieldsChanged(const Tp::Contact::InfoFields &))));
}
GPtrArray *info_default = (GPtrArray *) dbus_g_type_specialized_construct (
TP_ARRAY_TYPE_CONTACT_INFO_FIELD_LIST);
{
const gchar * const field_values[2] = {
"FooBar", NULL
};
g_ptr_array_add (info_default, tp_value_array_build (3,
G_TYPE_STRING, "n",
G_TYPE_STRV, NULL,
G_TYPE_STRV, field_values,
G_TYPE_INVALID));
}
tp_tests_contacts_connection_set_default_contact_info(TP_TESTS_CONTACTS_CONNECTION(mConn->service()),
info_default);
GPtrArray *info_1 = (GPtrArray *) dbus_g_type_specialized_construct (
TP_ARRAY_TYPE_CONTACT_INFO_FIELD_LIST);
{
const gchar * const field_values[2] = {
"Foo", NULL
};
g_ptr_array_add (info_1, tp_value_array_build (3,
G_TYPE_STRING, "n",
G_TYPE_STRV, NULL,
G_TYPE_STRV, field_values,
G_TYPE_INVALID));
}
GPtrArray *info_2 = (GPtrArray *) dbus_g_type_specialized_construct (
TP_ARRAY_TYPE_CONTACT_INFO_FIELD_LIST);
{
const gchar * const field_values[2] = {
"Bar", NULL
};
g_ptr_array_add (info_2, tp_value_array_build (3,
G_TYPE_STRING, "n",
G_TYPE_STRV, NULL,
G_TYPE_STRV, field_values,
G_TYPE_INVALID));
}
TpHandle handles[] = { 0, 0 };
TpHandleRepoIface *serviceRepo = tp_base_connection_get_handles(
TP_BASE_CONNECTION(mConn->service()), TP_HANDLE_TYPE_CONTACT);
for (unsigned i = 0; i < 2; i++) {
handles[i] = tp_handle_ensure(serviceRepo, qPrintable(validIDs[i]),
NULL, NULL);
}
tp_tests_contacts_connection_change_contact_info(TP_TESTS_CONTACTS_CONNECTION(mConn->service()),
handles[0], info_1);
tp_tests_contacts_connection_change_contact_info(TP_TESTS_CONTACTS_CONNECTION(mConn->service()),
handles[1], info_2);
while (mContactsInfoFieldsUpdated != 2) {
QCOMPARE(mLoop->exec(), 0);
}
QCOMPARE(mContactsInfoFieldsUpdated, 2);
mContactsInfoFieldsUpdated = 0;
ContactPtr contactFoo = contacts[0];
ContactPtr contactBar = contacts[1];
QCOMPARE(contactFoo->infoFields().isValid(), true);
QCOMPARE(contactFoo->infoFields().allFields().size(), 1);
QCOMPARE(contactFoo->infoFields().allFields()[0].fieldName, QLatin1String("n"));
QCOMPARE(contactFoo->infoFields().allFields()[0].fieldValue[0], QLatin1String("Foo"));
QCOMPARE(contactBar->infoFields().isValid(), true);
QCOMPARE(contactBar->infoFields().allFields().size(), 1);
QCOMPARE(contactBar->infoFields().allFields()[0].fieldName, QLatin1String("n"));
QCOMPARE(contactBar->infoFields().allFields()[0].fieldValue[0], QLatin1String("Bar"));
mContactsInfoFieldsUpdated = 0;
Q_FOREACH (const ContactPtr &contact, contacts) {
PendingOperation *op = contact->refreshInfo();
QVERIFY(connect(op,
SIGNAL(finished(Tp::PendingOperation*)),
SLOT(expectSuccessfulCall(Tp::PendingOperation*))));
QCOMPARE(mLoop->exec(), 0);
}
while (mContactsInfoFieldsUpdated != contacts.size()) {
mLoop->processEvents();
}
QCOMPARE(mContactsInfoFieldsUpdated, contacts.size());
for (int i = 0; i < contacts.size(); i++) {
ContactPtr contact = contacts[i];
QVERIFY(disconnect(contact.data(),
SIGNAL(infoFieldsChanged(const Tp::Contact::InfoFields &)),
this,
SLOT(onContactInfoFieldsChanged(const Tp::Contact::InfoFields &))));
}
PendingContactInfo *pci = contactFoo->requestInfo();
QVERIFY(connect(pci,
SIGNAL(finished(Tp::PendingOperation*)),
SLOT(expectSuccessfulCall(Tp::PendingOperation*))));
while (!pci->isFinished()) {
QCOMPARE(mLoop->exec(), 0);
}
QCOMPARE(pci->infoFields().isValid(), true);
QCOMPARE(pci->infoFields().allFields().size(), 1);
QCOMPARE(pci->infoFields().allFields()[0].fieldName, QLatin1String("n"));
QCOMPARE(pci->infoFields().allFields()[0].fieldValue[0], QLatin1String("FooBar"));
g_boxed_free(TP_ARRAY_TYPE_CONTACT_INFO_FIELD_LIST, info_default);
g_boxed_free(TP_ARRAY_TYPE_CONTACT_INFO_FIELD_LIST, info_1);
g_boxed_free(TP_ARRAY_TYPE_CONTACT_INFO_FIELD_LIST, info_2);
}
void TestContactsInfo::cleanup()
{
cleanupImpl();
}
void TestContactsInfo::cleanupTestCase()
{
QCOMPARE(mConn->disconnect(), true);
delete mConn;
cleanupTestCaseImpl();
}
QTEST_MAIN(TestContactsInfo)
#include "_gen/contacts-info.cpp.moc.hpp"
<commit_msg>contacts-info test: Add test to check how many times RefreshContactInfo is called.<commit_after>#include <tests/lib/test.h>
#include <tests/lib/glib-helpers/test-conn-helper.h>
#include <tests/lib/glib/contacts-conn.h>
#include <TelepathyQt4/Connection>
#include <TelepathyQt4/Contact>
#include <TelepathyQt4/ContactManager>
#include <TelepathyQt4/PendingContacts>
#include <TelepathyQt4/PendingContactInfo>
#include <telepathy-glib/debug.h>
using namespace Tp;
class TestContactsInfo : public Test
{
Q_OBJECT
public:
TestContactsInfo(QObject *parent = 0)
: Test(parent), mConn(0), mContactsInfoFieldsUpdated(0)
{ }
protected Q_SLOTS:
void onContactInfoFieldsChanged(const Tp::Contact::InfoFields &);
private Q_SLOTS:
void initTestCase();
void init();
void testInfo();
void cleanup();
void cleanupTestCase();
private:
TestConnHelper *mConn;
int mContactsInfoFieldsUpdated;
};
void TestContactsInfo::onContactInfoFieldsChanged(const Tp::Contact::InfoFields &info)
{
Q_UNUSED(info);
mContactsInfoFieldsUpdated++;
}
void TestContactsInfo::initTestCase()
{
initTestCaseImpl();
g_type_init();
g_set_prgname("contacts-info");
tp_debug_set_flags("all");
dbus_g_bus_get(DBUS_BUS_STARTER, 0);
mConn = new TestConnHelper(this,
TP_TESTS_TYPE_CONTACTS_CONNECTION,
"account", "[email protected]",
"protocol", "foo",
NULL);
QCOMPARE(mConn->connect(), true);
}
void TestContactsInfo::init()
{
initImpl();
mContactsInfoFieldsUpdated = 0;
}
void TestContactsInfo::testInfo()
{
ContactManagerPtr contactManager = mConn->client()->contactManager();
QVERIFY(contactManager->supportedFeatures().contains(Contact::FeatureInfo));
QStringList validIDs = QStringList() << QLatin1String("foo")
<< QLatin1String("bar");
QList<ContactPtr> contacts = mConn->contacts(validIDs, Contact::FeatureInfo);
QCOMPARE(contacts.size(), validIDs.size());
for (int i = 0; i < contacts.size(); i++) {
ContactPtr contact = contacts[i];
QCOMPARE(contact->requestedFeatures().contains(Contact::FeatureInfo), true);
QCOMPARE(contact->actualFeatures().contains(Contact::FeatureInfo), true);
QVERIFY(contact->infoFields().allFields().isEmpty());
QVERIFY(connect(contact.data(),
SIGNAL(infoFieldsChanged(const Tp::Contact::InfoFields &)),
SLOT(onContactInfoFieldsChanged(const Tp::Contact::InfoFields &))));
}
GPtrArray *info_default = (GPtrArray *) dbus_g_type_specialized_construct (
TP_ARRAY_TYPE_CONTACT_INFO_FIELD_LIST);
{
const gchar * const field_values[2] = {
"FooBar", NULL
};
g_ptr_array_add (info_default, tp_value_array_build (3,
G_TYPE_STRING, "n",
G_TYPE_STRV, NULL,
G_TYPE_STRV, field_values,
G_TYPE_INVALID));
}
tp_tests_contacts_connection_set_default_contact_info(TP_TESTS_CONTACTS_CONNECTION(mConn->service()),
info_default);
GPtrArray *info_1 = (GPtrArray *) dbus_g_type_specialized_construct (
TP_ARRAY_TYPE_CONTACT_INFO_FIELD_LIST);
{
const gchar * const field_values[2] = {
"Foo", NULL
};
g_ptr_array_add (info_1, tp_value_array_build (3,
G_TYPE_STRING, "n",
G_TYPE_STRV, NULL,
G_TYPE_STRV, field_values,
G_TYPE_INVALID));
}
GPtrArray *info_2 = (GPtrArray *) dbus_g_type_specialized_construct (
TP_ARRAY_TYPE_CONTACT_INFO_FIELD_LIST);
{
const gchar * const field_values[2] = {
"Bar", NULL
};
g_ptr_array_add (info_2, tp_value_array_build (3,
G_TYPE_STRING, "n",
G_TYPE_STRV, NULL,
G_TYPE_STRV, field_values,
G_TYPE_INVALID));
}
TpHandle handles[] = { 0, 0 };
TpHandleRepoIface *serviceRepo = tp_base_connection_get_handles(
TP_BASE_CONNECTION(mConn->service()), TP_HANDLE_TYPE_CONTACT);
for (unsigned i = 0; i < 2; i++) {
handles[i] = tp_handle_ensure(serviceRepo, qPrintable(validIDs[i]),
NULL, NULL);
}
tp_tests_contacts_connection_change_contact_info(TP_TESTS_CONTACTS_CONNECTION(mConn->service()),
handles[0], info_1);
tp_tests_contacts_connection_change_contact_info(TP_TESTS_CONTACTS_CONNECTION(mConn->service()),
handles[1], info_2);
while (mContactsInfoFieldsUpdated != 2) {
mLoop->processEvents();
}
QCOMPARE(mContactsInfoFieldsUpdated, 2);
mContactsInfoFieldsUpdated = 0;
ContactPtr contactFoo = contacts[0];
ContactPtr contactBar = contacts[1];
QCOMPARE(contactFoo->infoFields().isValid(), true);
QCOMPARE(contactFoo->infoFields().allFields().size(), 1);
QCOMPARE(contactFoo->infoFields().allFields()[0].fieldName, QLatin1String("n"));
QCOMPARE(contactFoo->infoFields().allFields()[0].fieldValue[0], QLatin1String("Foo"));
QCOMPARE(contactBar->infoFields().isValid(), true);
QCOMPARE(contactBar->infoFields().allFields().size(), 1);
QCOMPARE(contactBar->infoFields().allFields()[0].fieldName, QLatin1String("n"));
QCOMPARE(contactBar->infoFields().allFields()[0].fieldValue[0], QLatin1String("Bar"));
TpTestsContactsConnection *serviceConn = TP_TESTS_CONTACTS_CONNECTION(mConn->service());
QCOMPARE(serviceConn->refresh_contact_info_called, static_cast<uint>(0));
mContactsInfoFieldsUpdated = 0;
Q_FOREACH (const ContactPtr &contact, contacts) {
QVERIFY(contact->refreshInfo());
}
while (mContactsInfoFieldsUpdated != contacts.size()) {
mLoop->processEvents();
}
QCOMPARE(mContactsInfoFieldsUpdated, contacts.size());
QCOMPARE(serviceConn->refresh_contact_info_called, static_cast<uint>(contacts.size()));
for (int i = 0; i < contacts.size(); i++) {
ContactPtr contact = contacts[i];
QVERIFY(disconnect(contact.data(),
SIGNAL(infoFieldsChanged(const Tp::Contact::InfoFields &)),
this,
SLOT(onContactInfoFieldsChanged(const Tp::Contact::InfoFields &))));
}
PendingContactInfo *pci = contactFoo->requestInfo();
QVERIFY(connect(pci,
SIGNAL(finished(Tp::PendingOperation*)),
SLOT(expectSuccessfulCall(Tp::PendingOperation*))));
while (!pci->isFinished()) {
QCOMPARE(mLoop->exec(), 0);
}
QCOMPARE(pci->infoFields().isValid(), true);
QCOMPARE(pci->infoFields().allFields().size(), 1);
QCOMPARE(pci->infoFields().allFields()[0].fieldName, QLatin1String("n"));
QCOMPARE(pci->infoFields().allFields()[0].fieldValue[0], QLatin1String("FooBar"));
g_boxed_free(TP_ARRAY_TYPE_CONTACT_INFO_FIELD_LIST, info_default);
g_boxed_free(TP_ARRAY_TYPE_CONTACT_INFO_FIELD_LIST, info_1);
g_boxed_free(TP_ARRAY_TYPE_CONTACT_INFO_FIELD_LIST, info_2);
}
void TestContactsInfo::cleanup()
{
cleanupImpl();
}
void TestContactsInfo::cleanupTestCase()
{
QCOMPARE(mConn->disconnect(), true);
delete mConn;
cleanupTestCaseImpl();
}
QTEST_MAIN(TestContactsInfo)
#include "_gen/contacts-info.cpp.moc.hpp"
<|endoftext|> |
<commit_before>// Copyright 2018 The Crashpad Authors. 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 "client/crashpad_client.h"
#include <fcntl.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include "base/logging.h"
#include "base/strings/stringprintf.h"
#include "client/client_argv_handling.h"
#include "util/file/file_io.h"
#include "util/linux/exception_handler_client.h"
#include "util/linux/exception_information.h"
#include "util/linux/scoped_pr_set_dumpable.h"
#include "util/linux/scoped_pr_set_ptracer.h"
#include "util/misc/from_pointer_cast.h"
#include "util/posix/double_fork_and_exec.h"
#include "util/posix/signals.h"
namespace crashpad {
namespace {
std::string FormatArgumentInt(const std::string& name, int value) {
return base::StringPrintf("--%s=%d", name.c_str(), value);
}
std::string FormatArgumentAddress(const std::string& name, void* addr) {
return base::StringPrintf("--%s=%p", name.c_str(), addr);
}
#if defined(OS_ANDROID)
std::vector<std::string> BuildAppProcessArgs(
const std::string& class_name,
const base::FilePath& database,
const base::FilePath& metrics_dir,
const std::string& url,
const std::map<std::string, std::string>& annotations,
const std::vector<std::string>& arguments,
int socket) {
std::vector<std::string> argv;
#if defined(ARCH_CPU_64_BITS)
argv.push_back("/system/bin/app_process64");
#else
argv.push_back("/system/bin/app_process32");
#endif
argv.push_back("/system/bin");
argv.push_back("--application");
argv.push_back(class_name);
std::vector<std::string> handler_argv = BuildHandlerArgvStrings(
base::FilePath(), database, metrics_dir, url, annotations, arguments);
if (socket != kInvalidFileHandle) {
handler_argv.push_back(FormatArgumentInt("initial-client-fd", socket));
}
argv.insert(argv.end(), handler_argv.begin() + 1, handler_argv.end());
return argv;
}
std::vector<std::string> BuildArgsToLaunchWithLinker(
const std::string& handler_trampoline,
const std::string& handler_library,
bool is_64_bit,
const base::FilePath& database,
const base::FilePath& metrics_dir,
const std::string& url,
const std::map<std::string, std::string>& annotations,
const std::vector<std::string>& arguments,
int socket) {
std::vector<std::string> argv;
if (is_64_bit) {
argv.push_back("/system/bin/linker64");
} else {
argv.push_back("/system/bin/linker");
}
argv.push_back(handler_trampoline);
argv.push_back(handler_library);
std::vector<std::string> handler_argv = BuildHandlerArgvStrings(
base::FilePath(), database, metrics_dir, url, annotations, arguments);
if (socket != kInvalidFileHandle) {
handler_argv.push_back(FormatArgumentInt("initial-client-fd", socket));
}
argv.insert(argv.end(), handler_argv.begin() + 1, handler_argv.end());
return argv;
}
#endif // OS_ANDROID
// Launches a single use handler to snapshot this process.
class LaunchAtCrashHandler {
public:
static LaunchAtCrashHandler* Get() {
static LaunchAtCrashHandler* instance = new LaunchAtCrashHandler();
return instance;
}
bool Initialize(std::vector<std::string>* argv_in,
const std::vector<std::string>* envp) {
argv_strings_.swap(*argv_in);
if (envp) {
envp_strings_ = *envp;
StringVectorToCStringVector(envp_strings_, &envp_);
set_envp_ = true;
}
argv_strings_.push_back(FormatArgumentAddress("trace-parent-with-exception",
&exception_information_));
StringVectorToCStringVector(argv_strings_, &argv_);
return Signals::InstallCrashHandlers(HandleCrash, 0, &old_actions_);
}
bool HandleCrashNonFatal(int signo, siginfo_t* siginfo, void* context) {
if (first_chance_handler_ &&
first_chance_handler_(
signo, siginfo, static_cast<ucontext_t*>(context))) {
return true;
}
exception_information_.siginfo_address =
FromPointerCast<decltype(exception_information_.siginfo_address)>(
siginfo);
exception_information_.context_address =
FromPointerCast<decltype(exception_information_.context_address)>(
context);
exception_information_.thread_id = syscall(SYS_gettid);
ScopedPrSetPtracer set_ptracer(getpid(), /* may_log= */ false);
ScopedPrSetDumpable set_dumpable(/* may_log= */ false);
pid_t pid = fork();
if (pid < 0) {
return false;
}
if (pid == 0) {
if (set_envp_) {
execve(argv_[0],
const_cast<char* const*>(argv_.data()),
const_cast<char* const*>(envp_.data()));
} else {
execv(argv_[0], const_cast<char* const*>(argv_.data()));
}
_exit(EXIT_FAILURE);
}
int status;
waitpid(pid, &status, 0);
return false;
}
void HandleCrashFatal(int signo, siginfo_t* siginfo, void* context) {
if (enabled_ && HandleCrashNonFatal(signo, siginfo, context)) {
return;
}
Signals::RestoreHandlerAndReraiseSignalOnReturn(
siginfo, old_actions_.ActionForSignal(signo));
}
void SetFirstChanceHandler(CrashpadClient::FirstChanceHandler handler) {
first_chance_handler_ = handler;
}
static void Disable() { enabled_ = false; }
private:
LaunchAtCrashHandler() = default;
~LaunchAtCrashHandler() = delete;
static void HandleCrash(int signo, siginfo_t* siginfo, void* context) {
auto state = Get();
state->HandleCrashFatal(signo, siginfo, context);
}
Signals::OldActions old_actions_ = {};
std::vector<std::string> argv_strings_;
std::vector<const char*> argv_;
std::vector<std::string> envp_strings_;
std::vector<const char*> envp_;
ExceptionInformation exception_information_;
CrashpadClient::FirstChanceHandler first_chance_handler_ = nullptr;
bool set_envp_ = false;
static thread_local bool enabled_;
DISALLOW_COPY_AND_ASSIGN(LaunchAtCrashHandler);
};
thread_local bool LaunchAtCrashHandler::enabled_ = true;
// A pointer to the currently installed crash signal handler. This allows
// the static method CrashpadClient::DumpWithoutCrashing to simulate a crash
// using the currently configured crash handling strategy.
static LaunchAtCrashHandler* g_crash_handler;
} // namespace
CrashpadClient::CrashpadClient() {}
CrashpadClient::~CrashpadClient() {}
bool CrashpadClient::StartHandler(
const base::FilePath& handler,
const base::FilePath& database,
const base::FilePath& metrics_dir,
const std::string& url,
const std::map<std::string, std::string>& annotations,
const std::vector<std::string>& arguments,
bool restartable,
bool asynchronous_start) {
// TODO(jperaza): Implement this after the Android/Linux ExceptionHandlerSever
// supports accepting new connections.
// https://crashpad.chromium.org/bug/30
NOTREACHED();
return false;
}
#if defined(OS_ANDROID)
// static
bool CrashpadClient::StartJavaHandlerAtCrash(
const std::string& class_name,
const std::vector<std::string>* env,
const base::FilePath& database,
const base::FilePath& metrics_dir,
const std::string& url,
const std::map<std::string, std::string>& annotations,
const std::vector<std::string>& arguments) {
std::vector<std::string> argv = BuildAppProcessArgs(class_name,
database,
metrics_dir,
url,
annotations,
arguments,
kInvalidFileHandle);
auto signal_handler = LaunchAtCrashHandler::Get();
if (signal_handler->Initialize(&argv, env)) {
DCHECK(!g_crash_handler);
g_crash_handler = signal_handler;
return true;
}
return false;
}
// static
bool CrashpadClient::StartJavaHandlerForClient(
const std::string& class_name,
const std::vector<std::string>* env,
const base::FilePath& database,
const base::FilePath& metrics_dir,
const std::string& url,
const std::map<std::string, std::string>& annotations,
const std::vector<std::string>& arguments,
int socket) {
std::vector<std::string> argv = BuildAppProcessArgs(
class_name, database, metrics_dir, url, annotations, arguments, socket);
return DoubleForkAndExec(argv, env, socket, false, nullptr);
}
// static
bool CrashpadClient::StartHandlerWithLinkerAtCrash(
const std::string& handler_trampoline,
const std::string& handler_library,
bool is_64_bit,
const std::vector<std::string>* env,
const base::FilePath& database,
const base::FilePath& metrics_dir,
const std::string& url,
const std::map<std::string, std::string>& annotations,
const std::vector<std::string>& arguments) {
std::vector<std::string> argv =
BuildArgsToLaunchWithLinker(handler_trampoline,
handler_library,
is_64_bit,
database,
metrics_dir,
url,
annotations,
arguments,
kInvalidFileHandle);
auto signal_handler = LaunchAtCrashHandler::Get();
if (signal_handler->Initialize(&argv, env)) {
DCHECK(!g_crash_handler);
g_crash_handler = signal_handler;
return true;
}
return false;
}
// static
bool CrashpadClient::StartHandlerWithLinkerForClient(
const std::string& handler_trampoline,
const std::string& handler_library,
bool is_64_bit,
const std::vector<std::string>* env,
const base::FilePath& database,
const base::FilePath& metrics_dir,
const std::string& url,
const std::map<std::string, std::string>& annotations,
const std::vector<std::string>& arguments,
int socket) {
std::vector<std::string> argv =
BuildArgsToLaunchWithLinker(handler_trampoline,
handler_library,
is_64_bit,
database,
metrics_dir,
url,
annotations,
arguments,
socket);
return DoubleForkAndExec(argv, env, socket, false, nullptr);
}
#endif
// static
bool CrashpadClient::StartHandlerAtCrash(
const base::FilePath& handler,
const base::FilePath& database,
const base::FilePath& metrics_dir,
const std::string& url,
const std::map<std::string, std::string>& annotations,
const std::vector<std::string>& arguments) {
std::vector<std::string> argv = BuildHandlerArgvStrings(
handler, database, metrics_dir, url, annotations, arguments);
auto signal_handler = LaunchAtCrashHandler::Get();
if (signal_handler->Initialize(&argv, nullptr)) {
DCHECK(!g_crash_handler);
g_crash_handler = signal_handler;
return true;
}
return false;
}
// static
bool CrashpadClient::StartHandlerForClient(
const base::FilePath& handler,
const base::FilePath& database,
const base::FilePath& metrics_dir,
const std::string& url,
const std::map<std::string, std::string>& annotations,
const std::vector<std::string>& arguments,
int socket) {
std::vector<std::string> argv = BuildHandlerArgvStrings(
handler, database, metrics_dir, url, annotations, arguments);
argv.push_back(FormatArgumentInt("initial-client-fd", socket));
return DoubleForkAndExec(argv, nullptr, socket, true, nullptr);
}
// static
void CrashpadClient::DumpWithoutCrash(NativeCPUContext* context) {
DCHECK(g_crash_handler);
#if defined(ARCH_CPU_ARMEL)
memset(context->uc_regspace, 0, sizeof(context->uc_regspace));
#elif defined(ARCH_CPU_ARM64)
memset(context->uc_mcontext.__reserved,
0,
sizeof(context->uc_mcontext.__reserved));
#endif
siginfo_t siginfo;
siginfo.si_signo = Signals::kSimulatedSigno;
siginfo.si_errno = 0;
siginfo.si_code = 0;
g_crash_handler->HandleCrashNonFatal(
siginfo.si_signo, &siginfo, reinterpret_cast<void*>(context));
}
// static
void CrashpadClient::CrashWithoutDump(const std::string& message) {
LaunchAtCrashHandler::Disable();
LOG(FATAL) << message;
}
// static
void CrashpadClient::SetFirstChanceExceptionHandler(
FirstChanceHandler handler) {
DCHECK(g_crash_handler);
g_crash_handler->SetFirstChanceHandler(handler);
}
} // namespace crashpad
<commit_msg>linux: Disable DumpWithoutCrash() if Crashpad isn't initialized<commit_after>// Copyright 2018 The Crashpad Authors. 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 "client/crashpad_client.h"
#include <fcntl.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include "base/logging.h"
#include "base/strings/stringprintf.h"
#include "client/client_argv_handling.h"
#include "util/file/file_io.h"
#include "util/linux/exception_handler_client.h"
#include "util/linux/exception_information.h"
#include "util/linux/scoped_pr_set_dumpable.h"
#include "util/linux/scoped_pr_set_ptracer.h"
#include "util/misc/from_pointer_cast.h"
#include "util/posix/double_fork_and_exec.h"
#include "util/posix/signals.h"
namespace crashpad {
namespace {
std::string FormatArgumentInt(const std::string& name, int value) {
return base::StringPrintf("--%s=%d", name.c_str(), value);
}
std::string FormatArgumentAddress(const std::string& name, void* addr) {
return base::StringPrintf("--%s=%p", name.c_str(), addr);
}
#if defined(OS_ANDROID)
std::vector<std::string> BuildAppProcessArgs(
const std::string& class_name,
const base::FilePath& database,
const base::FilePath& metrics_dir,
const std::string& url,
const std::map<std::string, std::string>& annotations,
const std::vector<std::string>& arguments,
int socket) {
std::vector<std::string> argv;
#if defined(ARCH_CPU_64_BITS)
argv.push_back("/system/bin/app_process64");
#else
argv.push_back("/system/bin/app_process32");
#endif
argv.push_back("/system/bin");
argv.push_back("--application");
argv.push_back(class_name);
std::vector<std::string> handler_argv = BuildHandlerArgvStrings(
base::FilePath(), database, metrics_dir, url, annotations, arguments);
if (socket != kInvalidFileHandle) {
handler_argv.push_back(FormatArgumentInt("initial-client-fd", socket));
}
argv.insert(argv.end(), handler_argv.begin() + 1, handler_argv.end());
return argv;
}
std::vector<std::string> BuildArgsToLaunchWithLinker(
const std::string& handler_trampoline,
const std::string& handler_library,
bool is_64_bit,
const base::FilePath& database,
const base::FilePath& metrics_dir,
const std::string& url,
const std::map<std::string, std::string>& annotations,
const std::vector<std::string>& arguments,
int socket) {
std::vector<std::string> argv;
if (is_64_bit) {
argv.push_back("/system/bin/linker64");
} else {
argv.push_back("/system/bin/linker");
}
argv.push_back(handler_trampoline);
argv.push_back(handler_library);
std::vector<std::string> handler_argv = BuildHandlerArgvStrings(
base::FilePath(), database, metrics_dir, url, annotations, arguments);
if (socket != kInvalidFileHandle) {
handler_argv.push_back(FormatArgumentInt("initial-client-fd", socket));
}
argv.insert(argv.end(), handler_argv.begin() + 1, handler_argv.end());
return argv;
}
#endif // OS_ANDROID
// Launches a single use handler to snapshot this process.
class LaunchAtCrashHandler {
public:
static LaunchAtCrashHandler* Get() {
static LaunchAtCrashHandler* instance = new LaunchAtCrashHandler();
return instance;
}
bool Initialize(std::vector<std::string>* argv_in,
const std::vector<std::string>* envp) {
argv_strings_.swap(*argv_in);
if (envp) {
envp_strings_ = *envp;
StringVectorToCStringVector(envp_strings_, &envp_);
set_envp_ = true;
}
argv_strings_.push_back(FormatArgumentAddress("trace-parent-with-exception",
&exception_information_));
StringVectorToCStringVector(argv_strings_, &argv_);
return Signals::InstallCrashHandlers(HandleCrash, 0, &old_actions_);
}
bool HandleCrashNonFatal(int signo, siginfo_t* siginfo, void* context) {
if (first_chance_handler_ &&
first_chance_handler_(
signo, siginfo, static_cast<ucontext_t*>(context))) {
return true;
}
exception_information_.siginfo_address =
FromPointerCast<decltype(exception_information_.siginfo_address)>(
siginfo);
exception_information_.context_address =
FromPointerCast<decltype(exception_information_.context_address)>(
context);
exception_information_.thread_id = syscall(SYS_gettid);
ScopedPrSetPtracer set_ptracer(getpid(), /* may_log= */ false);
ScopedPrSetDumpable set_dumpable(/* may_log= */ false);
pid_t pid = fork();
if (pid < 0) {
return false;
}
if (pid == 0) {
if (set_envp_) {
execve(argv_[0],
const_cast<char* const*>(argv_.data()),
const_cast<char* const*>(envp_.data()));
} else {
execv(argv_[0], const_cast<char* const*>(argv_.data()));
}
_exit(EXIT_FAILURE);
}
int status;
waitpid(pid, &status, 0);
return false;
}
void HandleCrashFatal(int signo, siginfo_t* siginfo, void* context) {
if (enabled_ && HandleCrashNonFatal(signo, siginfo, context)) {
return;
}
Signals::RestoreHandlerAndReraiseSignalOnReturn(
siginfo, old_actions_.ActionForSignal(signo));
}
void SetFirstChanceHandler(CrashpadClient::FirstChanceHandler handler) {
first_chance_handler_ = handler;
}
static void Disable() { enabled_ = false; }
private:
LaunchAtCrashHandler() = default;
~LaunchAtCrashHandler() = delete;
static void HandleCrash(int signo, siginfo_t* siginfo, void* context) {
auto state = Get();
state->HandleCrashFatal(signo, siginfo, context);
}
Signals::OldActions old_actions_ = {};
std::vector<std::string> argv_strings_;
std::vector<const char*> argv_;
std::vector<std::string> envp_strings_;
std::vector<const char*> envp_;
ExceptionInformation exception_information_;
CrashpadClient::FirstChanceHandler first_chance_handler_ = nullptr;
bool set_envp_ = false;
static thread_local bool enabled_;
DISALLOW_COPY_AND_ASSIGN(LaunchAtCrashHandler);
};
thread_local bool LaunchAtCrashHandler::enabled_ = true;
// A pointer to the currently installed crash signal handler. This allows
// the static method CrashpadClient::DumpWithoutCrashing to simulate a crash
// using the currently configured crash handling strategy.
static LaunchAtCrashHandler* g_crash_handler;
} // namespace
CrashpadClient::CrashpadClient() {}
CrashpadClient::~CrashpadClient() {}
bool CrashpadClient::StartHandler(
const base::FilePath& handler,
const base::FilePath& database,
const base::FilePath& metrics_dir,
const std::string& url,
const std::map<std::string, std::string>& annotations,
const std::vector<std::string>& arguments,
bool restartable,
bool asynchronous_start) {
// TODO(jperaza): Implement this after the Android/Linux ExceptionHandlerSever
// supports accepting new connections.
// https://crashpad.chromium.org/bug/30
NOTREACHED();
return false;
}
#if defined(OS_ANDROID)
// static
bool CrashpadClient::StartJavaHandlerAtCrash(
const std::string& class_name,
const std::vector<std::string>* env,
const base::FilePath& database,
const base::FilePath& metrics_dir,
const std::string& url,
const std::map<std::string, std::string>& annotations,
const std::vector<std::string>& arguments) {
std::vector<std::string> argv = BuildAppProcessArgs(class_name,
database,
metrics_dir,
url,
annotations,
arguments,
kInvalidFileHandle);
auto signal_handler = LaunchAtCrashHandler::Get();
if (signal_handler->Initialize(&argv, env)) {
DCHECK(!g_crash_handler);
g_crash_handler = signal_handler;
return true;
}
return false;
}
// static
bool CrashpadClient::StartJavaHandlerForClient(
const std::string& class_name,
const std::vector<std::string>* env,
const base::FilePath& database,
const base::FilePath& metrics_dir,
const std::string& url,
const std::map<std::string, std::string>& annotations,
const std::vector<std::string>& arguments,
int socket) {
std::vector<std::string> argv = BuildAppProcessArgs(
class_name, database, metrics_dir, url, annotations, arguments, socket);
return DoubleForkAndExec(argv, env, socket, false, nullptr);
}
// static
bool CrashpadClient::StartHandlerWithLinkerAtCrash(
const std::string& handler_trampoline,
const std::string& handler_library,
bool is_64_bit,
const std::vector<std::string>* env,
const base::FilePath& database,
const base::FilePath& metrics_dir,
const std::string& url,
const std::map<std::string, std::string>& annotations,
const std::vector<std::string>& arguments) {
std::vector<std::string> argv =
BuildArgsToLaunchWithLinker(handler_trampoline,
handler_library,
is_64_bit,
database,
metrics_dir,
url,
annotations,
arguments,
kInvalidFileHandle);
auto signal_handler = LaunchAtCrashHandler::Get();
if (signal_handler->Initialize(&argv, env)) {
DCHECK(!g_crash_handler);
g_crash_handler = signal_handler;
return true;
}
return false;
}
// static
bool CrashpadClient::StartHandlerWithLinkerForClient(
const std::string& handler_trampoline,
const std::string& handler_library,
bool is_64_bit,
const std::vector<std::string>* env,
const base::FilePath& database,
const base::FilePath& metrics_dir,
const std::string& url,
const std::map<std::string, std::string>& annotations,
const std::vector<std::string>& arguments,
int socket) {
std::vector<std::string> argv =
BuildArgsToLaunchWithLinker(handler_trampoline,
handler_library,
is_64_bit,
database,
metrics_dir,
url,
annotations,
arguments,
socket);
return DoubleForkAndExec(argv, env, socket, false, nullptr);
}
#endif
// static
bool CrashpadClient::StartHandlerAtCrash(
const base::FilePath& handler,
const base::FilePath& database,
const base::FilePath& metrics_dir,
const std::string& url,
const std::map<std::string, std::string>& annotations,
const std::vector<std::string>& arguments) {
std::vector<std::string> argv = BuildHandlerArgvStrings(
handler, database, metrics_dir, url, annotations, arguments);
auto signal_handler = LaunchAtCrashHandler::Get();
if (signal_handler->Initialize(&argv, nullptr)) {
DCHECK(!g_crash_handler);
g_crash_handler = signal_handler;
return true;
}
return false;
}
// static
bool CrashpadClient::StartHandlerForClient(
const base::FilePath& handler,
const base::FilePath& database,
const base::FilePath& metrics_dir,
const std::string& url,
const std::map<std::string, std::string>& annotations,
const std::vector<std::string>& arguments,
int socket) {
std::vector<std::string> argv = BuildHandlerArgvStrings(
handler, database, metrics_dir, url, annotations, arguments);
argv.push_back(FormatArgumentInt("initial-client-fd", socket));
return DoubleForkAndExec(argv, nullptr, socket, true, nullptr);
}
// static
void CrashpadClient::DumpWithoutCrash(NativeCPUContext* context) {
if (!g_crash_handler) {
DLOG(ERROR) << "Crashpad isn't enabled";
return;
}
#if defined(ARCH_CPU_ARMEL)
memset(context->uc_regspace, 0, sizeof(context->uc_regspace));
#elif defined(ARCH_CPU_ARM64)
memset(context->uc_mcontext.__reserved,
0,
sizeof(context->uc_mcontext.__reserved));
#endif
siginfo_t siginfo;
siginfo.si_signo = Signals::kSimulatedSigno;
siginfo.si_errno = 0;
siginfo.si_code = 0;
g_crash_handler->HandleCrashNonFatal(
siginfo.si_signo, &siginfo, reinterpret_cast<void*>(context));
}
// static
void CrashpadClient::CrashWithoutDump(const std::string& message) {
LaunchAtCrashHandler::Disable();
LOG(FATAL) << message;
}
// static
void CrashpadClient::SetFirstChanceExceptionHandler(
FirstChanceHandler handler) {
DCHECK(g_crash_handler);
g_crash_handler->SetFirstChanceHandler(handler);
}
} // namespace crashpad
<|endoftext|> |
<commit_before>#ifndef ENTT_CORE_MEMORY_HPP
#define ENTT_CORE_MEMORY_HPP
#include <cstddef>
#include <limits>
#include <memory>
#include <type_traits>
#include <utility>
#include "../config/config.h"
namespace entt {
/**
* @brief Unwraps fancy pointers, does nothing otherwise (waiting for C++20).
* @tparam Type Pointer type.
* @param ptr Fancy or raw pointer.
* @return A raw pointer that represents the address of the original pointer.
*/
template<typename Type>
[[nodiscard]] constexpr auto to_address(Type &&ptr) ENTT_NOEXCEPT {
if constexpr(std::is_pointer_v<std::remove_const_t<std::remove_reference_t<Type>>>) {
return ptr;
} else {
return to_address(std::forward<Type>(ptr).operator->());
}
}
/**
* @brief Utility function to design allocation-aware containers.
* @tparam Allocator Type of allocator.
* @param lhs A valid allocator.
* @param rhs Another valid allocator.
*/
template<typename Allocator>
constexpr void propagate_on_container_copy_assignment([[maybe_unused]] Allocator &lhs, [[maybe_unused]] Allocator &rhs) ENTT_NOEXCEPT {
if constexpr(std::allocator_traits<Allocator>::propagate_on_container_copy_assignment::value) {
lhs = rhs;
}
}
/**
* @brief Utility function to design allocation-aware containers.
* @tparam Allocator Type of allocator.
* @param lhs A valid allocator.
* @param rhs Another valid allocator.
*/
template<typename Allocator>
constexpr void propagate_on_container_move_assignment([[maybe_unused]] Allocator &lhs, [[maybe_unused]] Allocator &rhs) ENTT_NOEXCEPT {
if constexpr(std::allocator_traits<Allocator>::propagate_on_container_move_assignment::value) {
lhs = std::move(rhs);
}
}
/**
* @brief Utility function to design allocation-aware containers.
* @tparam Allocator Type of allocator.
* @param lhs A valid allocator.
* @param rhs Another valid allocator.
*/
template<typename Allocator>
constexpr void propagate_on_container_swap([[maybe_unused]] Allocator &lhs, [[maybe_unused]] Allocator &rhs) ENTT_NOEXCEPT {
ENTT_ASSERT(std::allocator_traits<Allocator>::propagate_on_container_swap::value || lhs == rhs, "Cannot swap the containers");
if constexpr(std::allocator_traits<Allocator>::propagate_on_container_swap::value) {
using std::swap;
swap(lhs, rhs);
}
}
/**
* @brief Checks whether a value is a power of two or not.
* @param value A value that may or may not be a power of two.
* @return True if the value is a power of two, false otherwise.
*/
[[nodiscard]] inline constexpr bool is_power_of_two(const std::size_t value) ENTT_NOEXCEPT {
return value && ((value & (value - 1)) == 0);
}
/**
* @brief Computes the smallest power of two greater than or equal to a value.
* @param value The value to use.
* @return The smallest power of two greater than or equal to the given value.
*/
[[nodiscard]] inline constexpr std::size_t next_power_of_two(const std::size_t value) ENTT_NOEXCEPT {
ENTT_ASSERT(value < (std::size_t{1u} << (std::numeric_limits<std::size_t>::digits - 1)), "Numeric limits exceeded");
std::size_t curr = value - (value != 0u);
for(int next = 1; next < std::numeric_limits<std::size_t>::digits; next = next * 2) {
curr |= curr >> next;
}
return ++curr;
}
/**
* @brief Fast module utility function (powers of two only).
* @param value A value for which to calculate the modulus.
* @param mod _Modulus_, it must be a power of two.
* @return The common remainder.
*/
[[nodiscard]] inline constexpr std::size_t fast_mod(const std::size_t value, const std::size_t mod) ENTT_NOEXCEPT {
ENTT_ASSERT(is_power_of_two(mod), "Value must be a power of two");
return value & (mod - 1u);
}
/**
* @brief General purpose deleter for allocator-aware unique pointers.
* @tparam Args Types of arguments to use to construct the object.
*/
template<typename Allocator>
struct allocation_deleter: private Allocator {
/*! @brief Allocator type. */
using allocator_type = Allocator;
/*! @brief Pointer type. */
using pointer = typename std::allocator_traits<Allocator>::pointer;
/**
* @brief Inherited constructors.
* @param allocator The allocator to use.
*/
allocation_deleter(const allocator_type &allocator)
: Allocator{allocator} {}
/**
* @brief Destroys the pointed object and deallocates its memory.
* @param ptr A valid pointer to an object of the given type.
*/
void operator()(pointer ptr) {
using alloc_traits = typename std::allocator_traits<Allocator>;
alloc_traits::destroy(*this, to_address(ptr));
alloc_traits::deallocate(*this, ptr, 1u);
}
};
/**
* @brief Allows `std::unique_ptr` to use allocators.
* @tparam Type Type of object to allocate for and to construct.
* @tparam Allocator Type of allocator used to manage memory and elements.
* @tparam Args Types of arguments to use to construct the object.
* @param allocator The allocator to use.
* @param args Parameters to use to construct an object for the entity.
* @return A properly initialized unique pointer with a custom deleter.
*/
template<typename Type, typename Allocator, typename... Args>
auto allocate_unique(Allocator &allocator, Args &&...args) {
using alloc = typename std::allocator_traits<Allocator>::template rebind_alloc<Type>;
using alloc_traits = typename std::allocator_traits<alloc>;
alloc type_allocator{allocator};
auto ptr = alloc_traits::allocate(type_allocator, 1u);
ENTT_TRY {
alloc_traits::construct(type_allocator, to_address(ptr), std::forward<Args>(args)...);
}
ENTT_CATCH {
alloc_traits::deallocate(type_allocator, ptr, 1u);
ENTT_THROW;
}
return std::unique_ptr<Type, allocation_deleter<alloc>>{ptr, type_allocator};
}
} // namespace entt
#endif
<commit_msg>memory: suppress a (shadow) warning from gcc<commit_after>#ifndef ENTT_CORE_MEMORY_HPP
#define ENTT_CORE_MEMORY_HPP
#include <cstddef>
#include <limits>
#include <memory>
#include <type_traits>
#include <utility>
#include "../config/config.h"
namespace entt {
/**
* @brief Unwraps fancy pointers, does nothing otherwise (waiting for C++20).
* @tparam Type Pointer type.
* @param ptr Fancy or raw pointer.
* @return A raw pointer that represents the address of the original pointer.
*/
template<typename Type>
[[nodiscard]] constexpr auto to_address(Type &&ptr) ENTT_NOEXCEPT {
if constexpr(std::is_pointer_v<std::remove_const_t<std::remove_reference_t<Type>>>) {
return ptr;
} else {
return to_address(std::forward<Type>(ptr).operator->());
}
}
/**
* @brief Utility function to design allocation-aware containers.
* @tparam Allocator Type of allocator.
* @param lhs A valid allocator.
* @param rhs Another valid allocator.
*/
template<typename Allocator>
constexpr void propagate_on_container_copy_assignment([[maybe_unused]] Allocator &lhs, [[maybe_unused]] Allocator &rhs) ENTT_NOEXCEPT {
if constexpr(std::allocator_traits<Allocator>::propagate_on_container_copy_assignment::value) {
lhs = rhs;
}
}
/**
* @brief Utility function to design allocation-aware containers.
* @tparam Allocator Type of allocator.
* @param lhs A valid allocator.
* @param rhs Another valid allocator.
*/
template<typename Allocator>
constexpr void propagate_on_container_move_assignment([[maybe_unused]] Allocator &lhs, [[maybe_unused]] Allocator &rhs) ENTT_NOEXCEPT {
if constexpr(std::allocator_traits<Allocator>::propagate_on_container_move_assignment::value) {
lhs = std::move(rhs);
}
}
/**
* @brief Utility function to design allocation-aware containers.
* @tparam Allocator Type of allocator.
* @param lhs A valid allocator.
* @param rhs Another valid allocator.
*/
template<typename Allocator>
constexpr void propagate_on_container_swap([[maybe_unused]] Allocator &lhs, [[maybe_unused]] Allocator &rhs) ENTT_NOEXCEPT {
ENTT_ASSERT(std::allocator_traits<Allocator>::propagate_on_container_swap::value || lhs == rhs, "Cannot swap the containers");
if constexpr(std::allocator_traits<Allocator>::propagate_on_container_swap::value) {
using std::swap;
swap(lhs, rhs);
}
}
/**
* @brief Checks whether a value is a power of two or not.
* @param value A value that may or may not be a power of two.
* @return True if the value is a power of two, false otherwise.
*/
[[nodiscard]] inline constexpr bool is_power_of_two(const std::size_t value) ENTT_NOEXCEPT {
return value && ((value & (value - 1)) == 0);
}
/**
* @brief Computes the smallest power of two greater than or equal to a value.
* @param value The value to use.
* @return The smallest power of two greater than or equal to the given value.
*/
[[nodiscard]] inline constexpr std::size_t next_power_of_two(const std::size_t value) ENTT_NOEXCEPT {
ENTT_ASSERT(value < (std::size_t{1u} << (std::numeric_limits<std::size_t>::digits - 1)), "Numeric limits exceeded");
std::size_t curr = value - (value != 0u);
for(int next = 1; next < std::numeric_limits<std::size_t>::digits; next = next * 2) {
curr |= curr >> next;
}
return ++curr;
}
/**
* @brief Fast module utility function (powers of two only).
* @param value A value for which to calculate the modulus.
* @param mod _Modulus_, it must be a power of two.
* @return The common remainder.
*/
[[nodiscard]] inline constexpr std::size_t fast_mod(const std::size_t value, const std::size_t mod) ENTT_NOEXCEPT {
ENTT_ASSERT(is_power_of_two(mod), "Value must be a power of two");
return value & (mod - 1u);
}
/**
* @brief General purpose deleter for allocator-aware unique pointers.
* @tparam Args Types of arguments to use to construct the object.
*/
template<typename Allocator>
struct allocation_deleter: private Allocator {
/*! @brief Allocator type. */
using allocator_type = Allocator;
/*! @brief Pointer type. */
using pointer = typename std::allocator_traits<Allocator>::pointer;
/**
* @brief Inherited constructors.
* @param alloc The allocator to use.
*/
allocation_deleter(const allocator_type &alloc)
: Allocator{alloc} {}
/**
* @brief Destroys the pointed object and deallocates its memory.
* @param ptr A valid pointer to an object of the given type.
*/
void operator()(pointer ptr) {
using alloc_traits = typename std::allocator_traits<Allocator>;
alloc_traits::destroy(*this, to_address(ptr));
alloc_traits::deallocate(*this, ptr, 1u);
}
};
/**
* @brief Allows `std::unique_ptr` to use allocators.
* @tparam Type Type of object to allocate for and to construct.
* @tparam Allocator Type of allocator used to manage memory and elements.
* @tparam Args Types of arguments to use to construct the object.
* @param allocator The allocator to use.
* @param args Parameters to use to construct an object for the entity.
* @return A properly initialized unique pointer with a custom deleter.
*/
template<typename Type, typename Allocator, typename... Args>
auto allocate_unique(Allocator &allocator, Args &&...args) {
using alloc = typename std::allocator_traits<Allocator>::template rebind_alloc<Type>;
using alloc_traits = typename std::allocator_traits<alloc>;
alloc type_allocator{allocator};
auto ptr = alloc_traits::allocate(type_allocator, 1u);
ENTT_TRY {
alloc_traits::construct(type_allocator, to_address(ptr), std::forward<Args>(args)...);
}
ENTT_CATCH {
alloc_traits::deallocate(type_allocator, ptr, 1u);
ENTT_THROW;
}
return std::unique_ptr<Type, allocation_deleter<alloc>>{ptr, type_allocator};
}
} // namespace entt
#endif
<|endoftext|> |
<commit_before>#include "stdafx.h"
/*
* Copyright (c) 2007-2009 SlimDX Group
*
* 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 <d3d10.h>
#include <d3dx10.h>
#include "../stack_array.h"
#include "BlendState.h"
#include "DepthStencilState.h"
#include "DepthStencilView.h"
#include "OutputMergerWrapper.h"
#include "RenderTargetView.h"
using namespace System;
namespace SlimDX
{
namespace Direct3D10
{
OutputMergerWrapper::OutputMergerWrapper( ID3D10Device* device )
{
if( device == 0 )
throw gcnew ArgumentNullException( "device" );
m_Device = device;
}
void OutputMergerWrapper::DepthStencilState::set( SlimDX::Direct3D10::DepthStencilState^ value )
{
ID3D10DepthStencilState* oldState;
int oldReference;
m_Device->OMGetDepthStencilState( &oldState, reinterpret_cast<UINT*>( &oldReference ) );
oldState->Release();
if( value == nullptr )
m_Device->OMSetDepthStencilState( 0, oldReference );
else
m_Device->OMSetDepthStencilState( value->InternalPointer, oldReference );
}
SlimDX::Direct3D10::DepthStencilState^ OutputMergerWrapper::DepthStencilState::get()
{
ID3D10DepthStencilState* oldState = 0;
int oldReference = 0;
m_Device->OMGetDepthStencilState( &oldState, reinterpret_cast<UINT*>( &oldReference ) );
return SlimDX::Direct3D10::DepthStencilState::FromPointer( oldState );
}
void OutputMergerWrapper::DepthStencilReference::set( int value )
{
ID3D10DepthStencilState* oldState = 0;
int oldReference = 0;
m_Device->OMGetDepthStencilState( &oldState, reinterpret_cast<UINT*>( &oldReference ) );
m_Device->OMSetDepthStencilState( oldState, value );
oldState->Release();
}
int OutputMergerWrapper::DepthStencilReference::get()
{
ID3D10DepthStencilState* oldState = 0;
int oldReference = 0;
m_Device->OMGetDepthStencilState( &oldState, reinterpret_cast<UINT*>( &oldReference ) );
oldState->Release();
return oldReference;
}
void OutputMergerWrapper::BlendState::set( SlimDX::Direct3D10::BlendState^ value )
{
ID3D10BlendState* oldState = 0;
float oldFactor[4];
int oldMask = 0;
m_Device->OMGetBlendState( &oldState, oldFactor, reinterpret_cast<UINT*>( &oldMask ) );
oldState->Release();
if( value == nullptr )
m_Device->OMSetBlendState( 0, oldFactor, oldMask );
else
m_Device->OMSetBlendState( value->InternalPointer, oldFactor, oldMask );
}
SlimDX::Direct3D10::BlendState^ OutputMergerWrapper::BlendState::get()
{
ID3D10BlendState* oldState = 0;
float oldFactor[4];
int oldMask = 0;
m_Device->OMGetBlendState( &oldState, oldFactor, reinterpret_cast<UINT*>( &oldMask ) );
return SlimDX::Direct3D10::BlendState::FromPointer( oldState );
}
void OutputMergerWrapper::BlendFactor::set( Color4 value )
{
ID3D10BlendState* oldState = 0;
float oldFactor[4];
int oldMask = 0;
m_Device->OMGetBlendState( &oldState, oldFactor, reinterpret_cast<UINT*>( &oldMask ) );
float newFactor[4] = { value.Red, value.Green, value.Blue, value.Alpha };
m_Device->OMSetBlendState( oldState, newFactor, oldMask );
oldState->Release();
}
Color4 OutputMergerWrapper::BlendFactor::get()
{
ID3D10BlendState* oldState = 0;
float oldFactor[4];
int oldMask = 0;
m_Device->OMGetBlendState( &oldState, oldFactor, reinterpret_cast<UINT*>( &oldMask ) );
oldState->Release();
return Color4( oldFactor[3], oldFactor[0], oldFactor[1], oldFactor[2] );
}
void OutputMergerWrapper::BlendSampleMask::set( int value )
{
ID3D10BlendState* oldState = 0;
float oldFactor[4];
int oldMask = 0;
m_Device->OMGetBlendState( &oldState, oldFactor, reinterpret_cast<UINT*>( &oldMask ) );
m_Device->OMSetBlendState( oldState, oldFactor, value );
oldState->Release();
}
int OutputMergerWrapper::BlendSampleMask::get()
{
ID3D10BlendState* oldState = 0;
float oldFactor[4];
int oldMask = 0;
m_Device->OMGetBlendState( &oldState, oldFactor, reinterpret_cast<UINT*>( &oldMask ) );
oldState->Release();
return oldMask;
}
void OutputMergerWrapper::SetTargets( RenderTargetView^ renderTargetView )
{
SetTargets( nullptr, renderTargetView );
}
void OutputMergerWrapper::SetTargets( DepthStencilView^ depthStencilView, RenderTargetView^ renderTargetView )
{
ID3D10DepthStencilView *nativeDSV = depthStencilView == nullptr ? 0 : static_cast<ID3D10DepthStencilView*>( depthStencilView->InternalPointer );
ID3D10RenderTargetView *nativeRTV[] = { renderTargetView == nullptr ? 0 : static_cast<ID3D10RenderTargetView*>( renderTargetView->InternalPointer ) };
m_Device->OMSetRenderTargets( 1, nativeRTV, nativeDSV );
}
void OutputMergerWrapper::SetTargets( ... array<RenderTargetView^>^ renderTargets )
{
SetTargets( nullptr, renderTargets );
}
void OutputMergerWrapper::SetTargets( DepthStencilView^ depthStencilView, ... array<RenderTargetView^>^ renderTargets )
{
ID3D10DepthStencilView *nativeDSV = depthStencilView == nullptr ? 0 : static_cast<ID3D10DepthStencilView*>( depthStencilView->InternalPointer );
ID3D10RenderTargetView* nativeRTVs[D3D10_SIMULTANEOUS_RENDER_TARGET_COUNT];
if( renderTargets == nullptr )
{
m_Device->OMSetRenderTargets( 0, 0, nativeDSV );
}
else
{
for( int i = 0; i < renderTargets->Length; ++i )
nativeRTVs[ i ] = renderTargets[ i ] == nullptr ? 0 : static_cast<ID3D10RenderTargetView*>( renderTargets[ i ]->InternalPointer );
m_Device->OMSetRenderTargets( renderTargets->Length, nativeRTVs, nativeDSV );
}
}
DepthStencilView^ OutputMergerWrapper::GetDepthStencilView()
{
ID3D10DepthStencilView *view;
m_Device->OMGetRenderTargets( 0, 0, &view );
return DepthStencilView::FromPointer( view );
}
array<RenderTargetView^>^ OutputMergerWrapper::GetRenderTargets( int count )
{
stack_array<ID3D10RenderTargetView*> targets = stackalloc( ID3D10RenderTargetView*, count );
array<RenderTargetView^>^ results = gcnew array<RenderTargetView^>( count );
m_Device->OMGetRenderTargets( count, &targets[0], 0 );
for( int i = 0; i < count; i++ )
results[i] = RenderTargetView::FromPointer( targets[i] );
return results;
}
}
}
<commit_msg>Added null checks to oldState->Release in OutputMergerWrapper. Fixes issue 536.<commit_after>#include "stdafx.h"
/*
* Copyright (c) 2007-2009 SlimDX Group
*
* 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 <d3d10.h>
#include <d3dx10.h>
#include "../stack_array.h"
#include "BlendState.h"
#include "DepthStencilState.h"
#include "DepthStencilView.h"
#include "OutputMergerWrapper.h"
#include "RenderTargetView.h"
using namespace System;
namespace SlimDX
{
namespace Direct3D10
{
OutputMergerWrapper::OutputMergerWrapper( ID3D10Device* device )
{
if( device == 0 )
throw gcnew ArgumentNullException( "device" );
m_Device = device;
}
void OutputMergerWrapper::DepthStencilState::set( SlimDX::Direct3D10::DepthStencilState^ value )
{
ID3D10DepthStencilState* oldState;
int oldReference;
m_Device->OMGetDepthStencilState( &oldState, reinterpret_cast<UINT*>( &oldReference ) );
if( oldState != NULL )
oldState->Release();
if( value == nullptr )
m_Device->OMSetDepthStencilState( 0, oldReference );
else
m_Device->OMSetDepthStencilState( value->InternalPointer, oldReference );
}
SlimDX::Direct3D10::DepthStencilState^ OutputMergerWrapper::DepthStencilState::get()
{
ID3D10DepthStencilState* oldState = 0;
int oldReference = 0;
m_Device->OMGetDepthStencilState( &oldState, reinterpret_cast<UINT*>( &oldReference ) );
return SlimDX::Direct3D10::DepthStencilState::FromPointer( oldState );
}
void OutputMergerWrapper::DepthStencilReference::set( int value )
{
ID3D10DepthStencilState* oldState = 0;
int oldReference = 0;
m_Device->OMGetDepthStencilState( &oldState, reinterpret_cast<UINT*>( &oldReference ) );
m_Device->OMSetDepthStencilState( oldState, value );
if( oldState != NULL )
oldState->Release();
}
int OutputMergerWrapper::DepthStencilReference::get()
{
ID3D10DepthStencilState* oldState = 0;
int oldReference = 0;
m_Device->OMGetDepthStencilState( &oldState, reinterpret_cast<UINT*>( &oldReference ) );
if( oldState != NULL )
oldState->Release();
return oldReference;
}
void OutputMergerWrapper::BlendState::set( SlimDX::Direct3D10::BlendState^ value )
{
ID3D10BlendState* oldState = 0;
float oldFactor[4];
int oldMask = 0;
m_Device->OMGetBlendState( &oldState, oldFactor, reinterpret_cast<UINT*>( &oldMask ) );
if( oldState != NULL )
oldState->Release();
if( value == nullptr )
m_Device->OMSetBlendState( 0, oldFactor, oldMask );
else
m_Device->OMSetBlendState( value->InternalPointer, oldFactor, oldMask );
}
SlimDX::Direct3D10::BlendState^ OutputMergerWrapper::BlendState::get()
{
ID3D10BlendState* oldState = 0;
float oldFactor[4];
int oldMask = 0;
m_Device->OMGetBlendState( &oldState, oldFactor, reinterpret_cast<UINT*>( &oldMask ) );
return SlimDX::Direct3D10::BlendState::FromPointer( oldState );
}
void OutputMergerWrapper::BlendFactor::set( Color4 value )
{
ID3D10BlendState* oldState = 0;
float oldFactor[4];
int oldMask = 0;
m_Device->OMGetBlendState( &oldState, oldFactor, reinterpret_cast<UINT*>( &oldMask ) );
float newFactor[4] = { value.Red, value.Green, value.Blue, value.Alpha };
m_Device->OMSetBlendState( oldState, newFactor, oldMask );
if( oldState != NULL )
oldState->Release();
}
Color4 OutputMergerWrapper::BlendFactor::get()
{
ID3D10BlendState* oldState = 0;
float oldFactor[4];
int oldMask = 0;
m_Device->OMGetBlendState( &oldState, oldFactor, reinterpret_cast<UINT*>( &oldMask ) );
if( oldState != NULL )
oldState->Release();
return Color4( oldFactor[3], oldFactor[0], oldFactor[1], oldFactor[2] );
}
void OutputMergerWrapper::BlendSampleMask::set( int value )
{
ID3D10BlendState* oldState = 0;
float oldFactor[4];
int oldMask = 0;
m_Device->OMGetBlendState( &oldState, oldFactor, reinterpret_cast<UINT*>( &oldMask ) );
m_Device->OMSetBlendState( oldState, oldFactor, value );
if( oldState != NULL )
oldState->Release();
}
int OutputMergerWrapper::BlendSampleMask::get()
{
ID3D10BlendState* oldState = 0;
float oldFactor[4];
int oldMask = 0;
m_Device->OMGetBlendState( &oldState, oldFactor, reinterpret_cast<UINT*>( &oldMask ) );
if( oldState != NULL )
oldState->Release();
return oldMask;
}
void OutputMergerWrapper::SetTargets( RenderTargetView^ renderTargetView )
{
SetTargets( nullptr, renderTargetView );
}
void OutputMergerWrapper::SetTargets( DepthStencilView^ depthStencilView, RenderTargetView^ renderTargetView )
{
ID3D10DepthStencilView *nativeDSV = depthStencilView == nullptr ? 0 : static_cast<ID3D10DepthStencilView*>( depthStencilView->InternalPointer );
ID3D10RenderTargetView *nativeRTV[] = { renderTargetView == nullptr ? 0 : static_cast<ID3D10RenderTargetView*>( renderTargetView->InternalPointer ) };
m_Device->OMSetRenderTargets( 1, nativeRTV, nativeDSV );
}
void OutputMergerWrapper::SetTargets( ... array<RenderTargetView^>^ renderTargets )
{
SetTargets( nullptr, renderTargets );
}
void OutputMergerWrapper::SetTargets( DepthStencilView^ depthStencilView, ... array<RenderTargetView^>^ renderTargets )
{
ID3D10DepthStencilView *nativeDSV = depthStencilView == nullptr ? 0 : static_cast<ID3D10DepthStencilView*>( depthStencilView->InternalPointer );
ID3D10RenderTargetView* nativeRTVs[D3D10_SIMULTANEOUS_RENDER_TARGET_COUNT];
if( renderTargets == nullptr )
{
m_Device->OMSetRenderTargets( 0, 0, nativeDSV );
}
else
{
for( int i = 0; i < renderTargets->Length; ++i )
nativeRTVs[ i ] = renderTargets[ i ] == nullptr ? 0 : static_cast<ID3D10RenderTargetView*>( renderTargets[ i ]->InternalPointer );
m_Device->OMSetRenderTargets( renderTargets->Length, nativeRTVs, nativeDSV );
}
}
DepthStencilView^ OutputMergerWrapper::GetDepthStencilView()
{
ID3D10DepthStencilView *view;
m_Device->OMGetRenderTargets( 0, 0, &view );
return DepthStencilView::FromPointer( view );
}
array<RenderTargetView^>^ OutputMergerWrapper::GetRenderTargets( int count )
{
stack_array<ID3D10RenderTargetView*> targets = stackalloc( ID3D10RenderTargetView*, count );
array<RenderTargetView^>^ results = gcnew array<RenderTargetView^>( count );
m_Device->OMGetRenderTargets( count, &targets[0], 0 );
for( int i = 0; i < count; i++ )
results[i] = RenderTargetView::FromPointer( targets[i] );
return results;
}
}
}
<|endoftext|> |
<commit_before>//
// poNodeContainer.cpp
// BasicScene
//
// Created by Stephen Varga on 3/22/14.
//
//
#include "poNodeContainer.h"
namespace po {
NodeContainerRef NodeContainer::create(std::string name)
{
return std::shared_ptr<NodeContainer>(new NodeContainer(name));
}
NodeContainer::NodeContainer(std::string name)
: Node(name)
{
}
//------------------------------------------------------
#pragma mark - Scene -
void NodeContainer::setScene(SceneRef scene)
{
Node::setScene(scene);
for(NodeRef &childNode : mChildren) {
childNode->setScene(scene);
}
}
void NodeContainer::removeScene()
{
Node::removeScene();
for(NodeRef &childNode : mChildren) {
childNode->removeScene();
}
}
//------------------------------------------------------
#pragma mark - Add Children -
void NodeContainer::addChild(NodeRef node)
{
setParentAndScene(node);
mChildren.push_back(node);
}
void NodeContainer::addChildAt(int index, NodeRef node)
{
setParentAndScene(node);
mChildren.insert(mChildren.begin()+index, node);
}
void NodeContainer::addChildBefore(NodeRef before, NodeRef node)
{
setParentAndScene(node);
mChildren.insert(mChildren.begin() + getChildIndex(before), node);
}
void NodeContainer::addChildAfter(NodeRef after, NodeRef node)
{
setParentAndScene(node);
mChildren.insert(mChildren.begin() + getChildIndex(after)+1, node);
}
//------------------------------------------------------
#pragma mark - Get Children -
std::vector<NodeRef> NodeContainer::getChildren()
{
return mChildren;
};
std::vector<NodeRef>& NodeContainer::getChildrenByReference()
{
return mChildren;
}
int NodeContainer::getChildIndex(const NodeRef& child)
{
std::vector<NodeRef>::iterator iter = std::find(mChildren.begin(), mChildren.end(), child);
if(iter != mChildren.end())
return (int)std::distance(mChildren.begin(), iter);
return INVALID_INDEX;
}
NodeRef NodeContainer::getChildByIndex(int index)
{
if(index < 0 || index >= mChildren.size())
return NodeRef();
return *(mChildren.begin() + index);
}
NodeRef NodeContainer::getChildByUID(uint32_t uid)
{
//Go through our tree to find any node with UID
for(NodeRef& node : mChildren) {
NodeContainerRef container = std::dynamic_pointer_cast<NodeContainer>(node);
if(container) {
NodeRef foundNode = container->getChildByUID(uid);
if(foundNode) return foundNode;
}
else {
if(node->getUID() == uid) return node;
}
}
//See if it is us
if(mUid == uid) return shared_from_this();
//Not found
return NodeRef();
}
NodeRef NodeContainer::getChildByName(const std::string &name)
{
for(NodeRef& node : mChildren) {
if(node->getName() == name) return node;
}
return NodeRef();
}
NodeRef NodeContainer::getFirstChild()
{
if(mChildren.empty())
return NodeRef();
return mChildren.front();
}
NodeRef NodeContainer::getLastChild()
{
if(mChildren.empty())
return NodeRef();
return mChildren.back();
}
//------------------------------------------------------
#pragma mark - Remove Children -
bool NodeContainer::removeChild(NodeRef node)
{
std::vector<NodeRef>::iterator iter = std::find(mChildren.begin(), mChildren.end(), node);
if(iter != mChildren.end()) {
(*iter)->removeParent();
(*iter)->removeScene();
#pragma message "This is not safe in recursion..."
mChildren.erase(iter);
return true;
}
return false;
}
bool NodeContainer::removeChildAt(int index)
{
if(index <= 0 || index >= mChildren.size())
return false;
mChildren[index]->removeParent();
mChildren[index]->removeScene();
mChildren.erase(mChildren.begin() + index);
return true;
}
void NodeContainer::removeAllChildren()
{
for(NodeRef& node : mChildren) {
node->removeParent();
node->removeScene();
}
mChildren.clear();
}
//------------------------------------------------------
#pragma mark - Move Children -
void NodeContainer::moveChildToFront(NodeRef& node)
{
if(removeChild(node))
addChild(node);
}
void NodeContainer::moveChildForward(NodeRef& node)
{
int idx = getChildIndex(node);
if(removeChild(node))
#pragma message "Does this work with a vector, or would this be out of bounds?"
addChildAt(std::min(idx+1, getNumChildren()), node);
}
void NodeContainer::moveChildToBack(NodeRef& node)
{
if(removeChild(node))
addChildAt(0, node);
}
void NodeContainer::moveChildBackward(NodeRef& node)
{
int idx = getChildIndex(node);
if(removeChild(node))
addChildAt(std::max(idx-1, 0), node);
}
void NodeContainer::setParentAndScene(NodeRef node)
{
//See if the node is already a child of another node.
if(node->getParent())
node->getParent()->removeChild(node);
//Assign ourselves as the parent
node->setParent(std::dynamic_pointer_cast<NodeContainer>(shared_from_this()));
node->setScene(mScene.lock());
}
//------------------------------------------------------
#pragma mark - Update and Draw Trees -
void NodeContainer::updateTree()
{
update();
for(NodeRef &childNode : mChildren)
childNode->updateTree();
}
void NodeContainer::drawTree()
{
#pragma message "Need to implement matrix order"
ci::gl::pushMatrices();
setTransformation();
draw();
for(NodeRef &childNode : mChildren) {
childNode->drawTree();
#pragma message "For testing, should be removed"
ci::gl::color(0,255,0);
ci::gl::drawStrokedRect(childNode->getFrame());
}
if(mDrawBounds)
drawBounds();
ci::gl::popMatrices();
}
//------------------------------------------------------
#pragma mark - Dimensions -
ci::Rectf NodeContainer::getBounds()
{
//Reset Bounds
ci::Rectf bounds = ci::Rectf(0,0,0,0);
for(NodeRef &childNode : mChildren)
bounds.include(childNode->getFrame());
return bounds;
}
bool NodeContainer::pointInside(const ci::Vec2f &point)
{
for (NodeRef node : mChildren) {
if (node->pointInside(point)) {
return true;
}
}
return false;
}
}<commit_msg>Checking objects for visibility before including frame in bounds<commit_after>//
// poNodeContainer.cpp
// BasicScene
//
// Created by Stephen Varga on 3/22/14.
//
//
#include "poNodeContainer.h"
namespace po {
NodeContainerRef NodeContainer::create(std::string name)
{
return std::shared_ptr<NodeContainer>(new NodeContainer(name));
}
NodeContainer::NodeContainer(std::string name)
: Node(name)
{
}
//------------------------------------------------------
#pragma mark - Scene -
void NodeContainer::setScene(SceneRef scene)
{
Node::setScene(scene);
for(NodeRef &childNode : mChildren) {
childNode->setScene(scene);
}
}
void NodeContainer::removeScene()
{
Node::removeScene();
for(NodeRef &childNode : mChildren) {
childNode->removeScene();
}
}
//------------------------------------------------------
#pragma mark - Add Children -
void NodeContainer::addChild(NodeRef node)
{
setParentAndScene(node);
mChildren.push_back(node);
}
void NodeContainer::addChildAt(int index, NodeRef node)
{
setParentAndScene(node);
mChildren.insert(mChildren.begin()+index, node);
}
void NodeContainer::addChildBefore(NodeRef before, NodeRef node)
{
setParentAndScene(node);
mChildren.insert(mChildren.begin() + getChildIndex(before), node);
}
void NodeContainer::addChildAfter(NodeRef after, NodeRef node)
{
setParentAndScene(node);
mChildren.insert(mChildren.begin() + getChildIndex(after)+1, node);
}
//------------------------------------------------------
#pragma mark - Get Children -
std::vector<NodeRef> NodeContainer::getChildren()
{
return mChildren;
};
std::vector<NodeRef>& NodeContainer::getChildrenByReference()
{
return mChildren;
}
int NodeContainer::getChildIndex(const NodeRef& child)
{
std::vector<NodeRef>::iterator iter = std::find(mChildren.begin(), mChildren.end(), child);
if(iter != mChildren.end())
return (int)std::distance(mChildren.begin(), iter);
return INVALID_INDEX;
}
NodeRef NodeContainer::getChildByIndex(int index)
{
if(index < 0 || index >= mChildren.size())
return NodeRef();
return *(mChildren.begin() + index);
}
NodeRef NodeContainer::getChildByUID(uint32_t uid)
{
//Go through our tree to find any node with UID
for(NodeRef& node : mChildren) {
NodeContainerRef container = std::dynamic_pointer_cast<NodeContainer>(node);
if(container) {
NodeRef foundNode = container->getChildByUID(uid);
if(foundNode) return foundNode;
}
else {
if(node->getUID() == uid) return node;
}
}
//See if it is us
if(mUid == uid) return shared_from_this();
//Not found
return NodeRef();
}
NodeRef NodeContainer::getChildByName(const std::string &name)
{
for(NodeRef& node : mChildren) {
if(node->getName() == name) return node;
}
return NodeRef();
}
NodeRef NodeContainer::getFirstChild()
{
if(mChildren.empty())
return NodeRef();
return mChildren.front();
}
NodeRef NodeContainer::getLastChild()
{
if(mChildren.empty())
return NodeRef();
return mChildren.back();
}
//------------------------------------------------------
#pragma mark - Remove Children -
bool NodeContainer::removeChild(NodeRef node)
{
std::vector<NodeRef>::iterator iter = std::find(mChildren.begin(), mChildren.end(), node);
if(iter != mChildren.end()) {
(*iter)->removeParent();
(*iter)->removeScene();
#pragma message "This is not safe in recursion..."
mChildren.erase(iter);
return true;
}
return false;
}
bool NodeContainer::removeChildAt(int index)
{
if(index <= 0 || index >= mChildren.size())
return false;
mChildren[index]->removeParent();
mChildren[index]->removeScene();
mChildren.erase(mChildren.begin() + index);
return true;
}
void NodeContainer::removeAllChildren()
{
for(NodeRef& node : mChildren) {
node->removeParent();
node->removeScene();
}
mChildren.clear();
}
//------------------------------------------------------
#pragma mark - Move Children -
void NodeContainer::moveChildToFront(NodeRef& node)
{
if(removeChild(node))
addChild(node);
}
void NodeContainer::moveChildForward(NodeRef& node)
{
int idx = getChildIndex(node);
if(removeChild(node))
#pragma message "Does this work with a vector, or would this be out of bounds?"
addChildAt(std::min(idx+1, getNumChildren()), node);
}
void NodeContainer::moveChildToBack(NodeRef& node)
{
if(removeChild(node))
addChildAt(0, node);
}
void NodeContainer::moveChildBackward(NodeRef& node)
{
int idx = getChildIndex(node);
if(removeChild(node))
addChildAt(std::max(idx-1, 0), node);
}
void NodeContainer::setParentAndScene(NodeRef node)
{
//See if the node is already a child of another node.
if(node->getParent())
node->getParent()->removeChild(node);
//Assign ourselves as the parent
node->setParent(std::dynamic_pointer_cast<NodeContainer>(shared_from_this()));
node->setScene(mScene.lock());
}
//------------------------------------------------------
#pragma mark - Update and Draw Trees -
void NodeContainer::updateTree()
{
update();
for(NodeRef &childNode : mChildren)
childNode->updateTree();
}
void NodeContainer::drawTree()
{
#pragma message "Need to implement matrix order"
ci::gl::pushMatrices();
setTransformation();
draw();
for(NodeRef &childNode : mChildren) {
childNode->drawTree();
#pragma message "For testing, should be removed"
//ci::gl::color(0,255,0);
//ci::gl::drawStrokedRect(childNode->getFrame());
}
if(mDrawBounds)
drawBounds();
ci::gl::popMatrices();
}
//------------------------------------------------------
#pragma mark - Dimensions -
ci::Rectf NodeContainer::getBounds()
{
//Reset Bounds
ci::Rectf bounds = ci::Rectf(0,0,0,0);
for(NodeRef &childNode : mChildren) {
if(childNode->isVisible())
bounds.include(childNode->getFrame());
}
return bounds;
}
bool NodeContainer::pointInside(const ci::Vec2f &point)
{
for (NodeRef node : mChildren) {
if (node->pointInside(point)) {
return true;
}
}
return false;
}
}<|endoftext|> |
<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2014. All rights reserved
*/
#include "../../StroikaPreComp.h"
#include "../../Characters/String_Constant.h"
#include "../../Debug/Trace.h"
#include "../../Execution/ErrNoException.h"
#include "InternetAddress.h"
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Characters;
using namespace Stroika::Foundation::Memory;
using namespace Stroika::Foundation::IO;
using namespace Stroika::Foundation::IO::Network;
#define qSupportPTONAndPTON_ (qPlatform_POSIX || (qPlatformWindows && (NTDDI_VERSION >= NTDDI_VISTA)))
#if qCompilerAndStdLib_constexpr_union_variants_Buggy
const InternetAddress V4::kAddrAny = InternetAddress (in_addr {});
const InternetAddress V6::kAddrAny = InternetAddress (in6_addr {});
#if qPlatform_POSIX
const InternetAddress V4::kLocalhost = InternetAddress (in_addr { INADDR_LOOPBACK } );
#elif qPlatform_Windows
const InternetAddress V4::kLocalhost = InternetAddress (in_addr { { { 0x1, 0x0, 0x0, 0x7f } } } );
#endif
const InternetAddress V6::kLocalhost = InternetAddress (in6_addr { { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 } } } );
#endif
#if qPlatform_Windows
// Not sure why this is necessary, but we get link errors sometimes without it... Maybe a windows makefile issue on regtest apps?
// -- LGP 2014-11-06
#pragma comment(lib, "Ws2_32.lib")
#endif
/*
********************************************************************************
********************* IO::Network::InternetAddress *****************************
********************************************************************************
*/
InternetAddress::InternetAddress (const string& s, AddressFamily af)
: fAddressFamily_ (AddressFamily::UNKNOWN)
{
if (not s.empty ()) {
if (af == AddressFamily::UNKNOWN) {
// guess format - based on '.' versus ':' in name
if (s.find ('.') != string::npos) {
af = AddressFamily::V4;
}
else if (s.find (':') != string::npos) {
af = AddressFamily::V6;
}
}
switch (af) {
case AddressFamily::V4: {
#if qSupportPTONAndPTON_
Execution::ThrowErrNoIfNegative (inet_pton (AF_INET, s.c_str (), &fV4_));
#elif qPlatform_Windows
DISABLE_COMPILER_MSC_WARNING_START(4996) // msft doesnt have this on old platforms but still warns!
fV4_.s_addr = ::inet_addr (s.c_str ());
DISABLE_COMPILER_MSC_WARNING_END(4996)
#else
AssertNotImplemented ();
#endif
fAddressFamily_ = af;
}
break;
case AddressFamily::V6: {
#if qSupportPTONAndPTON_
Execution::ThrowErrNoIfNegative (inet_pton (AF_INET6, s.c_str (), &fV6_));
#else
AssertNotImplemented ();
#endif
fAddressFamily_ = af;
}
break;
default: {
// @todo need better exception
Execution::DoThrow (Execution::StringException (String_Constant (L"Unrecognized address family")));
}
break;
}
}
}
InternetAddress::InternetAddress (const String& s, AddressFamily af)
: InternetAddress (s.AsUTF8 (), af)
{
}
namespace Stroika {
namespace Foundation {
namespace IO {
namespace Network {
template <>
String InternetAddress::As<String> () const
{
switch (fAddressFamily_) {
case AddressFamily::UNKNOWN: {
return String ();
}
break;
case AddressFamily::V4: {
#if qSupportPTONAndPTON_
char buf[INET_ADDRSTRLEN + 1];
const char* result = ::inet_ntop (AF_INET, &fV4_, buf, sizeof (buf));
return result == nullptr ? String () : String::FromUTF8 (result);
#else
DISABLE_COMPILER_MSC_WARNING_START(4996) // msft doesnt have this on old platforms but still warns!
return String::FromUTF8 (::inet_ntoa (fV4_));
DISABLE_COMPILER_MSC_WARNING_END(4996)
#endif
}
break;
case AddressFamily::V6: {
#if qSupportPTONAndPTON_
char buf[INET6_ADDRSTRLEN + 1];
const char* result = ::inet_ntop (AF_INET6, &fV6_, buf, sizeof (buf));
return result == nullptr ? String () : String::FromUTF8 (result);
#else
AssertNotImplemented ();
return String ();
#endif
}
break;
default: {
RequireNotReached ();
return String ();
}
break;
}
}
}
}
}
}
bool InternetAddress::IsLocalhostAddress () const
{
Require (not empty ());
switch (fAddressFamily_) {
case AddressFamily::V4: {
// 127.0.0.x
//return (::ntohl (fV4_.s_addr) & 0xffffff00) == 0x7f000000;
return (ntohl (fV4_.s_addr) & 0x00ffffff) == 0x00007f;
}
break;
case AddressFamily::V6: {
return
fV6_.s6_addr[0] == 0 and
fV6_.s6_addr[1] == 0 and
fV6_.s6_addr[2] == 0 and
fV6_.s6_addr[3] == 0 and
fV6_.s6_addr[4] == 0 and
fV6_.s6_addr[5] == 0 and
fV6_.s6_addr[6] == 0 and
fV6_.s6_addr[7] == 0 and
fV6_.s6_addr[8] == 0 and
fV6_.s6_addr[9] == 0 and
fV6_.s6_addr[10] == 0 and
fV6_.s6_addr[11] == 0 and
fV6_.s6_addr[12] == 0 and
fV6_.s6_addr[13] == 0 and
fV6_.s6_addr[14] == 0 and
fV6_.s6_addr[15] == 1
;
}
break;
}
AssertNotReached ();
return false;
}
bool InternetAddress::IsLinkLocalAddress () const
{
Require (not empty ());
switch (fAddressFamily_) {
case AddressFamily::V4: {
static const InternetAddress kMinLinkLocal_ { "169.254.0.1" };
static const InternetAddress kMaxLinkLocal_ { "169.254.255.254" };
return kMinLinkLocal_ <= *this and * this <= kMaxLinkLocal_;
}
break;
case AddressFamily::V6: {
return
fV6_.s6_addr[0] == 0xfe and fV6_.s6_addr[1] == 0x80 and
fV6_.s6_addr[2] == 0x0 and fV6_.s6_addr[3] == 0x0 and
fV6_.s6_addr[4] == 0x0 and fV6_.s6_addr[5] == 0x0 and
fV6_.s6_addr[6] == 0x0 and fV6_.s6_addr[7] == 0x0
;
}
break;
}
AssertNotReached ();
return false;
}
bool InternetAddress::IsPrivateAddress () const
{
#if qDebug && defined (s_net)
auto ipv4Checker = [](in_addr n) -> bool {
if (n.s_net == 10)
{
return true;
}
else if (n.s_net == 172 and (16 <= n.s_host and n.s_host == 31))
{
return true;
}
else if (n.s_net == 192 and n.s_host == 168)
{
return true;
}
return false;
};
#endif
#if qDebug && defined (s6_words)
auto ipv6Checker = [](in6_addr n) -> bool {
return n.s6_words[0] == 0xfc00;
};
#endif
switch (fAddressFamily_) {
case AddressFamily::V4: {
/*
* http://www.faqs.org/rfcs/rfc1918.html
*
* 3. Private Address Space
*
* The Internet Assigned Numbers Authority (IANA) has reserved the
* following three blocks of the IP address space for private internets:
*
* 10.0.0.0 - 10.255.255.255 (10/8 prefix)
* 172.16.0.0 - 172.31.255.255 (172.16/12 prefix)
* 192.168.0.0 - 192.168.255.255 (192.168/16 prefix)
*/
uint32_t hostByteOrderAddr = ntohl (fV4_.s_addr);
uint8_t net = (hostByteOrderAddr >> 24);
uint8_t host = ((hostByteOrderAddr >> 16) & 0xff);
if (net == 10) {
#if defined (s_net)
Assert (ipv4Checker (fV4_));
#endif
return true;
}
else if (net == 172 and (16 <= host and host == 31)) {
#if defined (s_net)
Assert (ipv4Checker (fV4_));
#endif
return true;
}
else if (net == 192 and host == 168) {
#if defined (s_net)
Assert (ipv4Checker (fV4_));
#endif
return true;
}
#if defined (s_net)
Assert (not ipv4Checker (fV4_));
#endif
return false;
}
break;
case AddressFamily::V6: {
/*
* From http://en.wikipedia.org/wiki/Private_network
*
* The concept of private networks and special address reservation for such networks
* has been carried over to the next generation of the Internet Protocol, IPv6.
* The address block fc00:: / 7 has been reserved by IANA as described in RFC 4193.
* These addresses are called Unique Local Addresses (ULA).They are defined as being
* unicast in character and contain a 40 - bit random number in the routing prefix.
*/
bool result = fV6_.s6_addr[0] == 0xfc and fV6_.s6_addr[1] == 0x0;
#if defined (s6_words)
Assert (ipv6Checker (fV6_) == result);
#endif
return result;
}
break;
}
AssertNotReached ();
return false;
}
bool InternetAddress::IsMulticastAddress () const
{
Require (not empty ());
switch (fAddressFamily_) {
case AddressFamily::V4: {
// Not sure - might have byte order backwards??? or totally wrong - a bit of a guess?
return (ntohl (fV4_.s_addr) & 0xf0000000) == 0xe0000000;
}
break;
case AddressFamily::V6: {
return (fV6_.s6_addr[0] == 0xff);
}
break;
}
AssertNotReached ();
return false;
}
int InternetAddress::Compare (const InternetAddress& rhs) const
{
if (fAddressFamily_ != rhs.fAddressFamily_) {
return fAddressFamily_ < rhs.fAddressFamily_ ? -1 : 1;
}
switch (fAddressFamily_) {
case AddressFamily::UNKNOWN: {
return 0;
}
break;
case AddressFamily::V4: {
// if not equal, compare by net/host before other things so we get sensible intuitive ordering
if (memcmp (&fV4_, &rhs.fV4_, sizeof (fV4_)) == 0) {
return 0;
}
#if qPlatform_POSIX
if (inet_netof (fV4_) != inet_netof (rhs.fV4_)) {
return inet_netof (fV4_) - inet_netof (rhs.fV4_);
}
if (inet_lnaof (fV4_) != inet_lnaof (rhs.fV4_)) {
return inet_lnaof (fV4_) - inet_lnaof (rhs.fV4_);
}
#elif qPlatform_Windows
if (fV4_.s_net != rhs.fV4_.s_net) {
return static_cast<int> (fV4_.s_net) - static_cast<int> (rhs.fV4_.s_net);
}
if (fV4_.s_host != rhs.fV4_.s_host) {
return static_cast<int> (fV4_.s_host) - static_cast<int> (rhs.fV4_.s_host);
}
if (fV4_.s_lh != rhs.fV4_.s_lh) {
return static_cast<int> (fV4_.s_lh) - static_cast<int> (rhs.fV4_.s_lh);
}
if (fV4_.s_impno != rhs.fV4_.s_impno) {
return static_cast<int> (fV4_.s_impno) - static_cast<int> (rhs.fV4_.s_impno);
}
#endif
AssertNotReached ();
return 0;
//return memcmp (&fV4_, &rhs.fV4_, sizeof (fV4_));
}
break;
case AddressFamily::V6: {
return memcmp (&fV6_, &fV6_, sizeof (fV6_));
}
break;
}
AssertNotReached ();
return false;
}
<commit_msg>cast to int for better compare in InternetAddress::Compare () for POSIX<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2014. All rights reserved
*/
#include "../../StroikaPreComp.h"
#include "../../Characters/String_Constant.h"
#include "../../Debug/Trace.h"
#include "../../Execution/ErrNoException.h"
#include "InternetAddress.h"
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Characters;
using namespace Stroika::Foundation::Memory;
using namespace Stroika::Foundation::IO;
using namespace Stroika::Foundation::IO::Network;
#define qSupportPTONAndPTON_ (qPlatform_POSIX || (qPlatformWindows && (NTDDI_VERSION >= NTDDI_VISTA)))
#if qCompilerAndStdLib_constexpr_union_variants_Buggy
const InternetAddress V4::kAddrAny = InternetAddress (in_addr {});
const InternetAddress V6::kAddrAny = InternetAddress (in6_addr {});
#if qPlatform_POSIX
const InternetAddress V4::kLocalhost = InternetAddress (in_addr { INADDR_LOOPBACK } );
#elif qPlatform_Windows
const InternetAddress V4::kLocalhost = InternetAddress (in_addr { { { 0x1, 0x0, 0x0, 0x7f } } } );
#endif
const InternetAddress V6::kLocalhost = InternetAddress (in6_addr { { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 } } } );
#endif
#if qPlatform_Windows
// Not sure why this is necessary, but we get link errors sometimes without it... Maybe a windows makefile issue on regtest apps?
// -- LGP 2014-11-06
#pragma comment(lib, "Ws2_32.lib")
#endif
/*
********************************************************************************
********************* IO::Network::InternetAddress *****************************
********************************************************************************
*/
InternetAddress::InternetAddress (const string& s, AddressFamily af)
: fAddressFamily_ (AddressFamily::UNKNOWN)
{
if (not s.empty ()) {
if (af == AddressFamily::UNKNOWN) {
// guess format - based on '.' versus ':' in name
if (s.find ('.') != string::npos) {
af = AddressFamily::V4;
}
else if (s.find (':') != string::npos) {
af = AddressFamily::V6;
}
}
switch (af) {
case AddressFamily::V4: {
#if qSupportPTONAndPTON_
Execution::ThrowErrNoIfNegative (inet_pton (AF_INET, s.c_str (), &fV4_));
#elif qPlatform_Windows
DISABLE_COMPILER_MSC_WARNING_START(4996) // msft doesnt have this on old platforms but still warns!
fV4_.s_addr = ::inet_addr (s.c_str ());
DISABLE_COMPILER_MSC_WARNING_END(4996)
#else
AssertNotImplemented ();
#endif
fAddressFamily_ = af;
}
break;
case AddressFamily::V6: {
#if qSupportPTONAndPTON_
Execution::ThrowErrNoIfNegative (inet_pton (AF_INET6, s.c_str (), &fV6_));
#else
AssertNotImplemented ();
#endif
fAddressFamily_ = af;
}
break;
default: {
// @todo need better exception
Execution::DoThrow (Execution::StringException (String_Constant (L"Unrecognized address family")));
}
break;
}
}
}
InternetAddress::InternetAddress (const String& s, AddressFamily af)
: InternetAddress (s.AsUTF8 (), af)
{
}
namespace Stroika {
namespace Foundation {
namespace IO {
namespace Network {
template <>
String InternetAddress::As<String> () const
{
switch (fAddressFamily_) {
case AddressFamily::UNKNOWN: {
return String ();
}
break;
case AddressFamily::V4: {
#if qSupportPTONAndPTON_
char buf[INET_ADDRSTRLEN + 1];
const char* result = ::inet_ntop (AF_INET, &fV4_, buf, sizeof (buf));
return result == nullptr ? String () : String::FromUTF8 (result);
#else
DISABLE_COMPILER_MSC_WARNING_START(4996) // msft doesnt have this on old platforms but still warns!
return String::FromUTF8 (::inet_ntoa (fV4_));
DISABLE_COMPILER_MSC_WARNING_END(4996)
#endif
}
break;
case AddressFamily::V6: {
#if qSupportPTONAndPTON_
char buf[INET6_ADDRSTRLEN + 1];
const char* result = ::inet_ntop (AF_INET6, &fV6_, buf, sizeof (buf));
return result == nullptr ? String () : String::FromUTF8 (result);
#else
AssertNotImplemented ();
return String ();
#endif
}
break;
default: {
RequireNotReached ();
return String ();
}
break;
}
}
}
}
}
}
bool InternetAddress::IsLocalhostAddress () const
{
Require (not empty ());
switch (fAddressFamily_) {
case AddressFamily::V4: {
// 127.0.0.x
//return (::ntohl (fV4_.s_addr) & 0xffffff00) == 0x7f000000;
return (ntohl (fV4_.s_addr) & 0x00ffffff) == 0x00007f;
}
break;
case AddressFamily::V6: {
return
fV6_.s6_addr[0] == 0 and
fV6_.s6_addr[1] == 0 and
fV6_.s6_addr[2] == 0 and
fV6_.s6_addr[3] == 0 and
fV6_.s6_addr[4] == 0 and
fV6_.s6_addr[5] == 0 and
fV6_.s6_addr[6] == 0 and
fV6_.s6_addr[7] == 0 and
fV6_.s6_addr[8] == 0 and
fV6_.s6_addr[9] == 0 and
fV6_.s6_addr[10] == 0 and
fV6_.s6_addr[11] == 0 and
fV6_.s6_addr[12] == 0 and
fV6_.s6_addr[13] == 0 and
fV6_.s6_addr[14] == 0 and
fV6_.s6_addr[15] == 1
;
}
break;
}
AssertNotReached ();
return false;
}
bool InternetAddress::IsLinkLocalAddress () const
{
Require (not empty ());
switch (fAddressFamily_) {
case AddressFamily::V4: {
static const InternetAddress kMinLinkLocal_ { "169.254.0.1" };
static const InternetAddress kMaxLinkLocal_ { "169.254.255.254" };
return kMinLinkLocal_ <= *this and * this <= kMaxLinkLocal_;
}
break;
case AddressFamily::V6: {
return
fV6_.s6_addr[0] == 0xfe and fV6_.s6_addr[1] == 0x80 and
fV6_.s6_addr[2] == 0x0 and fV6_.s6_addr[3] == 0x0 and
fV6_.s6_addr[4] == 0x0 and fV6_.s6_addr[5] == 0x0 and
fV6_.s6_addr[6] == 0x0 and fV6_.s6_addr[7] == 0x0
;
}
break;
}
AssertNotReached ();
return false;
}
bool InternetAddress::IsPrivateAddress () const
{
#if qDebug && defined (s_net)
auto ipv4Checker = [](in_addr n) -> bool {
if (n.s_net == 10)
{
return true;
}
else if (n.s_net == 172 and (16 <= n.s_host and n.s_host == 31))
{
return true;
}
else if (n.s_net == 192 and n.s_host == 168)
{
return true;
}
return false;
};
#endif
#if qDebug && defined (s6_words)
auto ipv6Checker = [](in6_addr n) -> bool {
return n.s6_words[0] == 0xfc00;
};
#endif
switch (fAddressFamily_) {
case AddressFamily::V4: {
/*
* http://www.faqs.org/rfcs/rfc1918.html
*
* 3. Private Address Space
*
* The Internet Assigned Numbers Authority (IANA) has reserved the
* following three blocks of the IP address space for private internets:
*
* 10.0.0.0 - 10.255.255.255 (10/8 prefix)
* 172.16.0.0 - 172.31.255.255 (172.16/12 prefix)
* 192.168.0.0 - 192.168.255.255 (192.168/16 prefix)
*/
uint32_t hostByteOrderAddr = ntohl (fV4_.s_addr);
uint8_t net = (hostByteOrderAddr >> 24);
uint8_t host = ((hostByteOrderAddr >> 16) & 0xff);
if (net == 10) {
#if defined (s_net)
Assert (ipv4Checker (fV4_));
#endif
return true;
}
else if (net == 172 and (16 <= host and host == 31)) {
#if defined (s_net)
Assert (ipv4Checker (fV4_));
#endif
return true;
}
else if (net == 192 and host == 168) {
#if defined (s_net)
Assert (ipv4Checker (fV4_));
#endif
return true;
}
#if defined (s_net)
Assert (not ipv4Checker (fV4_));
#endif
return false;
}
break;
case AddressFamily::V6: {
/*
* From http://en.wikipedia.org/wiki/Private_network
*
* The concept of private networks and special address reservation for such networks
* has been carried over to the next generation of the Internet Protocol, IPv6.
* The address block fc00:: / 7 has been reserved by IANA as described in RFC 4193.
* These addresses are called Unique Local Addresses (ULA).They are defined as being
* unicast in character and contain a 40 - bit random number in the routing prefix.
*/
bool result = fV6_.s6_addr[0] == 0xfc and fV6_.s6_addr[1] == 0x0;
#if defined (s6_words)
Assert (ipv6Checker (fV6_) == result);
#endif
return result;
}
break;
}
AssertNotReached ();
return false;
}
bool InternetAddress::IsMulticastAddress () const
{
Require (not empty ());
switch (fAddressFamily_) {
case AddressFamily::V4: {
// Not sure - might have byte order backwards??? or totally wrong - a bit of a guess?
return (ntohl (fV4_.s_addr) & 0xf0000000) == 0xe0000000;
}
break;
case AddressFamily::V6: {
return (fV6_.s6_addr[0] == 0xff);
}
break;
}
AssertNotReached ();
return false;
}
int InternetAddress::Compare (const InternetAddress& rhs) const
{
if (fAddressFamily_ != rhs.fAddressFamily_) {
return fAddressFamily_ < rhs.fAddressFamily_ ? -1 : 1;
}
switch (fAddressFamily_) {
case AddressFamily::UNKNOWN: {
return 0;
}
break;
case AddressFamily::V4: {
// if not equal, compare by net/host before other things so we get sensible intuitive ordering
if (memcmp (&fV4_, &rhs.fV4_, sizeof (fV4_)) == 0) {
return 0;
}
#if qPlatform_POSIX
if (inet_netof (fV4_) != inet_netof (rhs.fV4_)) {
return static_cast<int> (inet_netof (fV4_)) - static_cast<int> (inet_netof (rhs.fV4_));
}
if (inet_lnaof (fV4_) != inet_lnaof (rhs.fV4_)) {
return static_cast<int> (inet_lnaof (fV4_)) - static_cast<int> (inet_lnaof (rhs.fV4_));
}
#elif qPlatform_Windows
if (fV4_.s_net != rhs.fV4_.s_net) {
return static_cast<int> (fV4_.s_net) - static_cast<int> (rhs.fV4_.s_net);
}
if (fV4_.s_host != rhs.fV4_.s_host) {
return static_cast<int> (fV4_.s_host) - static_cast<int> (rhs.fV4_.s_host);
}
if (fV4_.s_lh != rhs.fV4_.s_lh) {
return static_cast<int> (fV4_.s_lh) - static_cast<int> (rhs.fV4_.s_lh);
}
if (fV4_.s_impno != rhs.fV4_.s_impno) {
return static_cast<int> (fV4_.s_impno) - static_cast<int> (rhs.fV4_.s_impno);
}
#endif
AssertNotReached ();
return 0;
//return memcmp (&fV4_, &rhs.fV4_, sizeof (fV4_));
}
break;
case AddressFamily::V6: {
return memcmp (&fV6_, &fV6_, sizeof (fV6_));
}
break;
}
AssertNotReached ();
return false;
}
<|endoftext|> |
<commit_before>#include "Threading.hpp"
#include "ThreadData.hpp"
#include <cassert>
#include <windows.h>
namespace Cpp {
//------------------------------------------------------------------------------
class Win32_ThreadData
{
public:
Win32_ThreadData()
{
InitializeCriticalSection(&cs_);
}
~Win32_ThreadData()
{
assert(ref_.isNull());
DeleteCriticalSection(&cs_);
}
void lock()
{
EnterCriticalSection(&cs);
}
void unlock()
{
LeaveCriticalSection(&cs);
}
void retain()
{
ref_.retain();
}
void release()
{
if(ref_.release())
{
delete this;
}
}
private:
AtomicReferenceCounter ref_;
CRITICAL_SECTION cs_;
};
//------------------------------------------------------------------------------
static DWORD dwTlsIndex = 0;
//------------------------------------------------------------------------------
void Threading::constructProcessData()
{
assert(!dwTlsIndex);
dwTlsIndex = TlsAlloc();
constructThreadData();
}
//------------------------------------------------------------------------------
void Threading::destructProcessData()
{
destructThreadData();
assert(dwTlsIndex);
TlsFree(dwTlsIndex);
}
//------------------------------------------------------------------------------
void Threading::constructThreadData()
{
assert(dwTlsIndex);
assert(!TlsGetValue(dwTlsIndex));
Win32_ThreadData * data = new Win32_ThreadData();
data->retain();
LPVOID pvTlsData = reinterpret_cast<LPVOID>(data);
TlsSetValue(dwTlsIndex, pvTlsData);
}
//------------------------------------------------------------------------------
void Threading::destructThreadData()
{
assert(dwTlsIndex);
LPVOID pvTlsData = TlsGetValue(dwTlsIndex);
assert(pvTlsData);
Win32_ThreadData * data = reinterpret_cast<Win32_ThreadData*>(pvTlsData);
data->release();
TlsSetValue(dwTlsIndex, NULL);
}
//------------------------------------------------------------------------------
Threading::ThreadData * Threading::currentThreadData()
{
assert(dwTlsIndex);
LPVOID pvTlsData = TlsGetValue(dwTlsIndex);
assert(pvTlsData);
Win32_ThreadData * data = reinterpret_cast<Win32_ThreadData*>(pvTlsData);
return reinterpret_cast<Threading::ThreadData*>(data);
}
//------------------------------------------------------------------------------
void Threading::ThreadData::lock()
{
reinterpret_cast<Win32_ThreadData*>(this)->lock();
}
//------------------------------------------------------------------------------
void Threading::ThreadData::unlock()
{
reinterpret_cast<Win32_ThreadData*>(this)->lock();
}
//------------------------------------------------------------------------------
void Threading::ThreadData::retain()
{
reinterpret_cast<Win32_ThreadData*>(this)->retain();
}
//------------------------------------------------------------------------------
void Threading::ThreadData::release()
{
reinterpret_cast<Win32_ThreadData*>(this)->release();
}
//------------------------------------------------------------------------------
} //namespace Cpp<commit_msg>-: Fix for commit 91<commit_after>#include "Threading.hpp"
#include "ThreadData.hpp"
#include <cassert>
#include <windows.h>
namespace Cpp {
//------------------------------------------------------------------------------
class Win32_ThreadData
{
public:
Win32_ThreadData()
{
InitializeCriticalSection(&cs_);
}
~Win32_ThreadData()
{
assert(ref_.isNull());
DeleteCriticalSection(&cs_);
}
void lock()
{
EnterCriticalSection(&cs_);
}
void unlock()
{
LeaveCriticalSection(&cs_);
}
void retain()
{
ref_.retain();
}
void release()
{
if(ref_.release())
{
delete this;
}
}
private:
AtomicReferenceCounter ref_;
CRITICAL_SECTION cs_;
};
//------------------------------------------------------------------------------
static DWORD dwTlsIndex = 0;
//------------------------------------------------------------------------------
void Threading::constructProcessData()
{
assert(!dwTlsIndex);
dwTlsIndex = TlsAlloc();
constructThreadData();
}
//------------------------------------------------------------------------------
void Threading::destructProcessData()
{
destructThreadData();
assert(dwTlsIndex);
TlsFree(dwTlsIndex);
}
//------------------------------------------------------------------------------
void Threading::constructThreadData()
{
assert(dwTlsIndex);
assert(!TlsGetValue(dwTlsIndex));
Win32_ThreadData * data = new Win32_ThreadData();
data->retain();
LPVOID pvTlsData = reinterpret_cast<LPVOID>(data);
TlsSetValue(dwTlsIndex, pvTlsData);
}
//------------------------------------------------------------------------------
void Threading::destructThreadData()
{
assert(dwTlsIndex);
LPVOID pvTlsData = TlsGetValue(dwTlsIndex);
assert(pvTlsData);
Win32_ThreadData * data = reinterpret_cast<Win32_ThreadData*>(pvTlsData);
data->release();
TlsSetValue(dwTlsIndex, NULL);
}
//------------------------------------------------------------------------------
Threading::ThreadData * Threading::currentThreadData()
{
assert(dwTlsIndex);
LPVOID pvTlsData = TlsGetValue(dwTlsIndex);
assert(pvTlsData);
Win32_ThreadData * data = reinterpret_cast<Win32_ThreadData*>(pvTlsData);
return reinterpret_cast<Threading::ThreadData*>(data);
}
//------------------------------------------------------------------------------
void Threading::ThreadData::lock()
{
reinterpret_cast<Win32_ThreadData*>(this)->lock();
}
//------------------------------------------------------------------------------
void Threading::ThreadData::unlock()
{
reinterpret_cast<Win32_ThreadData*>(this)->lock();
}
//------------------------------------------------------------------------------
void Threading::ThreadData::retain()
{
reinterpret_cast<Win32_ThreadData*>(this)->retain();
}
//------------------------------------------------------------------------------
void Threading::ThreadData::release()
{
reinterpret_cast<Win32_ThreadData*>(this)->release();
}
//------------------------------------------------------------------------------
} //namespace Cpp<|endoftext|> |
<commit_before>#include <vtkActor.h>
#include <vtkCylinderSource.h>
#include <vtkMath.h>
#include <vtkMinimalStandardRandomSequence.h>
#include <vtkNamedColors.h>
#include <vtkPolyData.h>
#include <vtkPolyDataMapper.h>
#include <vtkProperty.h>
#include <vtkOpenVRRenderWindow.h>
#include <vtkOpenVRRenderer.h>
#include <vtkOpenVRRenderWindowInteractor.h>
#include <vtkSmartPointer.h>
#include <vtkSphereSource.h>
#include <vtkTransform.h>
#include <vtkTransformPolyDataFilter.h>
#include <array>
#define USER_MATRIX
int main(int, char *[])
{
vtkSmartPointer<vtkNamedColors> colors =
vtkSmartPointer<vtkNamedColors>::New();
// Set the background color.
std::array<unsigned char, 4> bkg{ { 26, 51, 77, 255 } };
colors->SetColor("BkgColor", bkg.data());
// Create a cylinder.
// Cylinder height vector is (0,1,0).
// Cylinder center is in the middle of the cylinder
vtkSmartPointer<vtkCylinderSource> cylinderSource =
vtkSmartPointer<vtkCylinderSource>::New();
cylinderSource->SetResolution(15);
// Generate a random start and end point
double startPoint[3];
double endPoint[3];
vtkSmartPointer<vtkMinimalStandardRandomSequence> rng =
vtkSmartPointer<vtkMinimalStandardRandomSequence>::New();
rng->SetSeed(8775070); // For testing.
for (auto i = 0; i < 3; ++i)
{
rng->Next();
startPoint[i] = rng->GetRangeValue(-10, 10);
rng->Next();
endPoint[i] = rng->GetRangeValue(-10, 10);
}
// Compute a basis
double normalizedX[3];
double normalizedY[3];
double normalizedZ[3];
// The X axis is a vector from start to end
vtkMath::Subtract(endPoint, startPoint, normalizedX);
double length = vtkMath::Norm(normalizedX);
vtkMath::Normalize(normalizedX);
// The Z axis is an arbitrary vector cross X
double arbitrary[3];
for (auto i = 0; i < 3; ++i)
{
rng->Next();
arbitrary[i] = rng->GetRangeValue(-10, 10);
}
vtkMath::Cross(normalizedX, arbitrary, normalizedZ);
vtkMath::Normalize(normalizedZ);
// The Y axis is Z cross X
vtkMath::Cross(normalizedZ, normalizedX, normalizedY);
vtkSmartPointer<vtkMatrix4x4> matrix =
vtkSmartPointer<vtkMatrix4x4>::New();
// Create the direction cosine matrix
matrix->Identity();
for (unsigned int i = 0; i < 3; i++)
{
matrix->SetElement(i, 0, normalizedX[i]);
matrix->SetElement(i, 1, normalizedY[i]);
matrix->SetElement(i, 2, normalizedZ[i]);
}
// Apply the transforms
vtkSmartPointer<vtkTransform> transform =
vtkSmartPointer<vtkTransform>::New();
transform->Translate(startPoint); // translate to starting point
transform->Concatenate(matrix); // apply direction cosines
transform->RotateZ(-90.0); // align cylinder to x axis
transform->Scale(1.0, length, 1.0); // scale along the height vector
transform->Translate(0, .5, 0); // translate to start of cylinder
// Transform the polydata
vtkSmartPointer<vtkTransformPolyDataFilter> transformPD =
vtkSmartPointer<vtkTransformPolyDataFilter>::New();
transformPD->SetTransform(transform);
transformPD->SetInputConnection(cylinderSource->GetOutputPort());
//Create a mapper and actor for the cylinder
vtkSmartPointer<vtkPolyDataMapper> mapper =
vtkSmartPointer<vtkPolyDataMapper>::New();
vtkSmartPointer<vtkActor> actor =
vtkSmartPointer<vtkActor>::New();
#ifdef USER_MATRIX
mapper->SetInputConnection(cylinderSource->GetOutputPort());
actor->SetUserMatrix(transform->GetMatrix());
#else
mapper->SetInputConnection(transformPD->GetOutputPort());
#endif
actor->SetMapper(mapper);
actor->GetProperty()->SetColor(colors->GetColor3d("Cyan").GetData());
// Create spheres for start and end point
vtkSmartPointer<vtkSphereSource> sphereStartSource =
vtkSmartPointer<vtkSphereSource>::New();
sphereStartSource->SetCenter(startPoint);
sphereStartSource->SetRadius(0.8);
vtkSmartPointer<vtkPolyDataMapper> sphereStartMapper =
vtkSmartPointer<vtkPolyDataMapper>::New();
sphereStartMapper->SetInputConnection(sphereStartSource->GetOutputPort());
vtkSmartPointer<vtkActor> sphereStart =
vtkSmartPointer<vtkActor>::New();
sphereStart->SetMapper(sphereStartMapper);
sphereStart->GetProperty()->SetColor(colors->GetColor3d("Yellow").GetData());
vtkSmartPointer<vtkSphereSource> sphereEndSource =
vtkSmartPointer<vtkSphereSource>::New();
sphereEndSource->SetCenter(endPoint);
sphereEndSource->SetRadius(0.8);
vtkSmartPointer<vtkPolyDataMapper> sphereEndMapper =
vtkSmartPointer<vtkPolyDataMapper>::New();
sphereEndMapper->SetInputConnection(sphereEndSource->GetOutputPort());
vtkSmartPointer<vtkActor> sphereEnd =
vtkSmartPointer<vtkActor>::New();
sphereEnd->SetMapper(sphereEndMapper);
sphereEnd->GetProperty()->SetColor(colors->GetColor3d("Magenta").GetData());
//Create a renderer, render window, and interactor
vtkSmartPointer<vtkOpenVRRenderer> renderer =
vtkSmartPointer<vtkOpenVRRenderer>::New();
vtkSmartPointer<vtkOpenVRRenderWindow> renderWindow =
vtkSmartPointer<vtkOpenVRRenderWindow>::New();
renderWindow->AddRenderer(renderer);
vtkSmartPointer<vtkOpenVRRenderWindowInteractor> renderWindowInteractor =
vtkSmartPointer<vtkOpenVRRenderWindowInteractor>::New();
renderWindowInteractor->SetRenderWindow(renderWindow);
//Add the actor to the scene
renderer->AddActor(actor);
renderer->AddActor(sphereStart);
renderer->AddActor(sphereEnd);
renderer->SetBackground(colors->GetColor3d("BkgColor").GetData());
//Render and interact
renderWindow->Render();
renderWindowInteractor->Start();
return EXIT_SUCCESS;
}
<commit_msg>Update OpenVROrientedCylinder.cxx<commit_after>#include <vtkActor.h>
#include <vtkCylinderSource.h>
#include <vtkMath.h>
#include <vtkMinimalStandardRandomSequence.h>
#include <vtkNamedColors.h>
#include <vtkPolyData.h>
#include <vtkPolyDataMapper.h>
#include <vtkProperty.h>
#include <vtkOpenVRRenderWindow.h>
#include <vtkOpenVRRenderer.h>
#include <vtkOpenVRRenderWindowInteractor.h>
#include <vtkSmartPointer.h>
#include <vtkSphereSource.h>
#include <vtkTransform.h>
#include <vtkTransformPolyDataFilter.h>
#include <array>
#define USER_MATRIX
int main(int, char *[])
{
vtkSmartPointer<vtkNamedColors> colors =
vtkSmartPointer<vtkNamedColors>::New();
// Set the background color.
std::array<unsigned char, 4> bkg{ { 26, 51, 77, 255 } };
colors->SetColor("BkgColor", bkg.data());
// Create a cylinder.
// Cylinder height vector is (0,1,0).
// Cylinder center is in the middle of the cylinder
vtkSmartPointer<vtkCylinderSource> cylinderSource =
vtkSmartPointer<vtkCylinderSource>::New();
cylinderSource->SetResolution(15);
// Generate a random start and end point
double startPoint[3];
double endPoint[3];
vtkSmartPointer<vtkMinimalStandardRandomSequence> rng =
vtkSmartPointer<vtkMinimalStandardRandomSequence>::New();
rng->SetSeed(8775070); // For testing.
for (auto i = 0; i < 3; ++i)
{
rng->Next();
startPoint[i] = rng->GetRangeValue(-10, 10);
rng->Next();
endPoint[i] = rng->GetRangeValue(-10, 10);
}
// Compute a basis
double normalizedX[3];
double normalizedY[3];
double normalizedZ[3];
// The X axis is a vector from start to end
vtkMath::Subtract(endPoint, startPoint, normalizedX);
double length = vtkMath::Norm(normalizedX);
vtkMath::Normalize(normalizedX);
// The Z axis is an arbitrary vector cross X
double arbitrary[3];
for (auto i = 0; i < 3; ++i)
{
rng->Next();
arbitrary[i] = rng->GetRangeValue(-10, 10);
}
vtkMath::Cross(normalizedX, arbitrary, normalizedZ);
vtkMath::Normalize(normalizedZ);
// The Y axis is Z cross X
vtkMath::Cross(normalizedZ, normalizedX, normalizedY);
vtkSmartPointer<vtkMatrix4x4> matrix =
vtkSmartPointer<vtkMatrix4x4>::New();
// Create the direction cosine matrix
matrix->Identity();
for (unsigned int i = 0; i < 3; i++)
{
matrix->SetElement(i, 0, normalizedX[i]);
matrix->SetElement(i, 1, normalizedY[i]);
matrix->SetElement(i, 2, normalizedZ[i]);
}
// Apply the transforms
vtkSmartPointer<vtkTransform> transform =
vtkSmartPointer<vtkTransform>::New();
transform->Translate(startPoint); // translate to starting point
transform->Concatenate(matrix); // apply direction cosines
transform->RotateZ(-90.0); // align cylinder to x axis
transform->Scale(1.0, length, 1.0); // scale along the height vector
transform->Translate(0, .5, 0); // translate to start of cylinder
// Transform the polydata
vtkSmartPointer<vtkTransformPolyDataFilter> transformPD =
vtkSmartPointer<vtkTransformPolyDataFilter>::New();
transformPD->SetTransform(transform);
transformPD->SetInputConnection(cylinderSource->GetOutputPort());
//Create a mapper and actor for the cylinder
vtkSmartPointer<vtkPolyDataMapper> mapper =
vtkSmartPointer<vtkPolyDataMapper>::New();
vtkSmartPointer<vtkActor> actor =
vtkSmartPointer<vtkActor>::New();
#ifdef USER_MATRIX
mapper->SetInputConnection(cylinderSource->GetOutputPort());
actor->SetUserMatrix(transform->GetMatrix());
#else
mapper->SetInputConnection(transformPD->GetOutputPort());
#endif
actor->SetMapper(mapper);
actor->GetProperty()->SetColor(colors->GetColor3d("Cyan").GetData());
// Create spheres for start and end point
vtkSmartPointer<vtkSphereSource> sphereStartSource =
vtkSmartPointer<vtkSphereSource>::New();
sphereStartSource->SetCenter(startPoint);
sphereStartSource->SetRadius(0.8);
vtkSmartPointer<vtkPolyDataMapper> sphereStartMapper =
vtkSmartPointer<vtkPolyDataMapper>::New();
sphereStartMapper->SetInputConnection(sphereStartSource->GetOutputPort());
vtkSmartPointer<vtkActor> sphereStart =
vtkSmartPointer<vtkActor>::New();
sphereStart->SetMapper(sphereStartMapper);
sphereStart->GetProperty()->SetColor(colors->GetColor3d("Yellow").GetData());
vtkSmartPointer<vtkSphereSource> sphereEndSource =
vtkSmartPointer<vtkSphereSource>::New();
sphereEndSource->SetCenter(endPoint);
sphereEndSource->SetRadius(0.8);
vtkSmartPointer<vtkPolyDataMapper> sphereEndMapper =
vtkSmartPointer<vtkPolyDataMapper>::New();
sphereEndMapper->SetInputConnection(sphereEndSource->GetOutputPort());
vtkSmartPointer<vtkActor> sphereEnd =
vtkSmartPointer<vtkActor>::New();
sphereEnd->SetMapper(sphereEndMapper);
sphereEnd->GetProperty()->SetColor(colors->GetColor3d("Magenta").GetData());
//Create a renderer, render window, and interactor
vtkSmartPointer<vtkOpenVRRenderer> renderer =
vtkSmartPointer<vtkOpenVRRenderer>::New();
vtkSmartPointer<vtkOpenVRRenderWindow> renderWindow =
vtkSmartPointer<vtkOpenVRRenderWindow>::New();
renderWindow->AddRenderer(renderer);
vtkSmartPointer<vtkOpenVRRenderWindowInteractor> renderWindowInteractor =
vtkSmartPointer<vtkOpenVRRenderWindowInteractor>::New();
renderWindowInteractor->SetRenderWindow(renderWindow);
//Add the actor to the scene
renderer->AddActor(actor);
renderer->AddActor(sphereStart);
renderer->AddActor(sphereEnd);
renderer->SetBackground(colors->GetColor3d("BkgColor").GetData());
//Render and interact
renderWindow->Render();
renderWindowInteractor->Start();
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>///////////////////////////////////////////////////////////////////////////
// //
// AliFemtoModelCorrFctn3DSpherical: a class to calculate 3D correlation //
// for pairs of identical particles, binned in spherical coordinates. //
// In analysis the function should be first created in a macro, then //
// added to the analysis, and at the end of the macro the procedure to //
// write out histograms should be called. //
// //
///////////////////////////////////////////////////////////////////////////
#include "AliFemtoModelCorrFctn3DSpherical.h"
#include "AliFemtoModelManager.h"
#include <TMath.h>
#include <cstdio>
#ifdef __ROOT__
ClassImp(AliFemtoModelCorrFctn3DSpherical)
#endif
//____________________________
AliFemtoModelCorrFctn3DSpherical::AliFemtoModelCorrFctn3DSpherical(char* title, const int& nqbins, const float& QLo, const float& QHi, const int& nphibins, const int& ncthetabins):
AliFemtoModelCorrFctn(),
fTrueNumeratorSph(0),
fFakeNumeratorSph(0),
fDenominatorSph(0),
fPairCut(0x0)
{
// set up numerator
char tTitNum[100] = "NumTrue";
strcat(tTitNum,title);
fTrueNumeratorSph = new TH3D(tTitNum,title,nqbins,QLo,QHi,nphibins,-TMath::Pi(),TMath::Pi(),ncthetabins,-1.0,1.0);
// set up numerator
char tTitNumF[100] = "NumFake";
strcat(tTitNumF,title);
fFakeNumeratorSph = new TH3D(tTitNumF,title,nqbins,QLo,QHi,nphibins,-TMath::Pi(),TMath::Pi(),ncthetabins,-1.0,1.0);
// set up denominator
char tTitDen[100] = "Den";
strcat(tTitDen,title);
fDenominatorSph = new TH3D(tTitDen,title,nqbins,QLo,QHi,nphibins,-TMath::Pi(),TMath::Pi(),ncthetabins,-1.0,1.0);
// to enable error bar calculation...
fTrueNumeratorSph->Sumw2();
fFakeNumeratorSph->Sumw2();
fDenominatorSph->Sumw2();
}
AliFemtoModelCorrFctn3DSpherical::AliFemtoModelCorrFctn3DSpherical(const AliFemtoModelCorrFctn3DSpherical& aCorrFctn) :
AliFemtoModelCorrFctn(aCorrFctn),
fTrueNumeratorSph(0),
fFakeNumeratorSph(0),
fDenominatorSph(0),
fPairCut(0x0)
{
// Copy constructor
fTrueNumeratorSph = new TH3D(*aCorrFctn.fTrueNumeratorSph);
fFakeNumeratorSph = new TH3D(*aCorrFctn.fFakeNumeratorSph);
fDenominatorSph = new TH3D(*aCorrFctn.fDenominatorSph);
fPairCut = aCorrFctn.fPairCut;
}
//____________________________
AliFemtoModelCorrFctn3DSpherical::~AliFemtoModelCorrFctn3DSpherical(){
// Destructor
delete fTrueNumeratorSph;
delete fFakeNumeratorSph;
delete fDenominatorSph;
}
//_________________________
AliFemtoModelCorrFctn3DSpherical& AliFemtoModelCorrFctn3DSpherical::operator=(const AliFemtoModelCorrFctn3DSpherical& aCorrFctn)
{
// assignment operator
if (this == &aCorrFctn)
return *this;
if (fTrueNumeratorSph) delete fTrueNumeratorSph;
fTrueNumeratorSph = new TH3D(*aCorrFctn.fTrueNumeratorSph);
if (fFakeNumeratorSph) delete fFakeNumeratorSph;
fFakeNumeratorSph = new TH3D(*aCorrFctn.fFakeNumeratorSph);
if (fDenominatorSph) delete fDenominatorSph;
fDenominatorSph = new TH3D(*aCorrFctn.fDenominatorSph);
fPairCut = aCorrFctn.fPairCut;
return *this;
}
//_________________________
void AliFemtoModelCorrFctn3DSpherical::WriteOutHistos(){
// Write out all histograms to file
fTrueNumeratorSph->Write();
fFakeNumeratorSph->Write();
fDenominatorSph->Write();
}
//______________________________
TList* AliFemtoModelCorrFctn3DSpherical::GetOutputList()
{
// Prepare the list of objects to be written to the output
TList *tOutputList = new TList();
tOutputList->Add(fTrueNumeratorSph);
tOutputList->Add(fFakeNumeratorSph);
tOutputList->Add(fDenominatorSph);
return tOutputList;
}
//_________________________
void AliFemtoModelCorrFctn3DSpherical::Finish(){
// here is where we should normalize, fit, etc...
}
//____________________________
AliFemtoString AliFemtoModelCorrFctn3DSpherical::Report(){
// Construct the report
string stemp = "PRF Frame Spherical 3D Model Correlation Function Report:\n";
char ctemp[100];
sprintf(ctemp,"Number of entries in numerator:\t%E\n",fTrueNumeratorSph->GetEntries());
stemp += ctemp;
sprintf(ctemp,"Number of entries in denominator:\t%E\n",fDenominatorSph->GetEntries());
stemp += ctemp;
if (fPairCut){
sprintf(ctemp,"Here is the PairCut specific to this CorrFctn\n");
stemp += ctemp;
stemp += fPairCut->Report();
}
else{
sprintf(ctemp,"No PairCut specific to this CorrFctn\n");
stemp += ctemp;
}
//
AliFemtoString returnThis = stemp;
return returnThis;
}
//____________________________
void AliFemtoModelCorrFctn3DSpherical::AddRealPair( AliFemtoPair* pair){
// perform operations on real pairs
if (fPairCut){
if (!(fPairCut->Pass(pair))) return;
}
Double_t weight = fManager->GetWeight(pair);
double tKO = pair->KOut();
double tKS = pair->KSide();
double tKL = pair->KLong();
double tKR = sqrt(tKO*tKO + tKS*tKS + tKL*tKL);
double tKC;
if ( fabs(tKR) < 1e-10 ) tKC = 0.0;
else tKC=tKL/tKR;
double tKP=atan2(tKS,tKO);
fTrueNumeratorSph->Fill(tKR,tKP,tKC,weight);
}
//____________________________
void AliFemtoModelCorrFctn3DSpherical::AddMixedPair( AliFemtoPair* pair){
// perform operations on mixed pairs
if (fPairCut){
if (!(fPairCut->Pass(pair))) return;
}
Double_t weight = fManager->GetWeight(pair);
double tKO = pair->KOut();
double tKS = pair->KSide();
double tKL = pair->KLong();
double tKR = sqrt(tKO*tKO + tKS*tKS + tKL*tKL);
double tKC;
if ( fabs(tKR) < 1e-10 ) tKC = 0.0;
else tKC=tKL/tKR;
double tKP=atan2(tKS,tKO);
fFakeNumeratorSph->Fill(tKR,tKP,tKC,weight);
fDenominatorSph->Fill(tKR,tKP,tKC);
}
<commit_msg>Remove dependence<commit_after>///////////////////////////////////////////////////////////////////////////
// //
// AliFemtoModelCorrFctn3DSpherical: a class to calculate 3D correlation //
// for pairs of identical particles, binned in spherical coordinates. //
// In analysis the function should be first created in a macro, then //
// added to the analysis, and at the end of the macro the procedure to //
// write out histograms should be called. //
// //
///////////////////////////////////////////////////////////////////////////
#include "AliFemtoModelCorrFctn3DSpherical.h"
#include "AliFemtoModelManager.h"
#include <TMath.h>
#include <cstdio>
//#include <Math/SpecFunc.h>
#ifdef __ROOT__
ClassImp(AliFemtoModelCorrFctn3DSpherical)
#endif
//____________________________
AliFemtoModelCorrFctn3DSpherical::AliFemtoModelCorrFctn3DSpherical(char* title, const int& nqbins, const float& QLo, const float& QHi, const int& nphibins, const int& ncthetabins):
AliFemtoModelCorrFctn(),
fTrueNumeratorSph(0),
fFakeNumeratorSph(0),
fDenominatorSph(0),
fPairCut(0x0)
{
// set up numerator
char tTitNum[100] = "NumTrue";
strcat(tTitNum,title);
fTrueNumeratorSph = new TH3D(tTitNum,title,nqbins,QLo,QHi,nphibins,-TMath::Pi(),TMath::Pi(),ncthetabins,-1.0,1.0);
// set up numerator
char tTitNumF[100] = "NumFake";
strcat(tTitNumF,title);
fFakeNumeratorSph = new TH3D(tTitNumF,title,nqbins,QLo,QHi,nphibins,-TMath::Pi(),TMath::Pi(),ncthetabins,-1.0,1.0);
// set up denominator
char tTitDen[100] = "Den";
strcat(tTitDen,title);
fDenominatorSph = new TH3D(tTitDen,title,nqbins,QLo,QHi,nphibins,-TMath::Pi(),TMath::Pi(),ncthetabins,-1.0,1.0);
// to enable error bar calculation...
fTrueNumeratorSph->Sumw2();
fFakeNumeratorSph->Sumw2();
fDenominatorSph->Sumw2();
}
AliFemtoModelCorrFctn3DSpherical::AliFemtoModelCorrFctn3DSpherical(const AliFemtoModelCorrFctn3DSpherical& aCorrFctn) :
AliFemtoModelCorrFctn(aCorrFctn),
fTrueNumeratorSph(0),
fFakeNumeratorSph(0),
fDenominatorSph(0),
fPairCut(0x0)
{
// Copy constructor
fTrueNumeratorSph = new TH3D(*aCorrFctn.fTrueNumeratorSph);
fFakeNumeratorSph = new TH3D(*aCorrFctn.fFakeNumeratorSph);
fDenominatorSph = new TH3D(*aCorrFctn.fDenominatorSph);
fPairCut = aCorrFctn.fPairCut;
}
//____________________________
AliFemtoModelCorrFctn3DSpherical::~AliFemtoModelCorrFctn3DSpherical(){
// Destructor
delete fTrueNumeratorSph;
delete fFakeNumeratorSph;
delete fDenominatorSph;
}
//_________________________
AliFemtoModelCorrFctn3DSpherical& AliFemtoModelCorrFctn3DSpherical::operator=(const AliFemtoModelCorrFctn3DSpherical& aCorrFctn)
{
// assignment operator
if (this == &aCorrFctn)
return *this;
if (fTrueNumeratorSph) delete fTrueNumeratorSph;
fTrueNumeratorSph = new TH3D(*aCorrFctn.fTrueNumeratorSph);
if (fFakeNumeratorSph) delete fFakeNumeratorSph;
fFakeNumeratorSph = new TH3D(*aCorrFctn.fFakeNumeratorSph);
if (fDenominatorSph) delete fDenominatorSph;
fDenominatorSph = new TH3D(*aCorrFctn.fDenominatorSph);
fPairCut = aCorrFctn.fPairCut;
return *this;
}
//_________________________
void AliFemtoModelCorrFctn3DSpherical::WriteOutHistos(){
// Write out all histograms to file
fTrueNumeratorSph->Write();
fFakeNumeratorSph->Write();
fDenominatorSph->Write();
}
//______________________________
TList* AliFemtoModelCorrFctn3DSpherical::GetOutputList()
{
// Prepare the list of objects to be written to the output
TList *tOutputList = new TList();
tOutputList->Add(fTrueNumeratorSph);
tOutputList->Add(fFakeNumeratorSph);
tOutputList->Add(fDenominatorSph);
return tOutputList;
}
//_________________________
void AliFemtoModelCorrFctn3DSpherical::Finish(){
// here is where we should normalize, fit, etc...
}
//____________________________
AliFemtoString AliFemtoModelCorrFctn3DSpherical::Report(){
// Construct the report
string stemp = "PRF Frame Spherical 3D Model Correlation Function Report:\n";
char ctemp[100];
sprintf(ctemp,"Number of entries in numerator:\t%E\n",fTrueNumeratorSph->GetEntries());
stemp += ctemp;
sprintf(ctemp,"Number of entries in denominator:\t%E\n",fDenominatorSph->GetEntries());
stemp += ctemp;
if (fPairCut){
sprintf(ctemp,"Here is the PairCut specific to this CorrFctn\n");
stemp += ctemp;
stemp += fPairCut->Report();
}
else{
sprintf(ctemp,"No PairCut specific to this CorrFctn\n");
stemp += ctemp;
}
//
AliFemtoString returnThis = stemp;
return returnThis;
}
//____________________________
void AliFemtoModelCorrFctn3DSpherical::AddRealPair( AliFemtoPair* pair){
// perform operations on real pairs
if (fPairCut){
if (!(fPairCut->Pass(pair))) return;
}
Double_t weight = fManager->GetWeight(pair);
double tKO = pair->KOut();
double tKS = pair->KSide();
double tKL = pair->KLong();
double tKR = sqrt(tKO*tKO + tKS*tKS + tKL*tKL);
double tKC;
if ( fabs(tKR) < 1e-10 ) tKC = 0.0;
else tKC=tKL/tKR;
double tKP=atan2(tKS,tKO);
fTrueNumeratorSph->Fill(tKR,tKP,tKC,weight);
}
//____________________________
void AliFemtoModelCorrFctn3DSpherical::AddMixedPair( AliFemtoPair* pair){
// perform operations on mixed pairs
if (fPairCut){
if (!(fPairCut->Pass(pair))) return;
}
Double_t weight = fManager->GetWeight(pair);
double tKO = pair->KOut();
double tKS = pair->KSide();
double tKL = pair->KLong();
double tKR = sqrt(tKO*tKO + tKS*tKS + tKL*tKL);
double tKC;
if ( fabs(tKR) < 1e-10 ) tKC = 0.0;
else tKC=tKL/tKR;
double tKP=atan2(tKS,tKO);
fFakeNumeratorSph->Fill(tKR,tKP,tKC,weight);
fDenominatorSph->Fill(tKR,tKP,tKC);
}
<|endoftext|> |
<commit_before>/*
* yosys -- Yosys Open SYnthesis Suite
*
* Copyright (C) 2012 Clifford Wolf <[email protected]>
*
* 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 "kernel/log.h"
#include "kernel/register.h"
#include "kernel/sigtools.h"
#include "kernel/consteval.h"
#include "kernel/celltypes.h"
#include "fsmdata.h"
#include <string.h>
USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN
struct FsmOpt
{
FsmData fsm_data;
RTLIL::Cell *cell;
RTLIL::Module *module;
void opt_unreachable_states()
{
while (1)
{
std::set<int> unreachable_states;
std::vector<FsmData::transition_t> new_transition_table;
std::vector<RTLIL::Const> new_state_table;
std::map<int, int> old_to_new_state;
for (int i = 0; i < GetSize(fsm_data.state_table); i++)
if (i != fsm_data.reset_state)
unreachable_states.insert(i);
for (auto &trans : fsm_data.transition_table)
unreachable_states.erase(trans.state_out);
if (unreachable_states.empty())
break;
for (int i = 0; i < GetSize(fsm_data.state_table); i++) {
if (unreachable_states.count(i)) {
log(" Removing unreachable state %s.\n", log_signal(fsm_data.state_table[i]));
continue;
}
old_to_new_state[i] = GetSize(new_state_table);
new_state_table.push_back(fsm_data.state_table[i]);
}
for (auto trans : fsm_data.transition_table) {
if (unreachable_states.count(trans.state_in))
continue;
trans.state_in = old_to_new_state.at(trans.state_in);
trans.state_out = old_to_new_state.at(trans.state_out);
new_transition_table.push_back(trans);
}
new_transition_table.swap(fsm_data.transition_table);
new_state_table.swap(fsm_data.state_table);
fsm_data.reset_state = old_to_new_state.at(fsm_data.reset_state);
}
}
bool signal_is_unused(RTLIL::SigSpec sig)
{
RTLIL::SigBit bit = sig.as_bit();
if (bit.wire == NULL || bit.wire->attributes.count("\\unused_bits") == 0)
return false;
char *str = strdup(bit.wire->attributes["\\unused_bits"].decode_string().c_str());
for (char *tok = strtok(str, " "); tok != NULL; tok = strtok(NULL, " ")) {
if (tok[0] && bit.offset == atoi(tok)) {
free(str);
return true;
}
}
free(str);
return false;
}
void opt_const_and_unused_inputs()
{
RTLIL::SigSpec ctrl_in = cell->getPort("\\CTRL_IN");
std::vector<bool> ctrl_in_used(ctrl_in.size());
std::vector<FsmData::transition_t> new_transition_table;
for (auto &tr : fsm_data.transition_table) {
for (int i = 0; i < ctrl_in.size(); i++) {
RTLIL::SigSpec ctrl_bit = ctrl_in.extract(i, 1);
if (ctrl_bit.is_fully_const()) {
if (tr.ctrl_in.bits[i] <= RTLIL::State::S1 && RTLIL::SigSpec(tr.ctrl_in.bits[i]) != ctrl_bit)
goto delete_this_transition;
continue;
}
if (tr.ctrl_in.bits[i] <= RTLIL::State::S1)
ctrl_in_used[i] = true;
}
new_transition_table.push_back(tr);
delete_this_transition:;
}
for (int i = int(ctrl_in_used.size())-1; i >= 0; i--) {
if (!ctrl_in_used[i]) {
log(" Removing unused input signal %s.\n", log_signal(cell->getPort("\\CTRL_IN").extract(i, 1)));
for (auto &tr : new_transition_table) {
RTLIL::SigSpec tmp(tr.ctrl_in);
tmp.remove(i, 1);
tr.ctrl_in = tmp.as_const();
}
RTLIL::SigSpec new_ctrl_in = cell->getPort("\\CTRL_IN");
new_ctrl_in.remove(i, 1);
cell->setPort("\\CTRL_IN", new_ctrl_in);
fsm_data.num_inputs--;
}
}
fsm_data.transition_table.swap(new_transition_table);
new_transition_table.clear();
}
void opt_unused_outputs()
{
for (int i = 0; i < fsm_data.num_outputs; i++) {
RTLIL::SigSpec sig = cell->getPort("\\CTRL_OUT").extract(i, 1);
if (signal_is_unused(sig)) {
log(" Removing unused output signal %s.\n", log_signal(sig));
RTLIL::SigSpec new_ctrl_out = cell->getPort("\\CTRL_OUT");
new_ctrl_out.remove(i, 1);
cell->setPort("\\CTRL_OUT", new_ctrl_out);
for (auto &tr : fsm_data.transition_table) {
RTLIL::SigSpec tmp(tr.ctrl_out);
tmp.remove(i, 1);
tr.ctrl_out = tmp.as_const();
}
fsm_data.num_outputs--;
i--;
}
}
}
void opt_alias_inputs()
{
RTLIL::SigSpec &ctrl_in = cell->connections_["\\CTRL_IN"];
for (int i = 0; i < ctrl_in.size(); i++)
for (int j = i+1; j < ctrl_in.size(); j++)
if (ctrl_in.extract(i, 1) == ctrl_in.extract(j, 1))
{
log(" Optimize handling of signal %s that is connected to inputs %d and %d.\n", log_signal(ctrl_in.extract(i, 1)), i, j);
std::vector<FsmData::transition_t> new_transition_table;
for (auto tr : fsm_data.transition_table)
{
RTLIL::State &si = tr.ctrl_in.bits[i];
RTLIL::State &sj = tr.ctrl_in.bits[j];
if (si > RTLIL::State::S1)
si = sj;
else if (sj > RTLIL::State::S1)
sj = si;
if (si == sj) {
RTLIL::SigSpec tmp(tr.ctrl_in);
tmp.remove(j, 1);
tr.ctrl_in = tmp.as_const();
new_transition_table.push_back(tr);
}
}
ctrl_in.remove(j--, 1);
fsm_data.num_inputs--;
fsm_data.transition_table.swap(new_transition_table);
new_transition_table.clear();
}
}
void opt_feedback_inputs()
{
RTLIL::SigSpec &ctrl_in = cell->connections_["\\CTRL_IN"];
RTLIL::SigSpec &ctrl_out = cell->connections_["\\CTRL_OUT"];
for (int j = 0; j < ctrl_out.size(); j++)
for (int i = 0; i < ctrl_in.size(); i++)
if (ctrl_in.extract(i, 1) == ctrl_out.extract(j, 1))
{
log(" Optimize handling of signal %s that is connected to input %d and output %d.\n", log_signal(ctrl_in.extract(i, 1)), i, j);
std::vector<FsmData::transition_t> new_transition_table;
for (auto tr : fsm_data.transition_table)
{
RTLIL::State &si = tr.ctrl_in.bits[i];
RTLIL::State &sj = tr.ctrl_out.bits[j];
if (si > RTLIL::State::S1 || si == sj) {
RTLIL::SigSpec tmp(tr.ctrl_in);
tmp.remove(i, 1);
tr.ctrl_in = tmp.as_const();
new_transition_table.push_back(tr);
}
}
ctrl_in.remove(i--, 1);
fsm_data.num_inputs--;
fsm_data.transition_table.swap(new_transition_table);
new_transition_table.clear();
}
}
void opt_find_dont_care_worker(std::set<RTLIL::Const> &set, int bit, FsmData::transition_t &tr, bool &did_something)
{
std::set<RTLIL::Const> new_set;
for (auto &pattern : set)
{
if (pattern.bits[bit] > RTLIL::State::S1) {
new_set.insert(pattern);
continue;
}
RTLIL::Const other_pattern = pattern;
if (pattern.bits[bit] == RTLIL::State::S1)
other_pattern.bits[bit] = RTLIL::State::S0;
else
other_pattern.bits[bit] = RTLIL::State::S1;
if (set.count(other_pattern) > 0) {
log(" Merging pattern %s and %s from group (%d %d %s).\n", log_signal(pattern), log_signal(other_pattern),
tr.state_in, tr.state_out, log_signal(tr.ctrl_out));
other_pattern.bits[bit] = RTLIL::State::Sa;
new_set.insert(other_pattern);
did_something = true;
continue;
}
new_set.insert(pattern);
}
set.swap(new_set);
}
void opt_find_dont_care()
{
typedef std::pair<std::pair<int, int>, RTLIL::Const> group_t;
std::map<group_t, std::set<RTLIL::Const>> transitions_by_group;
for (auto &tr : fsm_data.transition_table) {
group_t group(std::pair<int, int>(tr.state_in, tr.state_out), tr.ctrl_out);
transitions_by_group[group].insert(tr.ctrl_in);
}
fsm_data.transition_table.clear();
for (auto &it : transitions_by_group)
{
FsmData::transition_t tr;
tr.state_in = it.first.first.first;
tr.state_out = it.first.first.second;
tr.ctrl_out = it.first.second;
bool did_something = true;
while (did_something) {
did_something = false;
for (int i = 0; i < fsm_data.num_inputs; i++)
opt_find_dont_care_worker(it.second, i, tr, did_something);
}
for (auto &ci : it.second) {
tr.ctrl_in = ci;
fsm_data.transition_table.push_back(tr);
}
}
}
FsmOpt(RTLIL::Cell *cell, RTLIL::Module *module)
{
log("Optimizing FSM `%s' from module `%s'.\n", cell->name.c_str(), module->name.c_str());
fsm_data.copy_from_cell(cell);
this->cell = cell;
this->module = module;
opt_unreachable_states();
opt_unused_outputs();
opt_alias_inputs();
opt_feedback_inputs();
opt_find_dont_care();
opt_const_and_unused_inputs();
fsm_data.copy_to_cell(cell);
}
};
PRIVATE_NAMESPACE_END
void YOSYS_NAMESPACE_PREFIX FsmData::optimize_fsm(RTLIL::Cell *cell, RTLIL::Module *module)
{
FsmOpt fsmopt(cell, module);
}
PRIVATE_NAMESPACE_BEGIN
struct FsmOptPass : public Pass {
FsmOptPass() : Pass("fsm_opt", "optimize finite state machines") { }
void help() YS_OVERRIDE
{
// |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
log("\n");
log(" fsm_opt [selection]\n");
log("\n");
log("This pass optimizes FSM cells. It detects which output signals are actually\n");
log("not used and removes them from the FSM. This pass is usually used in\n");
log("combination with the 'opt_clean' pass (see also 'help fsm').\n");
log("\n");
}
void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE
{
log_header(design, "Executing FSM_OPT pass (simple optimizations of FSMs).\n");
extra_args(args, 1, design);
for (auto &mod_it : design->modules_) {
if (design->selected(mod_it.second))
for (auto &cell_it : mod_it.second->cells_)
if (cell_it.second->type == "$fsm" && design->selected(mod_it.second, cell_it.second))
FsmData::optimize_fsm(cell_it.second, mod_it.second);
}
}
} FsmOptPass;
PRIVATE_NAMESPACE_END
<commit_msg>fsm_opt: Fix runtime error for FSMs without a reset state<commit_after>/*
* yosys -- Yosys Open SYnthesis Suite
*
* Copyright (C) 2012 Clifford Wolf <[email protected]>
*
* 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 "kernel/log.h"
#include "kernel/register.h"
#include "kernel/sigtools.h"
#include "kernel/consteval.h"
#include "kernel/celltypes.h"
#include "fsmdata.h"
#include <string.h>
USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN
struct FsmOpt
{
FsmData fsm_data;
RTLIL::Cell *cell;
RTLIL::Module *module;
void opt_unreachable_states()
{
while (1)
{
std::set<int> unreachable_states;
std::vector<FsmData::transition_t> new_transition_table;
std::vector<RTLIL::Const> new_state_table;
std::map<int, int> old_to_new_state;
for (int i = 0; i < GetSize(fsm_data.state_table); i++)
if (i != fsm_data.reset_state)
unreachable_states.insert(i);
for (auto &trans : fsm_data.transition_table)
unreachable_states.erase(trans.state_out);
if (unreachable_states.empty())
break;
for (int i = 0; i < GetSize(fsm_data.state_table); i++) {
if (unreachable_states.count(i)) {
log(" Removing unreachable state %s.\n", log_signal(fsm_data.state_table[i]));
continue;
}
old_to_new_state[i] = GetSize(new_state_table);
new_state_table.push_back(fsm_data.state_table[i]);
}
for (auto trans : fsm_data.transition_table) {
if (unreachable_states.count(trans.state_in))
continue;
trans.state_in = old_to_new_state.at(trans.state_in);
trans.state_out = old_to_new_state.at(trans.state_out);
new_transition_table.push_back(trans);
}
new_transition_table.swap(fsm_data.transition_table);
new_state_table.swap(fsm_data.state_table);
if (fsm_data.reset_state != -1)
fsm_data.reset_state = old_to_new_state.at(fsm_data.reset_state);
}
}
bool signal_is_unused(RTLIL::SigSpec sig)
{
RTLIL::SigBit bit = sig.as_bit();
if (bit.wire == NULL || bit.wire->attributes.count("\\unused_bits") == 0)
return false;
char *str = strdup(bit.wire->attributes["\\unused_bits"].decode_string().c_str());
for (char *tok = strtok(str, " "); tok != NULL; tok = strtok(NULL, " ")) {
if (tok[0] && bit.offset == atoi(tok)) {
free(str);
return true;
}
}
free(str);
return false;
}
void opt_const_and_unused_inputs()
{
RTLIL::SigSpec ctrl_in = cell->getPort("\\CTRL_IN");
std::vector<bool> ctrl_in_used(ctrl_in.size());
std::vector<FsmData::transition_t> new_transition_table;
for (auto &tr : fsm_data.transition_table) {
for (int i = 0; i < ctrl_in.size(); i++) {
RTLIL::SigSpec ctrl_bit = ctrl_in.extract(i, 1);
if (ctrl_bit.is_fully_const()) {
if (tr.ctrl_in.bits[i] <= RTLIL::State::S1 && RTLIL::SigSpec(tr.ctrl_in.bits[i]) != ctrl_bit)
goto delete_this_transition;
continue;
}
if (tr.ctrl_in.bits[i] <= RTLIL::State::S1)
ctrl_in_used[i] = true;
}
new_transition_table.push_back(tr);
delete_this_transition:;
}
for (int i = int(ctrl_in_used.size())-1; i >= 0; i--) {
if (!ctrl_in_used[i]) {
log(" Removing unused input signal %s.\n", log_signal(cell->getPort("\\CTRL_IN").extract(i, 1)));
for (auto &tr : new_transition_table) {
RTLIL::SigSpec tmp(tr.ctrl_in);
tmp.remove(i, 1);
tr.ctrl_in = tmp.as_const();
}
RTLIL::SigSpec new_ctrl_in = cell->getPort("\\CTRL_IN");
new_ctrl_in.remove(i, 1);
cell->setPort("\\CTRL_IN", new_ctrl_in);
fsm_data.num_inputs--;
}
}
fsm_data.transition_table.swap(new_transition_table);
new_transition_table.clear();
}
void opt_unused_outputs()
{
for (int i = 0; i < fsm_data.num_outputs; i++) {
RTLIL::SigSpec sig = cell->getPort("\\CTRL_OUT").extract(i, 1);
if (signal_is_unused(sig)) {
log(" Removing unused output signal %s.\n", log_signal(sig));
RTLIL::SigSpec new_ctrl_out = cell->getPort("\\CTRL_OUT");
new_ctrl_out.remove(i, 1);
cell->setPort("\\CTRL_OUT", new_ctrl_out);
for (auto &tr : fsm_data.transition_table) {
RTLIL::SigSpec tmp(tr.ctrl_out);
tmp.remove(i, 1);
tr.ctrl_out = tmp.as_const();
}
fsm_data.num_outputs--;
i--;
}
}
}
void opt_alias_inputs()
{
RTLIL::SigSpec &ctrl_in = cell->connections_["\\CTRL_IN"];
for (int i = 0; i < ctrl_in.size(); i++)
for (int j = i+1; j < ctrl_in.size(); j++)
if (ctrl_in.extract(i, 1) == ctrl_in.extract(j, 1))
{
log(" Optimize handling of signal %s that is connected to inputs %d and %d.\n", log_signal(ctrl_in.extract(i, 1)), i, j);
std::vector<FsmData::transition_t> new_transition_table;
for (auto tr : fsm_data.transition_table)
{
RTLIL::State &si = tr.ctrl_in.bits[i];
RTLIL::State &sj = tr.ctrl_in.bits[j];
if (si > RTLIL::State::S1)
si = sj;
else if (sj > RTLIL::State::S1)
sj = si;
if (si == sj) {
RTLIL::SigSpec tmp(tr.ctrl_in);
tmp.remove(j, 1);
tr.ctrl_in = tmp.as_const();
new_transition_table.push_back(tr);
}
}
ctrl_in.remove(j--, 1);
fsm_data.num_inputs--;
fsm_data.transition_table.swap(new_transition_table);
new_transition_table.clear();
}
}
void opt_feedback_inputs()
{
RTLIL::SigSpec &ctrl_in = cell->connections_["\\CTRL_IN"];
RTLIL::SigSpec &ctrl_out = cell->connections_["\\CTRL_OUT"];
for (int j = 0; j < ctrl_out.size(); j++)
for (int i = 0; i < ctrl_in.size(); i++)
if (ctrl_in.extract(i, 1) == ctrl_out.extract(j, 1))
{
log(" Optimize handling of signal %s that is connected to input %d and output %d.\n", log_signal(ctrl_in.extract(i, 1)), i, j);
std::vector<FsmData::transition_t> new_transition_table;
for (auto tr : fsm_data.transition_table)
{
RTLIL::State &si = tr.ctrl_in.bits[i];
RTLIL::State &sj = tr.ctrl_out.bits[j];
if (si > RTLIL::State::S1 || si == sj) {
RTLIL::SigSpec tmp(tr.ctrl_in);
tmp.remove(i, 1);
tr.ctrl_in = tmp.as_const();
new_transition_table.push_back(tr);
}
}
ctrl_in.remove(i--, 1);
fsm_data.num_inputs--;
fsm_data.transition_table.swap(new_transition_table);
new_transition_table.clear();
}
}
void opt_find_dont_care_worker(std::set<RTLIL::Const> &set, int bit, FsmData::transition_t &tr, bool &did_something)
{
std::set<RTLIL::Const> new_set;
for (auto &pattern : set)
{
if (pattern.bits[bit] > RTLIL::State::S1) {
new_set.insert(pattern);
continue;
}
RTLIL::Const other_pattern = pattern;
if (pattern.bits[bit] == RTLIL::State::S1)
other_pattern.bits[bit] = RTLIL::State::S0;
else
other_pattern.bits[bit] = RTLIL::State::S1;
if (set.count(other_pattern) > 0) {
log(" Merging pattern %s and %s from group (%d %d %s).\n", log_signal(pattern), log_signal(other_pattern),
tr.state_in, tr.state_out, log_signal(tr.ctrl_out));
other_pattern.bits[bit] = RTLIL::State::Sa;
new_set.insert(other_pattern);
did_something = true;
continue;
}
new_set.insert(pattern);
}
set.swap(new_set);
}
void opt_find_dont_care()
{
typedef std::pair<std::pair<int, int>, RTLIL::Const> group_t;
std::map<group_t, std::set<RTLIL::Const>> transitions_by_group;
for (auto &tr : fsm_data.transition_table) {
group_t group(std::pair<int, int>(tr.state_in, tr.state_out), tr.ctrl_out);
transitions_by_group[group].insert(tr.ctrl_in);
}
fsm_data.transition_table.clear();
for (auto &it : transitions_by_group)
{
FsmData::transition_t tr;
tr.state_in = it.first.first.first;
tr.state_out = it.first.first.second;
tr.ctrl_out = it.first.second;
bool did_something = true;
while (did_something) {
did_something = false;
for (int i = 0; i < fsm_data.num_inputs; i++)
opt_find_dont_care_worker(it.second, i, tr, did_something);
}
for (auto &ci : it.second) {
tr.ctrl_in = ci;
fsm_data.transition_table.push_back(tr);
}
}
}
FsmOpt(RTLIL::Cell *cell, RTLIL::Module *module)
{
log("Optimizing FSM `%s' from module `%s'.\n", cell->name.c_str(), module->name.c_str());
fsm_data.copy_from_cell(cell);
this->cell = cell;
this->module = module;
opt_unreachable_states();
opt_unused_outputs();
opt_alias_inputs();
opt_feedback_inputs();
opt_find_dont_care();
opt_const_and_unused_inputs();
fsm_data.copy_to_cell(cell);
}
};
PRIVATE_NAMESPACE_END
void YOSYS_NAMESPACE_PREFIX FsmData::optimize_fsm(RTLIL::Cell *cell, RTLIL::Module *module)
{
FsmOpt fsmopt(cell, module);
}
PRIVATE_NAMESPACE_BEGIN
struct FsmOptPass : public Pass {
FsmOptPass() : Pass("fsm_opt", "optimize finite state machines") { }
void help() YS_OVERRIDE
{
// |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
log("\n");
log(" fsm_opt [selection]\n");
log("\n");
log("This pass optimizes FSM cells. It detects which output signals are actually\n");
log("not used and removes them from the FSM. This pass is usually used in\n");
log("combination with the 'opt_clean' pass (see also 'help fsm').\n");
log("\n");
}
void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE
{
log_header(design, "Executing FSM_OPT pass (simple optimizations of FSMs).\n");
extra_args(args, 1, design);
for (auto &mod_it : design->modules_) {
if (design->selected(mod_it.second))
for (auto &cell_it : mod_it.second->cells_)
if (cell_it.second->type == "$fsm" && design->selected(mod_it.second, cell_it.second))
FsmData::optimize_fsm(cell_it.second, mod_it.second);
}
}
} FsmOptPass;
PRIVATE_NAMESPACE_END
<|endoftext|> |
<commit_before>/*!
@file
@author George Evmenov
@date 07/2009
*/
#include "MyGUI_OpenGLRenderManager.h"
#include "MyGUI_OpenGLTexture.h"
#include "MyGUI_OpenGLVertexBuffer.h"
#include "MyGUI_OpenGLDiagnostic.h"
#include "MyGUI_VertexData.h"
#include "MyGUI_Gui.h"
#include "MyGUI_Timer.h"
#include "GL/glew.h"
namespace MyGUI
{
OpenGLRenderManager::OpenGLRenderManager() :
mUpdate(false),
mImageLoader(nullptr),
mPboIsSupported(false),
mIsInitialise(false)
{
}
void OpenGLRenderManager::initialise(OpenGLImageLoader* _loader)
{
MYGUI_ASSERT(!mIsInitialise, getClassTypeName() << " initialised twice");
MYGUI_LOG(Info, "* Initialise: " << getClassTypeName());
mVertexFormat = VertexColourType::ColourABGR;
mUpdate = false;
mImageLoader = _loader;
glewInit();
mPboIsSupported = glewIsExtensionSupported("GL_EXT_pixel_buffer_object") != 0;
MYGUI_LOG(Info, getClassTypeName() << " successfully initialized");
mIsInitialise = true;
}
void OpenGLRenderManager::shutdown()
{
MYGUI_ASSERT(mIsInitialise, getClassTypeName() << " is not initialised");
MYGUI_LOG(Info, "* Shutdown: " << getClassTypeName());
destroyAllResources();
MYGUI_LOG(Info, getClassTypeName() << " successfully shutdown");
mIsInitialise = false;
}
IVertexBuffer* OpenGLRenderManager::createVertexBuffer()
{
return new OpenGLVertexBuffer();
}
void OpenGLRenderManager::destroyVertexBuffer(IVertexBuffer* _buffer)
{
delete _buffer;
}
void OpenGLRenderManager::doRender(IVertexBuffer* _buffer, ITexture* _texture, size_t _count)
{
OpenGLVertexBuffer* buffer = static_cast<OpenGLVertexBuffer*>(_buffer);
unsigned int buffer_id = buffer->getBufferID();
MYGUI_PLATFORM_ASSERT(buffer_id, "Vertex buffer is not created");
unsigned int texture_id = 0;
if (_texture)
{
OpenGLTexture* texture = static_cast<OpenGLTexture*>(_texture);
texture_id = texture->getTextureID();
//MYGUI_PLATFORM_ASSERT(texture_id, "Texture is not created");
}
glBindTexture(GL_TEXTURE_2D, texture_id);
glBindBufferARB(GL_ARRAY_BUFFER_ARB, buffer_id);
// enable vertex arrays
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_COLOR_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
// before draw, specify vertex and index arrays with their offsets
size_t offset = 0;
glVertexPointer(3, GL_FLOAT, sizeof(Vertex), (void*)offset);
offset += (sizeof(float) * 3);
glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(Vertex), (void*)offset);
offset += (4);
glTexCoordPointer(2, GL_FLOAT, sizeof(Vertex), (void*)offset);
glDrawArrays(GL_TRIANGLES, 0, _count);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
glDisableClientState(GL_COLOR_ARRAY);
glDisableClientState(GL_VERTEX_ARRAY);
glBindBufferARB(GL_ARRAY_BUFFER_ARB, 0);
glBindTexture(GL_TEXTURE_2D, 0);
}
void OpenGLRenderManager::begin()
{
//save current attributes
glPushClientAttrib(GL_CLIENT_ALL_ATTRIB_BITS);
glPushAttrib(GL_ALL_ATTRIB_BITS);
glPolygonMode(GL_FRONT, GL_FILL);
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
glOrtho(-1, 1, -1, 1, -1, 1);
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
glDisable(GL_LIGHTING);
glDisable(GL_DEPTH_TEST);
glDisable(GL_FOG);
glDisable(GL_TEXTURE_GEN_S);
glDisable(GL_TEXTURE_GEN_T);
glDisable(GL_TEXTURE_GEN_R);
//glFrontFace(GL_CW);
//glCullFace(GL_BACK);
//glEnable(GL_CULL_FACE);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
glEnable(GL_TEXTURE_2D);
}
void OpenGLRenderManager::end()
{
glPopMatrix();
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glMatrixMode(GL_MODELVIEW);
//restore former attributes
glPopAttrib();
glPopClientAttrib();
}
const RenderTargetInfo& OpenGLRenderManager::getInfo()
{
return mInfo;
}
const IntSize& OpenGLRenderManager::getViewSize() const
{
return mViewSize;
}
VertexColourType OpenGLRenderManager::getVertexFormat()
{
return mVertexFormat;
}
void OpenGLRenderManager::drawOneFrame()
{
Gui* gui = Gui::getInstancePtr();
if (gui == nullptr)
return;
static Timer timer;
static unsigned long last_time = timer.getMilliseconds();
unsigned long now_time = timer.getMilliseconds();
unsigned long time = now_time - last_time;
gui->_injectFrameEntered((float)((double)(time) / (double)1000));
last_time = now_time;
begin();
LayerManager::getInstance().renderToTarget(this, mUpdate);
end();
mUpdate = false;
}
void OpenGLRenderManager::setViewSize(int _width, int _height)
{
if (_height == 0)
_height = 1;
if (_width == 0)
_width = 1;
mViewSize.set(_width, _height);
mInfo.maximumDepth = 1;
mInfo.hOffset = 0;
mInfo.vOffset = 0;
mInfo.aspectCoef = float(mViewSize.height) / float(mViewSize.width);
mInfo.pixScaleX = 1.0f / float(mViewSize.width);
mInfo.pixScaleY = 1.0f / float(mViewSize.height);
Gui* gui = Gui::getInstancePtr();
if (gui != nullptr)
{
gui->_resizeWindow(mViewSize);
mUpdate = true;
}
}
bool OpenGLRenderManager::isPixelBufferObjectSupported()
{
return mPboIsSupported;
}
ITexture* OpenGLRenderManager::createTexture(const std::string& _name)
{
MapTexture::const_iterator item = mTextures.find(_name);
MYGUI_PLATFORM_ASSERT(item == mTextures.end(), "Texture '" << _name << "' already exist");
OpenGLTexture* texture = new OpenGLTexture(_name, mImageLoader);
mTextures[_name] = texture;
return texture;
}
void OpenGLRenderManager::destroyTexture(ITexture* _texture)
{
if (_texture == nullptr) return;
MapTexture::iterator item = mTextures.find(_texture->getName());
MYGUI_PLATFORM_ASSERT(item != mTextures.end(), "Texture '" << _texture->getName() << "' not found");
mTextures.erase(item);
delete _texture;
}
ITexture* OpenGLRenderManager::getTexture(const std::string& _name)
{
MapTexture::const_iterator item = mTextures.find(_name);
if (item == mTextures.end()) return nullptr;
return item->second;
}
void OpenGLRenderManager::destroyAllResources()
{
for (MapTexture::const_iterator item = mTextures.begin(); item != mTextures.end(); ++item)
{
delete item->second;
}
mTextures.clear();
}
} // namespace MyGUI
<commit_msg>refactoring OpenGL platform<commit_after>/*!
@file
@author George Evmenov
@date 07/2009
*/
#include "MyGUI_OpenGLRenderManager.h"
#include "MyGUI_OpenGLTexture.h"
#include "MyGUI_OpenGLVertexBuffer.h"
#include "MyGUI_OpenGLDiagnostic.h"
#include "MyGUI_VertexData.h"
#include "MyGUI_Gui.h"
#include "MyGUI_Timer.h"
#include "GL/glew.h"
namespace MyGUI
{
OpenGLRenderManager::OpenGLRenderManager() :
mUpdate(false),
mImageLoader(nullptr),
mPboIsSupported(false),
mIsInitialise(false)
{
}
void OpenGLRenderManager::initialise(OpenGLImageLoader* _loader)
{
MYGUI_ASSERT(!mIsInitialise, getClassTypeName() << " initialised twice");
MYGUI_LOG(Info, "* Initialise: " << getClassTypeName());
mVertexFormat = VertexColourType::ColourABGR;
mUpdate = false;
mImageLoader = _loader;
glewInit();
mPboIsSupported = glewIsExtensionSupported("GL_EXT_pixel_buffer_object") != 0;
MYGUI_LOG(Info, getClassTypeName() << " successfully initialized");
mIsInitialise = true;
}
void OpenGLRenderManager::shutdown()
{
MYGUI_ASSERT(mIsInitialise, getClassTypeName() << " is not initialised");
MYGUI_LOG(Info, "* Shutdown: " << getClassTypeName());
destroyAllResources();
MYGUI_LOG(Info, getClassTypeName() << " successfully shutdown");
mIsInitialise = false;
}
IVertexBuffer* OpenGLRenderManager::createVertexBuffer()
{
return new OpenGLVertexBuffer();
}
void OpenGLRenderManager::destroyVertexBuffer(IVertexBuffer* _buffer)
{
delete _buffer;
}
void OpenGLRenderManager::doRender(IVertexBuffer* _buffer, ITexture* _texture, size_t _count)
{
OpenGLVertexBuffer* buffer = static_cast<OpenGLVertexBuffer*>(_buffer);
unsigned int buffer_id = buffer->getBufferID();
MYGUI_PLATFORM_ASSERT(buffer_id, "Vertex buffer is not created");
unsigned int texture_id = 0;
if (_texture)
{
OpenGLTexture* texture = static_cast<OpenGLTexture*>(_texture);
texture_id = texture->getTextureID();
//MYGUI_PLATFORM_ASSERT(texture_id, "Texture is not created");
}
glBindTexture(GL_TEXTURE_2D, texture_id);
glBindBufferARB(GL_ARRAY_BUFFER_ARB, buffer_id);
// enable vertex arrays
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_COLOR_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
// before draw, specify vertex and index arrays with their offsets
size_t offset = 0;
glVertexPointer(3, GL_FLOAT, sizeof(Vertex), (void*)offset);
offset += (sizeof(float) * 3);
glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(Vertex), (void*)offset);
offset += (4);
glTexCoordPointer(2, GL_FLOAT, sizeof(Vertex), (void*)offset);
glDrawArrays(GL_TRIANGLES, 0, _count);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
glDisableClientState(GL_COLOR_ARRAY);
glDisableClientState(GL_VERTEX_ARRAY);
glBindBufferARB(GL_ARRAY_BUFFER_ARB, 0);
glBindTexture(GL_TEXTURE_2D, 0);
}
void OpenGLRenderManager::begin()
{
//save current attributes
glPushClientAttrib(GL_CLIENT_ALL_ATTRIB_BITS);
glPushAttrib(GL_ALL_ATTRIB_BITS);
glPolygonMode(GL_FRONT, GL_FILL);
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
glOrtho(-1, 1, -1, 1, -1, 1);
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
glDisable(GL_LIGHTING);
glDisable(GL_DEPTH_TEST);
glDisable(GL_FOG);
glDisable(GL_TEXTURE_GEN_S);
glDisable(GL_TEXTURE_GEN_T);
glDisable(GL_TEXTURE_GEN_R);
//glFrontFace(GL_CW);
//glCullFace(GL_BACK);
//glEnable(GL_CULL_FACE);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
glEnable(GL_TEXTURE_2D);
}
void OpenGLRenderManager::end()
{
glPopMatrix();
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glMatrixMode(GL_MODELVIEW);
//restore former attributes
glPopAttrib();
glPopClientAttrib();
}
const RenderTargetInfo& OpenGLRenderManager::getInfo()
{
return mInfo;
}
const IntSize& OpenGLRenderManager::getViewSize() const
{
return mViewSize;
}
VertexColourType OpenGLRenderManager::getVertexFormat()
{
return mVertexFormat;
}
void OpenGLRenderManager::drawOneFrame()
{
Gui* gui = Gui::getInstancePtr();
if (gui == nullptr)
return;
static Timer timer;
static unsigned long last_time = timer.getMilliseconds();
unsigned long now_time = timer.getMilliseconds();
unsigned long time = now_time - last_time;
onFrameEvent((float)((double)(time) / (double)1000));
last_time = now_time;
begin();
onRenderToTarget(this, mUpdate);
end();
mUpdate = false;
}
void OpenGLRenderManager::setViewSize(int _width, int _height)
{
if (_height == 0)
_height = 1;
if (_width == 0)
_width = 1;
mViewSize.set(_width, _height);
mInfo.maximumDepth = 1;
mInfo.hOffset = 0;
mInfo.vOffset = 0;
mInfo.aspectCoef = float(mViewSize.height) / float(mViewSize.width);
mInfo.pixScaleX = 1.0f / float(mViewSize.width);
mInfo.pixScaleY = 1.0f / float(mViewSize.height);
onResizeView(mViewSize);
mUpdate = true;
}
bool OpenGLRenderManager::isPixelBufferObjectSupported()
{
return mPboIsSupported;
}
ITexture* OpenGLRenderManager::createTexture(const std::string& _name)
{
MapTexture::const_iterator item = mTextures.find(_name);
MYGUI_PLATFORM_ASSERT(item == mTextures.end(), "Texture '" << _name << "' already exist");
OpenGLTexture* texture = new OpenGLTexture(_name, mImageLoader);
mTextures[_name] = texture;
return texture;
}
void OpenGLRenderManager::destroyTexture(ITexture* _texture)
{
if (_texture == nullptr)
return;
MapTexture::iterator item = mTextures.find(_texture->getName());
MYGUI_PLATFORM_ASSERT(item != mTextures.end(), "Texture '" << _texture->getName() << "' not found");
mTextures.erase(item);
delete _texture;
}
ITexture* OpenGLRenderManager::getTexture(const std::string& _name)
{
MapTexture::const_iterator item = mTextures.find(_name);
if (item == mTextures.end())
return nullptr;
return item->second;
}
void OpenGLRenderManager::destroyAllResources()
{
for (MapTexture::const_iterator item = mTextures.begin(); item != mTextures.end(); ++item)
{
delete item->second;
}
mTextures.clear();
}
} // namespace MyGUI
<|endoftext|> |
<commit_before>#include <iostream>
#include <string>
#include <affine_invariant_features/affine_invariant_feature.hpp>
#include <affine_invariant_features/feature_parameters.hpp>
#include <affine_invariant_features/results.hpp>
#include <affine_invariant_features/target.hpp>
#include <opencv2/core.hpp>
#include <opencv2/features2d.hpp>
#include <opencv2/highgui.hpp>
int main(int argc, char *argv[]) {
namespace aif = affine_invariant_features;
if (argc != 4) {
std::cout << "Usage: extract_features <parameter_file> <target_file> <result_file>"
<< std::endl;
std::cout << "Note: use generate_*_file to generate parameter or target files" << std::endl;
return 0;
}
const std::string param_path(argv[1]);
const std::string target_path(argv[2]);
const std::string result_path(argv[3]);
const cv::FileStorage param_file(param_path, cv::FileStorage::READ);
const cv::Ptr< const aif::FeatureParameters > params(
aif::readFeatureParameters(param_file.root()));
if (!params) {
std::cerr << "Could not load a parameter set from " << param_path << std::endl;
return 1;
}
const cv::FileStorage target_file(target_path, cv::FileStorage::READ);
aif::TargetDescription target_desc;
target_file[target_desc.getDefaultName()] >> target_desc;
if (target_desc.imagePath.empty()) {
std::cerr << "Could not load an image path from " << target_path << std::endl;
return 1;
}
const aif::TargetData target_data(target_desc.toData());
if (target_data.image.empty()) {
std::cerr << "Could not load a target image described in " << target_path << std::endl;
return 1;
}
cv::Mat target_image;
if (target_data.mask.empty()) {
target_image = target_data.image.clone();
} else {
target_image = target_data.image / 4;
target_data.image.copyTo(target_image, target_data.mask);
}
std::cout << "Showing the target image with mask. Press any key to continue." << std::endl;
cv::imshow("Target", target_image);
cv::waitKey(0);
std::cout << "Extracting features. This may take seconds or minutes." << std::endl;
const cv::Ptr< cv::Feature2D > feature(
aif::AffineInvariantFeature::create(params->createFeature()));
aif::Results results;
feature->detectAndCompute(target_data.image, target_data.mask, results.keypoints,
results.descriptors);
results.normType = feature->defaultNorm();
cv::Mat result_image;
cv::drawKeypoints(target_image, results.keypoints, result_image);
std::cout << "Showing a result image with keypoints. Press any key to continue." << std::endl;
cv::imshow("Resutls", result_image);
cv::waitKey(0);
cv::FileStorage result_file(result_path, cv::FileStorage::WRITE);
result_file << params->getDefaultName() << *params;
result_file << target_desc.getDefaultName() << target_desc;
result_file << results.getDefaultName() << results;
std::cout << "Wrote context and results of feature extraction to " << result_path << std::endl;
return 0;
}
<commit_msg>refactor extract_features<commit_after>#include <iostream>
#include <string>
#include <affine_invariant_features/affine_invariant_feature.hpp>
#include <affine_invariant_features/feature_parameters.hpp>
#include <affine_invariant_features/results.hpp>
#include <affine_invariant_features/target.hpp>
#include <opencv2/core.hpp>
#include <opencv2/features2d.hpp>
#include <opencv2/highgui.hpp>
int main(int argc, char *argv[]) {
namespace aif = affine_invariant_features;
const cv::CommandLineParser args(
argc, argv, "{ help | | }"
"{ use-simple-feature | <none> | will not use affine invariant sampling }"
"{ @parameter-file | <none> | can be generated by generate_parameter_file }"
"{ @target-file | <none> | can be generated by generate_target_file }"
"{ @result-file | <none> | }");
if (args.has("help")) {
args.printMessage();
return 0;
}
const bool use_simple_feature(args.has("use-simple-feature"));
const std::string param_path(args.get< std::string >("@parameter-file"));
const std::string target_path(args.get< std::string >("@target-file"));
const std::string result_path(args.get< std::string >("@result-file"));
if (!args.check()) {
args.printErrors();
return 1;
}
const cv::FileStorage param_file(param_path, cv::FileStorage::READ);
if (!param_file.isOpened()) {
std::cerr << "Could not open " << param_path << std::endl;
return 1;
}
const cv::Ptr< const aif::FeatureParameters > params(
aif::readFeatureParameters(param_file.root()));
if (!params) {
std::cerr << "Could not load a parameter set from " << param_path << std::endl;
return 1;
}
const cv::FileStorage target_file(target_path, cv::FileStorage::READ);
if (!target_file.isOpened()) {
std::cerr << "Could not open " << target_path << std::endl;
return 1;
}
aif::TargetDescription target_desc;
target_file[target_desc.getDefaultName()] >> target_desc;
if (target_desc.imagePath.empty()) {
std::cerr << "Could not load an image path from " << target_path << std::endl;
return 1;
}
const aif::TargetData target_data(target_desc.toData());
if (target_data.image.empty()) {
std::cerr << "Could not load a target image described in " << target_path << std::endl;
return 1;
}
cv::Mat target_image;
if (target_data.mask.empty()) {
target_image = target_data.image.clone();
} else {
target_image = target_data.image / 4;
target_data.image.copyTo(target_image, target_data.mask);
}
std::cout << "Showing the target image with mask. Press any key to continue." << std::endl;
cv::imshow("Target", target_image);
cv::waitKey(0);
std::cout << "Extracting features. This may take seconds or minutes." << std::endl;
cv::Ptr< cv::Feature2D > feature;
if (use_simple_feature) {
feature = params->createFeature();
} else {
feature = aif::AffineInvariantFeature::create(params->createFeature());
}
aif::Results results;
feature->detectAndCompute(target_data.image, target_data.mask, results.keypoints,
results.descriptors);
results.normType = feature->defaultNorm();
cv::Mat result_image;
cv::drawKeypoints(target_image, results.keypoints, result_image);
std::cout << "Showing a result image with keypoints. Press any key to continue." << std::endl;
cv::imshow("Resutls", result_image);
cv::waitKey(0);
cv::FileStorage result_file(result_path, cv::FileStorage::WRITE);
if(!result_file.isOpened()){
std::cerr << "Could not open or create " << result_path << std::endl;
return 1;
}
result_file << params->getDefaultName() << *params;
result_file << target_desc.getDefaultName() << target_desc;
result_file << results.getDefaultName() << results;
std::cout << "Wrote context and results of feature extraction to " << result_path << std::endl;
return 0;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: syshelp.hxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: rt $ $Date: 2005-09-09 11:58:53 $
*
* 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 X2C_SYSHELP_HXX
#define X2C_SYSHELP_HXX
// USED SERVICES
// BASE CLASSES
// COMPONENTS
// PARAMETERS
#include <iosfwd>
class Simstr;
template <class XY> class List;
#ifdef WNT
const char C_sSLASH[] = "\\";
const char C_cSLASH = '\\';
#elif defined(UNX)
const char C_sSLASH[] = "/";
const char C_cSLASH = '/';
#else
#error Must run under unix or windows, please define UNX or WNT.
#endif
enum E_LinkType
{
lt_nolink = 0,
lt_idl,
lt_html
};
void WriteName(
std::ostream & o_rFile,
const Simstr & i_rIdlDocuBaseDir,
const Simstr & i_rName,
E_LinkType i_eLinkType );
void WriteStr(
std::ostream & o_rFile,
const char * i_sStr );
void WriteStr(
std::ostream & o_rFile,
const Simstr & i_sStr );
void GatherFileNames(
List<Simstr> & o_sFiles,
const char * i_sSrcDirectory );
void GatherSubDirectories(
List<Simstr> & o_sSubDirectories,
const char * i_sParentdDirectory );
#endif
<commit_msg>INTEGRATION: CWS os2port02 (1.7.40); FILE MERGED 2007/10/04 19:45:25 ydario 1.7.40.1: Issue number: i82034 Submitted by: ydario Reviewed by: ydario Commit of changes for OS/2 CWS source code integration.<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: syshelp.hxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: hr $ $Date: 2007-11-02 12:55:47 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef X2C_SYSHELP_HXX
#define X2C_SYSHELP_HXX
// USED SERVICES
// BASE CLASSES
// COMPONENTS
// PARAMETERS
#include <iosfwd>
class Simstr;
template <class XY> class List;
#if defined(WNT) || defined(OS2)
const char C_sSLASH[] = "\\";
const char C_cSLASH = '\\';
#elif defined(UNX)
const char C_sSLASH[] = "/";
const char C_cSLASH = '/';
#else
#error Must run under unix or windows, please define UNX or WNT.
#endif
enum E_LinkType
{
lt_nolink = 0,
lt_idl,
lt_html
};
void WriteName(
std::ostream & o_rFile,
const Simstr & i_rIdlDocuBaseDir,
const Simstr & i_rName,
E_LinkType i_eLinkType );
void WriteStr(
std::ostream & o_rFile,
const char * i_sStr );
void WriteStr(
std::ostream & o_rFile,
const Simstr & i_sStr );
void GatherFileNames(
List<Simstr> & o_sFiles,
const char * i_sSrcDirectory );
void GatherSubDirectories(
List<Simstr> & o_sSubDirectories,
const char * i_sParentdDirectory );
#endif
<|endoftext|> |
<commit_before><commit_msg>coverity#704111: Unchecked return value<commit_after><|endoftext|> |
<commit_before>// Copyright (c) 2013 - 2015, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.
#include <nix/file/DimensionFS.hpp>
using namespace std;
using namespace nix::base;
namespace nix {
namespace file {
DimensionType dimensionTypeFromStr(const string &str) {
if (str == "set") {
return DimensionType::Set;
} else if (str == "range") {
return DimensionType::Range;
} else if (str == "sample") {
return DimensionType::Sample;
} else {
throw runtime_error("Not a valid dimension name");
}
}
std::string dimensionTypeToStr(DimensionType dim) {
//The way this switch + string.empty() checking is
// done here might seem a bit convoluted, but the
// idea behind it is:
// a) have no default case in the switch to get a
// compile warning in case a new element is
// added to the enum
// b) still be safe and throw an exception in case
// not all enum cases are handled properly
std::string dimType;
switch (dim) {
case DimensionType::Set:
dimType = "set";
break;
case DimensionType::Range:
dimType = "range";
break;
case DimensionType::Sample:
dimType = "sample";
break;
}
if (dimType.empty()) {
throw runtime_error("Not a valid dimension type");
}
return dimType;
}
shared_ptr<IDimension> openDimensionFS(const string &loc, size_t index, FileMode mode) {
AttributesFS attr(loc, mode);
string type_name;
attr.get("dimension_type", type_name);
DimensionType type = dimensionTypeFromStr(type_name);
shared_ptr<IDimension> dim;
switch (type) {
case DimensionType::Set:
dim = make_shared<SetDimensionFS>(loc, index, mode);
break;
case DimensionType::Range:
dim = make_shared<RangeDimensionFS>(loc, index, mode);
break;
case DimensionType::Sample:
dim = make_shared<SampledDimensionFS>(loc, index, mode);
break;
}
return dim;
}
// Implementation of Dimension
DimensionFS::DimensionFS(const string &loc, size_t index, FileMode mode)
: DirectoryWithAttributes(loc + boost::filesystem::path::preferred_separator + util::numToStr(index), mode)
{
this->index(index);
}
void DimensionFS::index(size_t index) {
setAttr("index", index);
}
size_t DimensionFS::index() const {
size_t idx;
if (hasAttr("index"))
getAttr("index", idx);
return idx;
}
void DimensionFS::setType() {
if (!hasAttr("dimension_type"))
setAttr("dimension_type", dimensionTypeToStr(dimensionType()));
}
bool DimensionFS::operator==(const DimensionFS &other) const {
return location() == other.location();
}
bool DimensionFS::operator!=(const DimensionFS &other) const {
return !(*this == other);
}
DimensionFS::~DimensionFS() {}
//--------------------------------------------------------------
// Implementation of SampledDimension
//--------------------------------------------------------------
SampledDimensionFS::SampledDimensionFS(const string &loc, size_t index, FileMode mode)
: DimensionFS(loc, index, mode)
{
}
SampledDimensionFS::SampledDimensionFS(const string &loc, size_t index, double sampling_interval, FileMode mode)
: SampledDimensionFS(loc, index, mode)
{
setType();
this->samplingInterval(sampling_interval);
}
DimensionType SampledDimensionFS::dimensionType() const {
return DimensionType::Sample;
}
boost::optional<std::string> SampledDimensionFS::label() const {
boost::optional<std::string> ret;
string label;
if (hasAttr("label")) {
getAttr("label", label);
ret = label;
}
return ret;
}
void SampledDimensionFS::label(const string &label) {
if (label.empty()) {
throw EmptyString("label");
} else {
setAttr("label", label);
// NOTE: forceUpdatedAt() not possible since not reachable from here
}
}
void SampledDimensionFS::label(const none_t t) {
if (hasAttr("label")) {
removeAttr("label");
}
// NOTE: forceUpdatedAt() not possible since not reachable from here
}
boost::optional<std::string> SampledDimensionFS::unit() const {
boost::optional<std::string> ret;
string unit;
if (hasAttr("unit")) {
getAttr("unit", unit);
ret = unit;
}
return ret;
}
void SampledDimensionFS::unit(const string &unit) {
if (unit.empty()) {
throw EmptyString("unit");
} else {
setAttr("unit", unit);
// NOTE: forceUpdatedAt() not possible since not reachable from here
}
}
void SampledDimensionFS::unit(const none_t t) {
if (hasAttr("unit")) {
removeAttr("unit");
}
// NOTE: forceUpdatedAt() not possible since not reachable from here
}
double SampledDimensionFS::samplingInterval() const {
double sampling_interval;
if (hasAttr("sampling_interval")) {
getAttr("sampling_interval", sampling_interval);
return sampling_interval;
} else {
throw MissingAttr("sampling_interval");
}
}
void SampledDimensionFS::samplingInterval(double sampling_interval) {
setAttr("sampling_interval", sampling_interval);
}
boost::optional<double> SampledDimensionFS::offset() const {
boost::optional<double> ret;
double offset = 0;
if (hasAttr("offset")) {
getAttr("offset", offset);
ret = offset;
}
return ret;
}
void SampledDimensionFS::offset(double offset) {
setAttr("offset", offset);
}
void SampledDimensionFS::offset(const none_t t) {
if (hasAttr("offset")) {
removeAttr("offset");
}
}
SampledDimensionFS::~SampledDimensionFS() {}
//--------------------------------------------------------------
// Implementation of SetDimensionHDF5
//--------------------------------------------------------------
SetDimensionFS::SetDimensionFS(const string &loc, size_t index, FileMode mode)
: DimensionFS(loc, index, mode)
{
setType();
}
DimensionType SetDimensionFS::dimensionType() const {
return DimensionType::Set;
}
vector<string> SetDimensionFS::labels() const {
vector<string> labels;
getAttr("labels", labels);
return labels;
}
void SetDimensionFS::labels(const vector<string> &labels) {
setAttr("labels", labels);
}
void SetDimensionFS::labels(const none_t t) {
if (hasAttr("labels")) {
removeAttr("labels");
}
}
SetDimensionFS::~SetDimensionFS() {}
//--------------------------------------------------------------
// Implementation of RangeDimensionHDF5
//--------------------------------------------------------------
RangeDimensionFS::RangeDimensionFS(const string &loc, size_t index, FileMode mode)
: DimensionFS(loc, index, mode)
{
}
RangeDimensionFS::RangeDimensionFS(const string &loc, size_t index, vector<double> ticks, FileMode mode)
: RangeDimensionFS(loc, index, mode)
{
setType();
this->ticks(ticks);
}
RangeDimensionFS::RangeDimensionFS(const string &loc, size_t index, const DataArrayFS &array, FileMode mode)
:RangeDimensionFS(loc, index, mode)
{
setType();
// this->group.createLink(array.group(), array.id()); FIXME
}
DimensionType RangeDimensionFS::dimensionType() const {
return DimensionType::Range;
}
string RangeDimensionFS::redirectGroup() const {
/*
Group g;
if (alias()) {
string group_name = group.objectName(0);
g = group.openGroup(group_name, false);
} else {
g = group;
}
return g;
*/
return "";
}
boost::optional<std::string> RangeDimensionFS::label() const {
boost::optional<std::string> ret;
string label;
/*
Group g = redirectGroup();
bool have_attr = g.getAttr("label", label);
if (have_attr) {
ret = label;
}
*/
return ret;
}
void RangeDimensionFS::label(const string &label) {
if (label.empty()) {
throw EmptyString("label");
}
/*
Group g = redirectGroup();
g.setAttr("label", label);
// NOTE: forceUpdatedAt() not possible since not reachable from here
*/
// FIXME
}
void RangeDimensionFS::label(const none_t t) {
/*
Group g = redirectGroup();
if (g.hasAttr("label")) {
g.removeAttr("label");
}
*/
// FIXME
// NOTE: forceUpdatedAt() not possible since not reachable from here
}
boost::optional<std::string> RangeDimensionFS::unit() const {
boost::optional<std::string> ret;
string unit;
/*
Group g = redirectGroup();
bool have_attr = g.getAttr("unit", unit);
if (have_attr) {
ret = unit;
}
*/ // FIXME
return ret;
}
void RangeDimensionFS::unit(const string &unit) {
if (unit.empty()) {
throw EmptyString("unit");
} else {
// Group g = redirectGroup(); FIXME
// g.setAttr("unit", unit);
// NOTE: forceUpdatedAt() not possible since not reachable from here
}
}
void RangeDimensionFS::unit(const none_t t) {
// Group g = redirectGroup();
// if (g.hasAttr("unit")) {
// g.removeAttr("unit");
// } FIXME
// NOTE: forceUpdatedAt() not possible since not reachable from here
}
bool RangeDimensionFS::alias() const {
return false;
// return group.objectCount() > 0 && !group.hasData("ticks");FIXME
}
vector<double> RangeDimensionFS::ticks() const {
vector<double> ticks;
/*
Group g = redirectGroup();
if (g.hasData("ticks")) {
g.getData("ticks", ticks);
return ticks;
} else if (g.hasData("data")) {
g.getData("data", ticks);
return ticks;
} else {
throw MissingAttr("ticks");
}
*/ // FIXME
return ticks;
}
void RangeDimensionFS::ticks(const vector<double> &ticks) {
/*
Group g = redirectGroup();
if (!alias()) {
g.setData("ticks", ticks);
} else if (g.hasData("data")) {
NDSize extent(1, ticks.size());
DataSet ds = g.openData("data");
ds.setExtent(extent);
ds.write(nix::DataType::Double, extent, ticks.data());
} else {
throw MissingAttr("ticks");
}
*/ //FIXME
}
RangeDimensionFS::~RangeDimensionFS() {}
} // ns nix::file
} // ns nix
<commit_msg>[file_backend/Dimensions] setType always(!) resets the dime type<commit_after>// Copyright (c) 2013 - 2015, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.
#include <nix/file/DimensionFS.hpp>
using namespace std;
using namespace nix::base;
namespace nix {
namespace file {
DimensionType dimensionTypeFromStr(const string &str) {
if (str == "set") {
return DimensionType::Set;
} else if (str == "range") {
return DimensionType::Range;
} else if (str == "sample") {
return DimensionType::Sample;
} else {
throw runtime_error("Not a valid dimension name");
}
}
std::string dimensionTypeToStr(DimensionType dim) {
//The way this switch + string.empty() checking is
// done here might seem a bit convoluted, but the
// idea behind it is:
// a) have no default case in the switch to get a
// compile warning in case a new element is
// added to the enum
// b) still be safe and throw an exception in case
// not all enum cases are handled properly
std::string dimType;
switch (dim) {
case DimensionType::Set:
dimType = "set";
break;
case DimensionType::Range:
dimType = "range";
break;
case DimensionType::Sample:
dimType = "sample";
break;
}
if (dimType.empty()) {
throw runtime_error("Not a valid dimension type");
}
return dimType;
}
shared_ptr<IDimension> openDimensionFS(const string &loc, size_t index, FileMode mode) {
AttributesFS attr(loc, mode);
string type_name;
attr.get("dimension_type", type_name);
DimensionType type = dimensionTypeFromStr(type_name);
shared_ptr<IDimension> dim;
switch (type) {
case DimensionType::Set:
dim = make_shared<SetDimensionFS>(loc, index, mode);
break;
case DimensionType::Range:
dim = make_shared<RangeDimensionFS>(loc, index, mode);
break;
case DimensionType::Sample:
dim = make_shared<SampledDimensionFS>(loc, index, mode);
break;
}
return dim;
}
// Implementation of Dimension
DimensionFS::DimensionFS(const string &loc, size_t index, FileMode mode)
: DirectoryWithAttributes(loc + boost::filesystem::path::preferred_separator + util::numToStr(index), mode)
{
this->index(index);
}
void DimensionFS::index(size_t index) {
setAttr("index", index);
}
size_t DimensionFS::index() const {
size_t idx;
if (hasAttr("index"))
getAttr("index", idx);
return idx;
}
void DimensionFS::setType() {
setAttr("dimension_type", dimensionTypeToStr(dimensionType()));
}
bool DimensionFS::operator==(const DimensionFS &other) const {
return location() == other.location();
}
bool DimensionFS::operator!=(const DimensionFS &other) const {
return !(*this == other);
}
DimensionFS::~DimensionFS() {}
//--------------------------------------------------------------
// Implementation of SampledDimension
//--------------------------------------------------------------
SampledDimensionFS::SampledDimensionFS(const string &loc, size_t index, FileMode mode)
: DimensionFS(loc, index, mode)
{
}
SampledDimensionFS::SampledDimensionFS(const string &loc, size_t index, double sampling_interval, FileMode mode)
: SampledDimensionFS(loc, index, mode)
{
setType();
this->samplingInterval(sampling_interval);
}
DimensionType SampledDimensionFS::dimensionType() const {
return DimensionType::Sample;
}
boost::optional<std::string> SampledDimensionFS::label() const {
boost::optional<std::string> ret;
string label;
if (hasAttr("label")) {
getAttr("label", label);
ret = label;
}
return ret;
}
void SampledDimensionFS::label(const string &label) {
if (label.empty()) {
throw EmptyString("label");
} else {
setAttr("label", label);
// NOTE: forceUpdatedAt() not possible since not reachable from here
}
}
void SampledDimensionFS::label(const none_t t) {
if (hasAttr("label")) {
removeAttr("label");
}
// NOTE: forceUpdatedAt() not possible since not reachable from here
}
boost::optional<std::string> SampledDimensionFS::unit() const {
boost::optional<std::string> ret;
string unit;
if (hasAttr("unit")) {
getAttr("unit", unit);
ret = unit;
}
return ret;
}
void SampledDimensionFS::unit(const string &unit) {
if (unit.empty()) {
throw EmptyString("unit");
} else {
setAttr("unit", unit);
// NOTE: forceUpdatedAt() not possible since not reachable from here
}
}
void SampledDimensionFS::unit(const none_t t) {
if (hasAttr("unit")) {
removeAttr("unit");
}
// NOTE: forceUpdatedAt() not possible since not reachable from here
}
double SampledDimensionFS::samplingInterval() const {
double sampling_interval;
if (hasAttr("sampling_interval")) {
getAttr("sampling_interval", sampling_interval);
return sampling_interval;
} else {
throw MissingAttr("sampling_interval");
}
}
void SampledDimensionFS::samplingInterval(double sampling_interval) {
setAttr("sampling_interval", sampling_interval);
}
boost::optional<double> SampledDimensionFS::offset() const {
boost::optional<double> ret;
double offset = 0;
if (hasAttr("offset")) {
getAttr("offset", offset);
ret = offset;
}
return ret;
}
void SampledDimensionFS::offset(double offset) {
setAttr("offset", offset);
}
void SampledDimensionFS::offset(const none_t t) {
if (hasAttr("offset")) {
removeAttr("offset");
}
}
SampledDimensionFS::~SampledDimensionFS() {}
//--------------------------------------------------------------
// Implementation of SetDimensionHDF5
//--------------------------------------------------------------
SetDimensionFS::SetDimensionFS(const string &loc, size_t index, FileMode mode)
: DimensionFS(loc, index, mode)
{
setType();
}
DimensionType SetDimensionFS::dimensionType() const {
return DimensionType::Set;
}
vector<string> SetDimensionFS::labels() const {
vector<string> labels;
getAttr("labels", labels);
return labels;
}
void SetDimensionFS::labels(const vector<string> &labels) {
setAttr("labels", labels);
}
void SetDimensionFS::labels(const none_t t) {
if (hasAttr("labels")) {
removeAttr("labels");
}
}
SetDimensionFS::~SetDimensionFS() {}
//--------------------------------------------------------------
// Implementation of RangeDimensionHDF5
//--------------------------------------------------------------
RangeDimensionFS::RangeDimensionFS(const string &loc, size_t index, FileMode mode)
: DimensionFS(loc, index, mode)
{
}
RangeDimensionFS::RangeDimensionFS(const string &loc, size_t index, vector<double> ticks, FileMode mode)
: RangeDimensionFS(loc, index, mode)
{
setType();
this->ticks(ticks);
}
RangeDimensionFS::RangeDimensionFS(const string &loc, size_t index, const DataArrayFS &array, FileMode mode)
:RangeDimensionFS(loc, index, mode)
{
setType();
// this->group.createLink(array.group(), array.id()); FIXME
}
DimensionType RangeDimensionFS::dimensionType() const {
return DimensionType::Range;
}
string RangeDimensionFS::redirectGroup() const {
/*
Group g;
if (alias()) {
string group_name = group.objectName(0);
g = group.openGroup(group_name, false);
} else {
g = group;
}
return g;
*/
return "";
}
boost::optional<std::string> RangeDimensionFS::label() const {
boost::optional<std::string> ret;
string label;
/*
Group g = redirectGroup();
bool have_attr = g.getAttr("label", label);
if (have_attr) {
ret = label;
}
*/
return ret;
}
void RangeDimensionFS::label(const string &label) {
if (label.empty()) {
throw EmptyString("label");
}
/*
Group g = redirectGroup();
g.setAttr("label", label);
// NOTE: forceUpdatedAt() not possible since not reachable from here
*/
// FIXME
}
void RangeDimensionFS::label(const none_t t) {
/*
Group g = redirectGroup();
if (g.hasAttr("label")) {
g.removeAttr("label");
}
*/
// FIXME
// NOTE: forceUpdatedAt() not possible since not reachable from here
}
boost::optional<std::string> RangeDimensionFS::unit() const {
boost::optional<std::string> ret;
string unit;
/*
Group g = redirectGroup();
bool have_attr = g.getAttr("unit", unit);
if (have_attr) {
ret = unit;
}
*/ // FIXME
return ret;
}
void RangeDimensionFS::unit(const string &unit) {
if (unit.empty()) {
throw EmptyString("unit");
} else {
// Group g = redirectGroup(); FIXME
// g.setAttr("unit", unit);
// NOTE: forceUpdatedAt() not possible since not reachable from here
}
}
void RangeDimensionFS::unit(const none_t t) {
// Group g = redirectGroup();
// if (g.hasAttr("unit")) {
// g.removeAttr("unit");
// } FIXME
// NOTE: forceUpdatedAt() not possible since not reachable from here
}
bool RangeDimensionFS::alias() const {
return false;
// return group.objectCount() > 0 && !group.hasData("ticks");FIXME
}
vector<double> RangeDimensionFS::ticks() const {
vector<double> ticks;
/*
Group g = redirectGroup();
if (g.hasData("ticks")) {
g.getData("ticks", ticks);
return ticks;
} else if (g.hasData("data")) {
g.getData("data", ticks);
return ticks;
} else {
throw MissingAttr("ticks");
}
*/ // FIXME
return ticks;
}
void RangeDimensionFS::ticks(const vector<double> &ticks) {
/*
Group g = redirectGroup();
if (!alias()) {
g.setData("ticks", ticks);
} else if (g.hasData("data")) {
NDSize extent(1, ticks.size());
DataSet ds = g.openData("data");
ds.setExtent(extent);
ds.write(nix::DataType::Double, extent, ticks.data());
} else {
throw MissingAttr("ticks");
}
*/ //FIXME
}
RangeDimensionFS::~RangeDimensionFS() {}
} // ns nix::file
} // ns nix
<|endoftext|> |
<commit_before>#include "ngraph.h"
#include <stdint.h>
#include <iostream>
#include <cstring>
#include <engpar_support.h>
#include "Iterators/PinIterator.h"
#include "Iterators/GraphIterator.h"
namespace agi {
void Ngraph::getResidence(GraphEdge* e, Peers& residence) const {
agi::PinIterator* pitr = pins(e);
agi::GraphVertex* vtx;
lid_t deg = degree(e);
for (lid_t i=0;i<deg;i++) {
vtx = iterate(pitr);
residence.insert(owner(vtx));
}
destroy(pitr);
}
wgt_t Ngraph::weight(GraphEdge* edge) const {
uintptr_t id = (uintptr_t)(edge)-1;
etype type = id%num_types;
id/=num_types;
if (isHyperGraph)
return edge_weights[type][edge_list[type][id]];
return edge_weights[type][id];
}
lid_t Ngraph::localID(GraphEdge* edge) const {
uintptr_t id = (uintptr_t)(edge)-1;
return id/num_types;
}
gid_t Ngraph::globalID(GraphEdge* edge) const {
if (!isHyperGraph)
return localID(edge);
uintptr_t id = (uintptr_t)(edge)-1;
etype type = id%num_types;
return edge_unmap[type][id/num_types];
}
lid_t Ngraph::u(lid_t e, etype t) const {
bool found = false;
lid_t index = 0;
lid_t bound_low=0;
lid_t bound_high = numLocalVtxs();
while (!found) {
index = (bound_high+bound_low)/2;
if (degree_list[t][index]<= e&& degree_list[t][index+1]>e)
found=true;
else if (degree_list[t][index]<=e)
bound_low=index;
else
bound_high=index;
}
return index;
}
GraphVertex* Ngraph::u(GraphEdge* edge) const {
lid_t lid = (uintptr_t)(edge)-1;
etype type = lid%num_types;
lid/=num_types;
lid_t vid = u(lid,type);
return reinterpret_cast<GraphVertex*>(vid+1);
}
GraphVertex* Ngraph::v(GraphEdge* edge) const {
if (isHyperGraph) {
fprintf(stderr,"v(edge) not supported in hypergraph mode");
return NULL;
}
if (edge==NULL)
return NULL;
uintptr_t id = (uintptr_t)(edge)-1;
etype type = id%num_types;
id/=num_types;
return reinterpret_cast<GraphVertex*>(edge_list[type][id]+1);
}
lid_t Ngraph::degree(GraphEdge* edge) const {
if (!isHyperGraph)
return 2;
uintptr_t id = (uintptr_t)(edge)-1;
etype type = id%num_types;
id/=num_types;
return pin_degree_list[type][id+1]-pin_degree_list[type][id];
}
PinIterator* Ngraph::pins(GraphEdge* edge) const {
uintptr_t id = (uintptr_t)(edge)-1;
etype type = id%num_types;
id/=num_types;
if (!isHyperGraph) {
return new PinIterator(reinterpret_cast<lid_t*>(u(edge)),
reinterpret_cast<lid_t*>((char*)(edge_list[type]
[id]+1)));
}
return new PinIterator((pin_list[type]+pin_degree_list[type][id]),
pin_list[type]+pin_degree_list[type][id+1]);
}
void Ngraph::setEdgeWeights(std::vector<wgt_t>& wgts, etype t) {
assert(!edge_weights[t]);
if (wgts.size()==0) {
edge_weights[t] = new wgt_t[num_local_edges[t]];
for (gid_t i=0;i<num_local_edges[t];i++)
edge_weights[t][i]=1;
return;
}
assert(wgts.size()==num_local_edges[t]);
edge_weights[t] = new wgt_t[num_local_edges[t]];
memcpy(edge_weights[t],&(wgts[0]),num_local_edges[t]*sizeof(wgt_t));
}
//Protected functions
void Ngraph::makeEdgeArray(etype t, int count) {
edge_unmap[t] = new gid_t[count];
edge_weights[t] = new wgt_t[count];
}
void Ngraph::setEdge(lid_t lid,gid_t gid, wgt_t w,etype t) {
edge_unmap[t][lid] = gid;
edge_weights[t][lid] = w;
edge_mapping[t][gid]=lid;
}
}
<commit_msg>Whoops... Deleted something that was needed<commit_after>#include "ngraph.h"
#include <stdint.h>
#include <iostream>
#include <cstring>
#include <engpar_support.h>
#include "Iterators/PinIterator.h"
#include "Iterators/GraphIterator.h"
namespace agi {
void Ngraph::getResidence(GraphEdge* e, Peers& residence) const {
agi::PinIterator* pitr = pins(e);
agi::GraphVertex* vtx;
lid_t deg = degree(e);
for (lid_t i=0;i<deg;i++) {
vtx = iterate(pitr);
residence.insert(owner(vtx));
}
destroy(pitr);
}
wgt_t Ngraph::weight(GraphEdge* edge) const {
uintptr_t id = (uintptr_t)(edge)-1;
etype type = id%num_types;
id/=num_types;
if (isHyperGraph)
return edge_weights[type][edge_list[type][id]];
return edge_weights[type][id];
}
lid_t Ngraph::localID(GraphEdge* edge) const {
uintptr_t id = (uintptr_t)(edge)-1;
return id/num_types;
}
gid_t Ngraph::globalID(GraphEdge* edge) const {
if (!isHyperGraph)
return localID(edge);
uintptr_t id = (uintptr_t)(edge)-1;
etype type = id%num_types;
return edge_unmap[type][id/num_types];
}
lid_t Ngraph::u(lid_t e, etype t) const {
bool found = false;
lid_t index = 0;
lid_t bound_low=0;
lid_t bound_high = numLocalVtxs();
while (!found) {
index = (bound_high+bound_low)/2;
if (degree_list[t][index]<= e&& degree_list[t][index+1]>e)
found=true;
else if (degree_list[t][index]<=e)
bound_low=index;
else
bound_high=index;
}
return index;
}
GraphVertex* Ngraph::u(GraphEdge* edge) const {
lid_t lid = (uintptr_t)(edge)-1;
etype type = lid%num_types;
lid/=num_types;
lid_t vid = u(lid,type);
return reinterpret_cast<GraphVertex*>(vid+1);
}
GraphVertex* Ngraph::v(GraphEdge* edge) const {
if (isHyperGraph) {
fprintf(stderr,"v(edge) not supported in hypergraph mode");
return NULL;
}
if (edge==NULL)
return NULL;
uintptr_t id = (uintptr_t)(edge)-1;
etype type = id%num_types;
id/=num_types;
return reinterpret_cast<GraphVertex*>(edge_list[type][id]+1);
}
lid_t Ngraph::degree(GraphEdge* edge) const {
if (!isHyperGraph)
return 2;
if (edge==NULL)
return 0;
uintptr_t id = (uintptr_t)(edge)-1;
etype type = id%num_types;
id/=num_types;
return pin_degree_list[type][id+1]-pin_degree_list[type][id];
}
PinIterator* Ngraph::pins(GraphEdge* edge) const {
uintptr_t id = (uintptr_t)(edge)-1;
etype type = id%num_types;
id/=num_types;
if (!isHyperGraph) {
return new PinIterator(reinterpret_cast<lid_t*>(u(edge)),
reinterpret_cast<lid_t*>((char*)(edge_list[type][id]+1)));
}
return new PinIterator((pin_list[type]+pin_degree_list[type][id]),
pin_list[type]+pin_degree_list[type][id+1]);
}
void Ngraph::setEdgeWeights(std::vector<wgt_t>& wgts, etype t) {
assert(!edge_weights[t]);
if (wgts.size()==0) {
edge_weights[t] = new wgt_t[num_local_edges[t]];
for (gid_t i=0;i<num_local_edges[t];i++)
edge_weights[t][i]=1;
return;
}
assert(wgts.size()==num_local_edges[t]);
edge_weights[t] = new wgt_t[num_local_edges[t]];
memcpy(edge_weights[t],&(wgts[0]),num_local_edges[t]*sizeof(wgt_t));
}
//Protected functions
void Ngraph::makeEdgeArray(etype t, int count) {
edge_unmap[t] = new gid_t[count];
edge_weights[t] = new wgt_t[count];
}
void Ngraph::setEdge(lid_t lid,gid_t gid, wgt_t w,etype t) {
edge_unmap[t][lid] = gid;
edge_weights[t][lid] = w;
edge_mapping[t][gid]=lid;
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: shapetransitionfactory.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: obo $ $Date: 2005-10-11 08:45:36 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#include <basegfx/numeric/ftools.hxx>
#include <basegfx/matrix/b2dhommatrix.hxx>
#include <basegfx/polygon/b2dpolypolygontools.hxx>
#include <canvas/debug.hxx>
#include <transitionfactory.hxx>
#include <transitiontools.hxx>
#include <parametricpolypolygonfactory.hxx>
#include <animationfactory.hxx>
#include <clippingfunctor.hxx>
#include <com/sun/star/animations/TransitionType.hpp>
#include <com/sun/star/animations/TransitionSubType.hpp>
#ifndef BOOST_BIND_HPP_INCLUDED
#include <boost/bind.hpp>
#endif
using namespace ::com::sun::star;
namespace presentation {
namespace internal {
/***************************************************
*** ***
*** Shape Transition Effects ***
*** ***
***************************************************/
namespace {
class ClippingAnimation : public NumberAnimation
{
public:
ClippingAnimation(
const ParametricPolyPolygonSharedPtr& rPolygon,
const LayerManagerSharedPtr& rLayerManager,
const TransitionInfo& rTransitionInfo,
bool bDirectionForward,
bool bModeIn );
~ClippingAnimation();
// Animation interface
// -------------------
virtual void start( const AnimatableShapeSharedPtr& rShape,
const ShapeAttributeLayerSharedPtr& rAttrLayer );
virtual void end();
// NumberAnimation interface
// -----------------------
virtual bool operator()( double nValue );
virtual double getUnderlyingValue() const;
private:
void end_();
AnimatableShapeSharedPtr mpShape;
ShapeAttributeLayerSharedPtr mpAttrLayer;
LayerManagerSharedPtr mpLayerManager;
ClippingFunctor maClippingFunctor;
bool mbSpriteActive;
};
ClippingAnimation::ClippingAnimation(
const ParametricPolyPolygonSharedPtr& rPolygon,
const LayerManagerSharedPtr& rLayerManager,
const TransitionInfo& rTransitionInfo,
bool bDirectionForward,
bool bModeIn ) :
mpShape(),
mpAttrLayer(),
mpLayerManager( rLayerManager ),
maClippingFunctor( rPolygon,
rTransitionInfo,
bDirectionForward,
bModeIn ),
mbSpriteActive(false)
{
ENSURE_AND_THROW(
rLayerManager.get(),
"ClippingAnimation::ClippingAnimation(): Invalid LayerManager" );
}
ClippingAnimation::~ClippingAnimation()
{
end_();
}
void ClippingAnimation::start( const AnimatableShapeSharedPtr& rShape,
const ShapeAttributeLayerSharedPtr& rAttrLayer )
{
OSL_ENSURE( !mpShape.get(),
"ClippingAnimation::start(): Shape already set" );
OSL_ENSURE( !mpAttrLayer.get(),
"ClippingAnimation::start(): Attribute layer already set" );
mpShape = rShape;
mpAttrLayer = rAttrLayer;
ENSURE_AND_THROW( rShape.get(),
"ClippingAnimation::start(): Invalid shape" );
ENSURE_AND_THROW( rAttrLayer.get(),
"ClippingAnimation::start(): Invalid attribute layer" );
mpShape = rShape;
mpAttrLayer = rAttrLayer;
if( !mbSpriteActive )
{
mpLayerManager->enterAnimationMode( mpShape );
mbSpriteActive = true;
}
}
void ClippingAnimation::end()
{
end_();
}
void ClippingAnimation::end_()
{
if( mbSpriteActive )
{
mbSpriteActive = false;
mpLayerManager->leaveAnimationMode( mpShape );
if( mpShape->isUpdateNecessary() )
mpLayerManager->notifyShapeUpdate( mpShape );
}
}
bool ClippingAnimation::operator()( double nValue )
{
ENSURE_AND_RETURN(
mpAttrLayer.get() && mpShape.get(),
"ClippingAnimation::operator(): Invalid ShapeAttributeLayer" );
// set new clip
mpAttrLayer->setClip( maClippingFunctor( nValue,
mpShape->getUpdateArea().getRange() ) );
if( mpShape->isUpdateNecessary() )
mpLayerManager->notifyShapeUpdate( mpShape );
return true;
}
double ClippingAnimation::getUnderlyingValue() const
{
ENSURE_AND_THROW(
mpAttrLayer.get(),
"ClippingAnimation::getUnderlyingValue(): Invalid ShapeAttributeLayer" );
return 0.0; // though this should be used in concert with
// ActivitiesFactory::createSimpleActivity, better
// explicitely name our start value.
// Permissible range for operator() above is [0,1]
}
} // anon namespace
AnimationActivitySharedPtr TransitionFactory::createShapeTransition(
const ActivitiesFactory::CommonParameters& rParms,
const AnimatableShapeSharedPtr& rShape,
const LayerManagerSharedPtr& rLayerManager,
uno::Reference< animations::XTransitionFilter > const& xTransition )
{
return createShapeTransition( rParms,
rShape,
rLayerManager,
xTransition,
xTransition->getTransition(),
xTransition->getSubtype() );
}
AnimationActivitySharedPtr TransitionFactory::createShapeTransition(
const ActivitiesFactory::CommonParameters& rParms,
const AnimatableShapeSharedPtr& rShape,
const LayerManagerSharedPtr& rLayerManager,
::com::sun::star::uno::Reference<
::com::sun::star::animations::XTransitionFilter > const& xTransition,
sal_Int16 nType,
sal_Int16 nSubType )
{
ENSURE_AND_THROW(
xTransition.is(),
"TransitionFactory::createShapeTransition(): Invalid XTransition" );
const TransitionInfo* pTransitionInfo(
getTransitionInfo( nType, nSubType ) );
AnimationActivitySharedPtr pGeneratedActivity;
if( pTransitionInfo != NULL )
{
switch( pTransitionInfo->meTransitionClass )
{
default:
case TransitionInfo::TRANSITION_INVALID:
OSL_ENSURE( false,
"TransitionFactory::createShapeTransition(): Invalid transition type. "
"Don't ask me for a 0 TransitionType, have no XTransitionFilter node instead!" );
return AnimationActivitySharedPtr();
case TransitionInfo::TRANSITION_CLIP_POLYPOLYGON:
{
// generate parametric poly-polygon
ParametricPolyPolygonSharedPtr pPoly(
ParametricPolyPolygonFactory::createClipPolyPolygon(
nType, nSubType ) );
// create a clip activity from that
pGeneratedActivity = ActivitiesFactory::createSimpleActivity(
rParms,
NumberAnimationSharedPtr(
new ClippingAnimation(
pPoly,
rLayerManager,
*pTransitionInfo,
xTransition->getDirection(),
xTransition->getMode() ) ),
true );
}
break;
case TransitionInfo::TRANSITION_SPECIAL:
{
switch( nType )
{
case animations::TransitionType::RANDOM:
{
// select randomly one of the effects from the
// TransitionFactoryTable
const TransitionInfo* pRandomTransitionInfo( getRandomTransitionInfo() );
ENSURE_AND_THROW( pRandomTransitionInfo != NULL,
"TransitionFactory::createShapeTransition(): Got invalid random transition info" );
ENSURE_AND_THROW( pRandomTransitionInfo->mnTransitionType != animations::TransitionType::RANDOM,
"TransitionFactory::createShapeTransition(): Got random again for random input!" );
// and recurse
pGeneratedActivity = createShapeTransition( rParms,
rShape,
rLayerManager,
xTransition,
pRandomTransitionInfo->mnTransitionType,
pRandomTransitionInfo->mnTransitionSubType );
}
break;
// TODO(F3): Implement slidewipe for shape
case animations::TransitionType::SLIDEWIPE:
{
sal_Int16 nBarWipeSubType(0);
bool bDirectionForward(true);
// map slidewipe to BARWIPE, for now
switch( nSubType )
{
case animations::TransitionSubType::FROMLEFT:
nBarWipeSubType = animations::TransitionSubType::LEFTTORIGHT;
bDirectionForward = true;
break;
case animations::TransitionSubType::FROMRIGHT:
nBarWipeSubType = animations::TransitionSubType::LEFTTORIGHT;
bDirectionForward = false;
break;
case animations::TransitionSubType::FROMTOP:
nBarWipeSubType = animations::TransitionSubType::TOPTOBOTTOM;
bDirectionForward = true;
break;
case animations::TransitionSubType::FROMBOTTOM:
nBarWipeSubType = animations::TransitionSubType::TOPTOBOTTOM;
bDirectionForward = false;
break;
default:
ENSURE_AND_THROW( false,
"TransitionFactory::createShapeTransition(): Unexpected subtype for SLIDEWIPE" );
break;
}
// generate parametric poly-polygon
ParametricPolyPolygonSharedPtr pPoly(
ParametricPolyPolygonFactory::createClipPolyPolygon(
animations::TransitionType::BARWIPE,
nBarWipeSubType ) );
// create a clip activity from that
pGeneratedActivity = ActivitiesFactory::createSimpleActivity(
rParms,
NumberAnimationSharedPtr(
new ClippingAnimation(
pPoly,
rLayerManager,
*getTransitionInfo( animations::TransitionType::BARWIPE,
nBarWipeSubType ),
bDirectionForward,
xTransition->getMode() ) ),
true );
}
break;
default:
{
// TODO(F1): Check whether there's anything left, anyway,
// for _shape_ transitions. AFAIK, there are no special
// effects for shapes...
// for now, map all to fade effect
pGeneratedActivity = ActivitiesFactory::createSimpleActivity(
rParms,
AnimationFactory::createNumberPropertyAnimation(
::rtl::OUString(
RTL_CONSTASCII_USTRINGPARAM("Opacity") ),
rShape,
rLayerManager ),
xTransition->getMode() );
}
break;
}
}
break;
}
}
if( !pGeneratedActivity.get() )
{
// No animation generated, maybe no table entry for given
// transition?
OSL_TRACE(
"TransitionFactory::createShapeTransition(): Unknown type/subtype (%d/%d) "
"combination encountered",
xTransition->getTransition(),
xTransition->getSubtype() );
OSL_ENSURE(
false,
"TransitionFactory::createShapeTransition(): Unknown type/subtype "
"combination encountered" );
}
return pGeneratedActivity;
}
}
}
<commit_msg>INTEGRATION: CWS canvas02 (1.2.34); FILE MERGED 2005/10/17 12:21:07 thb 1.2.34.3: RESYNC: (1.3-1.4); FILE MERGED 2005/10/09 04:21:18 thb 1.2.34.2: RESYNC: (1.2-1.3); FILE MERGED 2005/09/01 14:01:29 thb 1.2.34.1: #122302# Using new Shape::getDOMBounds() method to determine size of the clip polygon, instead of the former getUpdateArea(). This is because, the sprite clip is transformed by the sprite transformation, which in turn contains the _full_ shape transform, relative to the DOM values<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: shapetransitionfactory.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: kz $ $Date: 2005-11-02 14:04: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
*
************************************************************************/
#include <basegfx/numeric/ftools.hxx>
#include <basegfx/matrix/b2dhommatrix.hxx>
#include <basegfx/polygon/b2dpolypolygontools.hxx>
#include <canvas/debug.hxx>
#include <transitionfactory.hxx>
#include <transitiontools.hxx>
#include <parametricpolypolygonfactory.hxx>
#include <animationfactory.hxx>
#include <clippingfunctor.hxx>
#include <com/sun/star/animations/TransitionType.hpp>
#include <com/sun/star/animations/TransitionSubType.hpp>
#ifndef BOOST_BIND_HPP_INCLUDED
#include <boost/bind.hpp>
#endif
using namespace ::com::sun::star;
namespace presentation {
namespace internal {
/***************************************************
*** ***
*** Shape Transition Effects ***
*** ***
***************************************************/
namespace {
class ClippingAnimation : public NumberAnimation
{
public:
ClippingAnimation(
const ParametricPolyPolygonSharedPtr& rPolygon,
const LayerManagerSharedPtr& rLayerManager,
const TransitionInfo& rTransitionInfo,
bool bDirectionForward,
bool bModeIn );
~ClippingAnimation();
// Animation interface
// -------------------
virtual void start( const AnimatableShapeSharedPtr& rShape,
const ShapeAttributeLayerSharedPtr& rAttrLayer );
virtual void end();
// NumberAnimation interface
// -----------------------
virtual bool operator()( double nValue );
virtual double getUnderlyingValue() const;
private:
void end_();
AnimatableShapeSharedPtr mpShape;
ShapeAttributeLayerSharedPtr mpAttrLayer;
LayerManagerSharedPtr mpLayerManager;
ClippingFunctor maClippingFunctor;
bool mbSpriteActive;
};
ClippingAnimation::ClippingAnimation(
const ParametricPolyPolygonSharedPtr& rPolygon,
const LayerManagerSharedPtr& rLayerManager,
const TransitionInfo& rTransitionInfo,
bool bDirectionForward,
bool bModeIn ) :
mpShape(),
mpAttrLayer(),
mpLayerManager( rLayerManager ),
maClippingFunctor( rPolygon,
rTransitionInfo,
bDirectionForward,
bModeIn ),
mbSpriteActive(false)
{
ENSURE_AND_THROW(
rLayerManager.get(),
"ClippingAnimation::ClippingAnimation(): Invalid LayerManager" );
}
ClippingAnimation::~ClippingAnimation()
{
end_();
}
void ClippingAnimation::start( const AnimatableShapeSharedPtr& rShape,
const ShapeAttributeLayerSharedPtr& rAttrLayer )
{
OSL_ENSURE( !mpShape.get(),
"ClippingAnimation::start(): Shape already set" );
OSL_ENSURE( !mpAttrLayer.get(),
"ClippingAnimation::start(): Attribute layer already set" );
mpShape = rShape;
mpAttrLayer = rAttrLayer;
ENSURE_AND_THROW( rShape.get(),
"ClippingAnimation::start(): Invalid shape" );
ENSURE_AND_THROW( rAttrLayer.get(),
"ClippingAnimation::start(): Invalid attribute layer" );
mpShape = rShape;
mpAttrLayer = rAttrLayer;
if( !mbSpriteActive )
{
mpLayerManager->enterAnimationMode( mpShape );
mbSpriteActive = true;
}
}
void ClippingAnimation::end()
{
end_();
}
void ClippingAnimation::end_()
{
if( mbSpriteActive )
{
mbSpriteActive = false;
mpLayerManager->leaveAnimationMode( mpShape );
if( mpShape->isUpdateNecessary() )
mpLayerManager->notifyShapeUpdate( mpShape );
}
}
bool ClippingAnimation::operator()( double nValue )
{
ENSURE_AND_RETURN(
mpAttrLayer.get() && mpShape.get(),
"ClippingAnimation::operator(): Invalid ShapeAttributeLayer" );
// set new clip
mpAttrLayer->setClip( maClippingFunctor( nValue,
mpShape->getDOMBounds().getRange() ) );
if( mpShape->isUpdateNecessary() )
mpLayerManager->notifyShapeUpdate( mpShape );
return true;
}
double ClippingAnimation::getUnderlyingValue() const
{
ENSURE_AND_THROW(
mpAttrLayer.get(),
"ClippingAnimation::getUnderlyingValue(): Invalid ShapeAttributeLayer" );
return 0.0; // though this should be used in concert with
// ActivitiesFactory::createSimpleActivity, better
// explicitely name our start value.
// Permissible range for operator() above is [0,1]
}
} // anon namespace
AnimationActivitySharedPtr TransitionFactory::createShapeTransition(
const ActivitiesFactory::CommonParameters& rParms,
const AnimatableShapeSharedPtr& rShape,
const LayerManagerSharedPtr& rLayerManager,
uno::Reference< animations::XTransitionFilter > const& xTransition )
{
return createShapeTransition( rParms,
rShape,
rLayerManager,
xTransition,
xTransition->getTransition(),
xTransition->getSubtype() );
}
AnimationActivitySharedPtr TransitionFactory::createShapeTransition(
const ActivitiesFactory::CommonParameters& rParms,
const AnimatableShapeSharedPtr& rShape,
const LayerManagerSharedPtr& rLayerManager,
::com::sun::star::uno::Reference<
::com::sun::star::animations::XTransitionFilter > const& xTransition,
sal_Int16 nType,
sal_Int16 nSubType )
{
ENSURE_AND_THROW(
xTransition.is(),
"TransitionFactory::createShapeTransition(): Invalid XTransition" );
const TransitionInfo* pTransitionInfo(
getTransitionInfo( nType, nSubType ) );
AnimationActivitySharedPtr pGeneratedActivity;
if( pTransitionInfo != NULL )
{
switch( pTransitionInfo->meTransitionClass )
{
default:
case TransitionInfo::TRANSITION_INVALID:
OSL_ENSURE( false,
"TransitionFactory::createShapeTransition(): Invalid transition type. "
"Don't ask me for a 0 TransitionType, have no XTransitionFilter node instead!" );
return AnimationActivitySharedPtr();
case TransitionInfo::TRANSITION_CLIP_POLYPOLYGON:
{
// generate parametric poly-polygon
ParametricPolyPolygonSharedPtr pPoly(
ParametricPolyPolygonFactory::createClipPolyPolygon(
nType, nSubType ) );
// create a clip activity from that
pGeneratedActivity = ActivitiesFactory::createSimpleActivity(
rParms,
NumberAnimationSharedPtr(
new ClippingAnimation(
pPoly,
rLayerManager,
*pTransitionInfo,
xTransition->getDirection(),
xTransition->getMode() ) ),
true );
}
break;
case TransitionInfo::TRANSITION_SPECIAL:
{
switch( nType )
{
case animations::TransitionType::RANDOM:
{
// select randomly one of the effects from the
// TransitionFactoryTable
const TransitionInfo* pRandomTransitionInfo( getRandomTransitionInfo() );
ENSURE_AND_THROW( pRandomTransitionInfo != NULL,
"TransitionFactory::createShapeTransition(): Got invalid random transition info" );
ENSURE_AND_THROW( pRandomTransitionInfo->mnTransitionType != animations::TransitionType::RANDOM,
"TransitionFactory::createShapeTransition(): Got random again for random input!" );
// and recurse
pGeneratedActivity = createShapeTransition( rParms,
rShape,
rLayerManager,
xTransition,
pRandomTransitionInfo->mnTransitionType,
pRandomTransitionInfo->mnTransitionSubType );
}
break;
// TODO(F3): Implement slidewipe for shape
case animations::TransitionType::SLIDEWIPE:
{
sal_Int16 nBarWipeSubType(0);
bool bDirectionForward(true);
// map slidewipe to BARWIPE, for now
switch( nSubType )
{
case animations::TransitionSubType::FROMLEFT:
nBarWipeSubType = animations::TransitionSubType::LEFTTORIGHT;
bDirectionForward = true;
break;
case animations::TransitionSubType::FROMRIGHT:
nBarWipeSubType = animations::TransitionSubType::LEFTTORIGHT;
bDirectionForward = false;
break;
case animations::TransitionSubType::FROMTOP:
nBarWipeSubType = animations::TransitionSubType::TOPTOBOTTOM;
bDirectionForward = true;
break;
case animations::TransitionSubType::FROMBOTTOM:
nBarWipeSubType = animations::TransitionSubType::TOPTOBOTTOM;
bDirectionForward = false;
break;
default:
ENSURE_AND_THROW( false,
"TransitionFactory::createShapeTransition(): Unexpected subtype for SLIDEWIPE" );
break;
}
// generate parametric poly-polygon
ParametricPolyPolygonSharedPtr pPoly(
ParametricPolyPolygonFactory::createClipPolyPolygon(
animations::TransitionType::BARWIPE,
nBarWipeSubType ) );
// create a clip activity from that
pGeneratedActivity = ActivitiesFactory::createSimpleActivity(
rParms,
NumberAnimationSharedPtr(
new ClippingAnimation(
pPoly,
rLayerManager,
*getTransitionInfo( animations::TransitionType::BARWIPE,
nBarWipeSubType ),
bDirectionForward,
xTransition->getMode() ) ),
true );
}
break;
default:
{
// TODO(F1): Check whether there's anything left, anyway,
// for _shape_ transitions. AFAIK, there are no special
// effects for shapes...
// for now, map all to fade effect
pGeneratedActivity = ActivitiesFactory::createSimpleActivity(
rParms,
AnimationFactory::createNumberPropertyAnimation(
::rtl::OUString(
RTL_CONSTASCII_USTRINGPARAM("Opacity") ),
rShape,
rLayerManager ),
xTransition->getMode() );
}
break;
}
}
break;
}
}
if( !pGeneratedActivity.get() )
{
// No animation generated, maybe no table entry for given
// transition?
OSL_TRACE(
"TransitionFactory::createShapeTransition(): Unknown type/subtype (%d/%d) "
"combination encountered",
xTransition->getTransition(),
xTransition->getSubtype() );
OSL_ENSURE(
false,
"TransitionFactory::createShapeTransition(): Unknown type/subtype "
"combination encountered" );
}
return pGeneratedActivity;
}
}
}
<|endoftext|> |
<commit_before><commit_msg>Update mongoUnsubscribeContext.cpp<commit_after><|endoftext|> |
<commit_before><commit_msg>added allreduct for testing<commit_after><|endoftext|> |
<commit_before>/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* 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.
*/
#pragma once
#include "begin_native.hpp"
#include <chrono>
#include <geode/util/chrono/duration.hpp>
#include "end_native.hpp"
namespace Apache
{
namespace Geode
{
namespace Client
{
using namespace System;
using namespace apache::geode::util::chrono::duration;
using ticks = std::chrono::duration<long long, std::ratio<1, 10000000>>;
class TimeUtils
{
public:
template <class _Duration>
inline static _Duration TimeSpanToDurationCeil(TimeSpan timeSpan)
{
return _ceil<_Duration>(TimeSpanToDuration(timeSpan));
}
inline static ticks TimeSpanToDuration(TimeSpan timespan)
{
return ticks(timespan.Ticks);
}
inline static TimeSpan DurationToTimeSpan(ticks duration)
{
return TimeSpan::FromTicks(duration.count());
}
inline static DateTime TimePointToDateTime(std::chrono::system_clock::time_point timePoint) {
using namespace std::chrono;
auto t = duration_cast<ticks>(timePoint.time_since_epoch());
t += epochDifference;
return DateTime(t.count());
}
inline static std::chrono::system_clock::time_point DateTimeToTimePoint(DateTime dateTime) {
using namespace std::chrono;
auto t = ticks(dateTime.Ticks);
t -= epochDifference;
return system_clock::time_point(t);
}
private:
static constexpr auto epochDifference = ticks(621355968000000000);
};
} // namespace Client
} // namespace Geode
} // namespace Apache
<commit_msg>GEODE-4188: Fixes CLI inlude of internal duration header.<commit_after>/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* 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.
*/
#pragma once
#include "begin_native.hpp"
#include <chrono>
#include <geode/internal/chrono/duration.hpp>
#include "end_native.hpp"
namespace Apache
{
namespace Geode
{
namespace Client
{
using namespace System;
using namespace apache::geode::internal::chrono::duration;
using ticks = std::chrono::duration<long long, std::ratio<1, 10000000>>;
class TimeUtils
{
public:
template <class _Duration>
inline static _Duration TimeSpanToDurationCeil(TimeSpan timeSpan)
{
return _ceil<_Duration>(TimeSpanToDuration(timeSpan));
}
inline static ticks TimeSpanToDuration(TimeSpan timespan)
{
return ticks(timespan.Ticks);
}
inline static TimeSpan DurationToTimeSpan(ticks duration)
{
return TimeSpan::FromTicks(duration.count());
}
inline static DateTime TimePointToDateTime(std::chrono::system_clock::time_point timePoint) {
using namespace std::chrono;
auto t = duration_cast<ticks>(timePoint.time_since_epoch());
t += epochDifference;
return DateTime(t.count());
}
inline static std::chrono::system_clock::time_point DateTimeToTimePoint(DateTime dateTime) {
using namespace std::chrono;
auto t = ticks(dateTime.Ticks);
t -= epochDifference;
return system_clock::time_point(t);
}
private:
static constexpr auto epochDifference = ticks(621355968000000000);
};
} // namespace Client
} // namespace Geode
} // namespace Apache
<|endoftext|> |
<commit_before>// Copyright eeGeo Ltd (2012-2015), All Rights Reserved
#include "Search.h"
#include "ICallback.h"
#include "SearchResultModel.h"
#include "YelpSearchQueryFactory.h"
#include "YelpSearchQuery.h"
#include "YelpSearchConstants.h"
#include "YelpCategoryModel.h"
#include "IAppCameraController.h"
#include "CameraState.h"
#include "RenderCamera.h"
#include "urlencode.h"
#include <sstream>
#include <iomanip>
namespace ExampleApp
{
namespace Search
{
namespace Yelp
{
namespace SdkModel
{
namespace
{
std::string UrlGetParamsEncoder(const std::map<std::string, std::string>& params)
{
std::string url;
for (std::map<std::string, std::string>::const_iterator it = params.begin();
it != params.end();
++it)
{
url += it->first + "=" + urlencode(it->second, URLEncodeType::URLEncode_Everything) + "&";
}
//remove trailing &
url[url.length() - 1] = '\0';
return url;
}
int GetSearchRadius(ExampleApp::AppCamera::SdkModel::IAppCameraController& cameraController)
{
const float SearchRadiusMin = 50.0f;
const float SearchRadiusMax = 40000.0f;
double distanceToInterest = (cameraController.GetCameraState().InterestPointEcef() - cameraController.GetCameraState().LocationEcef()).Length();
float radius = (distanceToInterest * Eegeo::Math::Tan(cameraController.GetRenderCamera().GetFOV()));
return static_cast<int>(Eegeo::Clamp(radius, SearchRadiusMin, SearchRadiusMax));
}
}
YelpSearchQueryFactory::YelpSearchQueryFactory(
const std::string& yelpApiKey,
SdkModel::SearchTagToYelpCategoryMapper& searchTagToYelpCategoryMap,
Eegeo::Web::IWebLoadRequestFactory& webRequestFactory,
ExampleApp::AppCamera::SdkModel::IAppCameraController& cameraController)
: m_webRequestFactory(webRequestFactory)
, m_cameraController(cameraController)
, m_yelpApiKey(yelpApiKey)
, m_searchTagToYelpCategoryMap(searchTagToYelpCategoryMap)
, m_apiUrl("https://api.yelp.com/v3/businesses/search")
{
}
YelpSearchQueryFactory::~YelpSearchQueryFactory()
{
}
SdkModel::IYelpSearchQuery* YelpSearchQueryFactory::CreateYelpSearchForQuery(const Search::SdkModel::SearchQuery& searchQuery,
Eegeo::Helpers::ICallback0 &completionCallback)
{
std::string searchTerm = "";
YelpCategoryModel categoryFilter { "", true };
std::string searchLimit("20");
if (searchQuery.IsTag())
{
m_searchTagToYelpCategoryMap.TryGetBestYelpCategoryForSearchTag(searchQuery.Query(), categoryFilter);
if(categoryFilter.skipYelpSearch == true)
{
searchLimit = "0";
}
}
else
{
searchTerm = searchQuery.Query();
}
std::map<std::string, std::string> params;
std::stringstream conversionStream;
conversionStream.setf(std::ios::fixed);
conversionStream << std::setprecision(17)
<< searchQuery.Location().GetLatitudeInDegrees();
std::string latitude = conversionStream.str();
conversionStream.clear();
conversionStream.str("");
conversionStream << std::setprecision(17)
<< searchQuery.Location().GetLongitudeInDegrees();
std::string longitude = conversionStream.str();
if (searchTerm.length() > 0)
{
params["term"] = searchTerm;
}
if (categoryFilter.yelpCategoryFilter.length() > 0)
{
params["categories"] = categoryFilter.yelpCategoryFilter;
}
params["latitude"] = latitude;
params["longitude"] = longitude;
params["limit"] = searchLimit;
int radius = GetSearchRadius(m_cameraController);
conversionStream.clear();
conversionStream.str("");
conversionStream << radius;
params["radius"] = conversionStream.str();
std::stringstream requestUrl;
requestUrl << m_apiUrl << "?" << UrlGetParamsEncoder(params);
return Eegeo_NEW(YelpSearchQuery)(
requestUrl.str(),
m_yelpApiKey,
completionCallback,
m_webRequestFactory);
}
}
}
}
}
<commit_msg>fix MPLY-10022 'Yelp searches only return results in the viewport rather than via radius'<commit_after>// Copyright eeGeo Ltd (2012-2015), All Rights Reserved
#include "Search.h"
#include "ICallback.h"
#include "SearchResultModel.h"
#include "YelpSearchQueryFactory.h"
#include "YelpSearchQuery.h"
#include "YelpSearchConstants.h"
#include "YelpCategoryModel.h"
#include "IAppCameraController.h"
#include "CameraState.h"
#include "RenderCamera.h"
#include "urlencode.h"
#include <sstream>
#include <iomanip>
namespace ExampleApp
{
namespace Search
{
namespace Yelp
{
namespace SdkModel
{
namespace
{
std::string UrlGetParamsEncoder(const std::map<std::string, std::string>& params)
{
std::string url;
for (std::map<std::string, std::string>::const_iterator it = params.begin();
it != params.end();
++it)
{
url += it->first + "=" + urlencode(it->second, URLEncodeType::URLEncode_Everything) + "&";
}
//remove trailing &
url[url.length() - 1] = '\0';
return url;
}
int GetSearchRadius(ExampleApp::AppCamera::SdkModel::IAppCameraController& cameraController)
{
const float SearchRadiusMin = 250.0f;
const float SearchRadiusMax = 40000.0f;
double distanceToInterest = (cameraController.GetCameraState().InterestPointEcef() - cameraController.GetCameraState().LocationEcef()).Length();
float radius = (distanceToInterest * Eegeo::Math::Tan(cameraController.GetRenderCamera().GetFOV()));
return static_cast<int>(Eegeo::Clamp(radius, SearchRadiusMin, SearchRadiusMax));
}
}
YelpSearchQueryFactory::YelpSearchQueryFactory(
const std::string& yelpApiKey,
SdkModel::SearchTagToYelpCategoryMapper& searchTagToYelpCategoryMap,
Eegeo::Web::IWebLoadRequestFactory& webRequestFactory,
ExampleApp::AppCamera::SdkModel::IAppCameraController& cameraController)
: m_webRequestFactory(webRequestFactory)
, m_cameraController(cameraController)
, m_yelpApiKey(yelpApiKey)
, m_searchTagToYelpCategoryMap(searchTagToYelpCategoryMap)
, m_apiUrl("https://api.yelp.com/v3/businesses/search")
{
}
YelpSearchQueryFactory::~YelpSearchQueryFactory()
{
}
SdkModel::IYelpSearchQuery* YelpSearchQueryFactory::CreateYelpSearchForQuery(const Search::SdkModel::SearchQuery& searchQuery,
Eegeo::Helpers::ICallback0 &completionCallback)
{
std::string searchTerm = "";
YelpCategoryModel categoryFilter { "", true };
std::string searchLimit("20");
if (searchQuery.IsTag())
{
m_searchTagToYelpCategoryMap.TryGetBestYelpCategoryForSearchTag(searchQuery.Query(), categoryFilter);
if(categoryFilter.skipYelpSearch == true)
{
searchLimit = "0";
}
}
else
{
searchTerm = searchQuery.Query();
}
std::map<std::string, std::string> params;
std::stringstream conversionStream;
conversionStream.setf(std::ios::fixed);
conversionStream << std::setprecision(17)
<< searchQuery.Location().GetLatitudeInDegrees();
std::string latitude = conversionStream.str();
conversionStream.clear();
conversionStream.str("");
conversionStream << std::setprecision(17)
<< searchQuery.Location().GetLongitudeInDegrees();
std::string longitude = conversionStream.str();
if (searchTerm.length() > 0)
{
params["term"] = searchTerm;
}
if (categoryFilter.yelpCategoryFilter.length() > 0)
{
params["categories"] = categoryFilter.yelpCategoryFilter;
}
params["latitude"] = latitude;
params["longitude"] = longitude;
params["limit"] = searchLimit;
int radius = GetSearchRadius(m_cameraController);
conversionStream.clear();
conversionStream.str("");
conversionStream << radius;
params["radius"] = conversionStream.str();
std::stringstream requestUrl;
requestUrl << m_apiUrl << "?" << UrlGetParamsEncoder(params);
return Eegeo_NEW(YelpSearchQuery)(
requestUrl.str(),
m_yelpApiKey,
completionCallback,
m_webRequestFactory);
}
}
}
}
}
<|endoftext|> |
<commit_before>#ifndef STAN_MATH_PRIM_PROB_INV_WISHART_CHOLESKY_RNG_HPP
#define STAN_MATH_PRIM_PROB_INV_WISHART_CHOLESKY_RNG_HPP
#include <stan/math/prim/meta.hpp>
#include <stan/math/prim/err.hpp>
#include <stan/math/prim/prob/wishart_cholesky_rng.hpp>
#include <stan/math/prim/prob/wishart_rng.hpp>
namespace stan {
namespace math {
/** \ingroup multivar_dists
* Return a random Cholesky factor of a covariance matrix
* of the specified dimensionality drawn
* from the inverse Wishart distribution with the specified degrees of freedom
* using the specified random number generator.
*
* @tparam RNG Random number generator type
* @param[in] nu scalar degrees of freedom
* @param[in] L_S lower Cholesky factor of the scale matrix
* @param[in, out] rng random-number generator
* @return random lower Cholesky factor drawn from the given inverse Wishart
* distribution
* @throw std::domain_error if the scale matrix is not a Cholesky factor
* @throw std::domain_error if the degrees of freedom is greater than k - 1
* where k is the dimension of L
*/
template <class RNG>
inline Eigen::MatrixXd inv_wishart_cholesky_rng(double nu,
const Eigen::MatrixXd& L_S,
RNG& rng) {
using Eigen::MatrixXd;
static const char* function = "inv_wishart_cholesky_rng";
index_type_t<MatrixXd> k = L_S.rows();
check_greater(function, "degrees of freedom > dims - 1", nu, k - 1);
check_positive(function, "Cholesky Scale matrix", L_S.diagonal());
check_positive(function, "columns of Cholesky Scale matrix", L_S.cols());
MatrixXd L_Sinv = mdivide_left_tri<Eigen::Lower>(L_S);
return mdivide_left_tri<Eigen::Lower>(wishart_cholesky_rng(nu, L_Sinv, rng));
}
} // namespace math
} // namespace stan
#endif
<commit_msg>Update inv_wishart_cholesky_rng.hpp<commit_after>#ifndef STAN_MATH_PRIM_PROB_INV_WISHART_CHOLESKY_RNG_HPP
#define STAN_MATH_PRIM_PROB_INV_WISHART_CHOLESKY_RNG_HPP
#include <stan/math/prim/meta.hpp>
#include <stan/math/prim/err.hpp>
#include <stan/math/prim/prob/wishart_cholesky_rng.hpp>
#include <stan/math/prim/prob/wishart_rng.hpp>
namespace stan {
namespace math {
/** \ingroup multivar_dists
* Return a random Cholesky factor of a covariance matrix
* of the specified dimensionality drawn
* from the inverse Wishart distribution with the specified degrees of freedom
* using the specified random number generator.
*
* @tparam RNG Random number generator type
* @param[in] nu scalar degrees of freedom
* @param[in] L_S lower Cholesky factor of the scale matrix
* @param[in, out] rng random-number generator
* @return random lower Cholesky factor drawn from the given inverse Wishart
* distribution
* @throw std::domain_error if the scale matrix is not a Cholesky factor
* @throw std::domain_error if the degrees of freedom is greater than k - 1
* where k is the dimension of L
*/
template <class RNG>
inline Eigen::MatrixXd inv_wishart_cholesky_rng(double nu,
const Eigen::MatrixXd& L_S,
RNG& rng) {
using Eigen::MatrixXd;
static const char* function = "inv_wishart_cholesky_rng";
index_type_t<MatrixXd> k = L_S.rows();
check_greater(function, "degrees of freedom > dims - 1", nu, k - 1);
check_positive(function, "Cholesky Scale matrix", L_S.diagonal());
check_positive(function, "columns of Cholesky Scale matrix", L_S.cols());
MatrixXd L_Sinv = stan::math::mdivide_left_tri<Eigen::Lower>(L_S);
return stan::math::mdivide_left_tri<Eigen::Lower>(wishart_cholesky_rng(nu, L_Sinv, rng));
}
} // namespace math
} // namespace stan
#endif
<|endoftext|> |
<commit_before>#include "regex.h"
#include <iostream>
#include <algorithm>
#include <map>
#include "document.h"
#include "prolog.h"
#include "pi.h"
#include "doctype.h"
#include "attribute.h"
#include "element.h"
#include "composite_element.h"
#include "content.h"
static std::string schema_to_regex(CompositeElement *, std::map<std::string, std::string> &);
static std::string element_to_regex(Element *, std::map<std::string, std::string> &);
static std::string simple_element_to_regex(Element *, std::map<std::string, std::string> &);
static std::string complexe_type_to_regex(CompositeElement *, std::map<std::string, std::string> &);
static std::string choice_to_regex(CompositeElement *, std::map<std::string, std::string> &);
static std::string sequence_to_regex(CompositeElement *, std::map<std::string, std::string> &, bool mixed=false);
static const std::string re_string("[^<]*");
static const std::string re_date("[0-9]{4}-[0-9]{2}-[0-9]{2}(((\\+|-)[0-2][0-9]:[0-5][0-9])|Z)?");
static const std::string re_mixed("[^<]*");
static const std::string re_blank("\\s*");
static const std::string re_S("(\\s+)");
static const std::string re_Eq(re_S + "?=" + re_S + "?");
static const std::string re_Name("[:A-Za-z\\200-\\377_][:A-Za-z\\200-\\377_0-9.-]*");
static const std::string re_AttValue("(\"[^<&\"]*\"|\'[^<&\"]*\')");
static const std::string re_Attr(re_Name + re_Eq + re_AttValue);
static const std::string re_version_info(re_S + "version" + re_Eq + "(\"1\\.[0-9]+\"|'1\\.[0-9]+')");
static const std::string re_encoding_decl(re_S + "encoding" + re_Eq + re_AttValue);
static const std::string re_sd_decl(re_S + re_Attr);
static const std::string re_xml_decl("<\\?xml(" +
re_version_info + ")?(" +
re_encoding_decl + ")?(" +
re_sd_decl + ")? ?\\?>");
static const std::string re_comment("<!--([^-]|-[^-])*-->");
static const std::string re_PI("<\\?" + re_Name + "(" + re_S + re_Attr + ")*\\?>");
static const std::string re_Misc("(" + re_comment + "|" + re_PI + "|" + re_S + ")");
static const std::string re_doctype_decl("<!DOCTYPE" + re_S + re_Name + "(" + re_S + re_Name + ")?(" + re_S + re_AttValue + ")?" + re_S + "?>");
static const std::string re_prolog("(" + re_xml_decl + ")?" + re_Misc + "*(" + re_doctype_decl + re_Misc + "*)?");
std::string xsd_to_regex(Document * doc)
{
// std::cout << "xml : " << re_xml_decl << std::endl;
// std::cout << "doc : " << re_doctype_decl << std::endl;
// std::cout << "com : " << re_comment << std::endl;
// std::cout << "pi : " << re_PI << std::endl;
// std::cout << "pro : " << re_prolog << std::endl;
CompositeElement * root = dynamic_cast<CompositeElement *>(doc->root());
if (root == nullptr)
return "^$";
if (root->begin_tag() == "xsd:schema")
{
std::map<std::string, std::string> refs;
std::string re("^" + re_prolog + schema_to_regex(root, refs) + re_Misc + "*$");
std::cout << re << std::endl; // Mais oui c'est clair
return re;
}
return "^$";
}
std::string schema_to_regex(CompositeElement * s,
std::map<std::string, std::string> & refs)
{
std::string r;
for (auto c : s->content())
{
auto e = dynamic_cast<Element *>(c);
if (e != nullptr && e->name() == "xsd:element")
r += element_to_regex(e, refs) + "|";
}
r = r.substr(0, r.length() - 1);
return "(" + r + ")";
}
std::string element_to_regex(Element * e,
std::map<std::string, std::string> & refs)
{
auto it_name = std::find_if(e->attributes().begin(), e->attributes().end(),
[](Attribute * a) { return a->name() == "name"; });
if (it_name == e->attributes().end())
{
auto it_ref = std::find_if(e->attributes().begin(), e->attributes().end(),
[](Attribute * a) { return a->name() == "ref"; });
if (it_ref == e->attributes().end())
return "";
auto ref = (*it_ref)->value();
auto r = refs.find(ref);
if (r == refs.end())
return "";
return r->second;
}
auto name = (*it_name)->value();
const std::string begin("<" + name + "(" + re_S + re_Attr + ")*" + re_blank + ">");
const std::string end("</" + name + re_blank + ">");
auto ce = dynamic_cast<CompositeElement *>(e);
if (ce != nullptr)
{
CompositeElement * cce = nullptr;
if (ce->content().size() >= 1
&& (cce = dynamic_cast<CompositeElement *>(ce->content().front())) != nullptr
&& cce->begin_tag() == "xsd:complexType")
{
std::string r(begin + complexe_type_to_regex(cce, refs) + end);
refs[name] = r;
return r;
}
}
else
{
std::string r( begin + simple_element_to_regex(e, refs) + end);
refs[name] = r;
return r;
}
return "";
}
std::string simple_element_to_regex(Element * e,
std::map<std::string, std::string> &)
{
auto it_type = std::find_if(e->attributes().begin(), e->attributes().end(),
[](Attribute * a) { return a->name() == "type"; });
if (it_type == e->attributes().end())
return "";
auto type = (*it_type)->value();
if (type == "xsd:string")
return re_string;
else if (type == "xsd:date")
return re_date;
return "";
}
std::string complexe_type_to_regex(CompositeElement * e,
std::map<std::string, std::string> & refs)
{
if (e->content().size() < 1)
return "";
CompositeElement * ce = dynamic_cast<CompositeElement *>(e->content().front());
if (ce == nullptr)
return "";
bool mixed = false;
auto it_mixed = std::find_if(e->attributes().begin(), e->attributes().end(),
[](Attribute * a) { return a->name() == "mixed"; });
if (it_mixed != e->attributes().end()
&& (*it_mixed)->value() == "true")
mixed = true;
std::string s;
if (ce->begin_tag() == "xsd:choice")
{
if (mixed)
s += re_mixed;
s += choice_to_regex(ce, refs);
if (mixed)
s += re_mixed;
}
else if (ce->begin_tag() == "xsd:sequence")
{
s += sequence_to_regex(ce, refs, mixed);
}
return s;
}
std::string choice_to_regex(CompositeElement * e,
std::map<std::string, std::string> & refs)
{
std::string s;
for (auto c : e->content())
{
auto ce = dynamic_cast<Element *>(c);
if (ce)
{
s += element_to_regex(ce, refs);
if (c != e->content().back())
s += "|";
}
}
return re_blank + "(" + s + ")" + re_blank;
}
std::string sequence_to_regex(CompositeElement * e,
std::map<std::string, std::string> & refs, bool mixed)
{
std::string s;
std::string space = mixed ? re_mixed : re_blank;
for (auto c : e->content())
{
auto ce = dynamic_cast<Element *>(c);
if (ce)
{
auto it_maxOccurs = std::find_if(ce->attributes().begin(),
ce->attributes().end(),
[](Attribute * a) { return a->name() == "maxOccurs"; });
std::string maxOccurs("1");
if (it_maxOccurs != ce->attributes().end())
maxOccurs = (*it_maxOccurs)->value();
s += "(" + element_to_regex(ce, refs) + "){1," + maxOccurs + "}" + space;
}
}
return space + s;
}
<commit_msg>Tous les tests passe pour p et v<commit_after>#include "regex.h"
#include <iostream>
#include <algorithm>
#include <map>
#include "document.h"
#include "prolog.h"
#include "pi.h"
#include "doctype.h"
#include "attribute.h"
#include "element.h"
#include "composite_element.h"
#include "content.h"
static std::string schema_to_regex(CompositeElement *, std::map<std::string, std::string> &);
static std::string element_to_regex(Element *, std::map<std::string, std::string> &);
static std::string simple_element_to_regex(Element *, std::map<std::string, std::string> &);
static std::string complexe_type_to_regex(CompositeElement *, std::map<std::string, std::string> &);
static std::string choice_to_regex(CompositeElement *, std::map<std::string, std::string> &);
static std::string sequence_to_regex(CompositeElement *, std::map<std::string, std::string> &, bool mixed=false);
static const std::string re_string("[^<]*");
static const std::string re_date("[0-9]{4}-[0-9]{2}-[0-9]{2}(((\\+|-)[0-2][0-9]:[0-5][0-9])|Z)?");
static const std::string re_mixed("[^<]*");
static const std::string re_blank("\\s*");
static const std::string re_S("(\\s+)");
static const std::string re_Eq(re_S + "?=" + re_S + "?");
static const std::string re_Name("[:A-Za-z\\200-\\377_][:A-Za-z\\200-\\377_0-9.-]*");
static const std::string re_AttValue("(\"[^<&\"]*\"|\'[^<&\"]*\')");
static const std::string re_Attr(re_Name + re_Eq + re_AttValue);
static const std::string re_version_info(re_S + "version" + re_Eq + "(\"1\\.[0-9]+\"|'1\\.[0-9]+')");
static const std::string re_encoding_decl(re_S + "encoding" + re_Eq + re_AttValue);
static const std::string re_sd_decl(re_S + re_Attr);
static const std::string re_xml_decl("<\\?xml(" +
re_version_info + ")?(" +
re_encoding_decl + ")?(" +
re_sd_decl + ")? ?\\?>");
static const std::string re_comment("<!--([^-]|-[^-])*-->");
static const std::string re_PI("<\\?" + re_Name + "(" + re_S + re_Attr + ")*\\?>");
static const std::string re_Misc("(" + re_comment + "|" + re_PI + "|" + re_S + ")");
static const std::string re_doctype_decl("<!DOCTYPE" + re_S + re_Name + "(" + re_S + re_Name + ")?(" + re_S + re_AttValue + ")?" + re_S + "?>");
static const std::string re_prolog("(" + re_xml_decl + ")?" + re_Misc + "*(" + re_doctype_decl + re_Misc + "*)?");
std::string xsd_to_regex(Document * doc)
{
// std::cout << "xml : " << re_xml_decl << std::endl;
// std::cout << "doc : " << re_doctype_decl << std::endl;
// std::cout << "com : " << re_comment << std::endl;
// std::cout << "pi : " << re_PI << std::endl;
// std::cout << "pro : " << re_prolog << std::endl;
CompositeElement * root = dynamic_cast<CompositeElement *>(doc->root());
if (root == nullptr)
return "^$";
if (root->begin_tag() == "xsd:schema")
{
std::map<std::string, std::string> refs;
std::string re("^" + re_prolog + schema_to_regex(root, refs) + re_Misc + "*$");
// std::cout << re << std::endl; // Mais oui c'est clair
return re;
}
return "^$";
}
std::string schema_to_regex(CompositeElement * s,
std::map<std::string, std::string> & refs)
{
std::string r;
for (auto c : s->content())
{
auto e = dynamic_cast<Element *>(c);
if (e != nullptr && e->name() == "xsd:element")
r += element_to_regex(e, refs) + "|";
}
r = r.substr(0, r.length() - 1);
return "(" + r + ")";
}
std::string element_to_regex(Element * e,
std::map<std::string, std::string> & refs)
{
auto it_name = std::find_if(e->attributes().begin(), e->attributes().end(),
[](Attribute * a) { return a->name() == "name"; });
if (it_name == e->attributes().end())
{
auto it_ref = std::find_if(e->attributes().begin(), e->attributes().end(),
[](Attribute * a) { return a->name() == "ref"; });
if (it_ref == e->attributes().end())
return "";
auto ref = (*it_ref)->value();
auto r = refs.find(ref);
if (r == refs.end())
return "";
return r->second;
}
auto name = (*it_name)->value();
const std::string begin("<" + name + "(" + re_S + re_Attr + ")*" + re_blank + ">");
const std::string end("</" + name + re_blank + ">");
auto ce = dynamic_cast<CompositeElement *>(e);
if (ce != nullptr)
{
CompositeElement * cce = nullptr;
if (ce->content().size() >= 1
&& (cce = dynamic_cast<CompositeElement *>(ce->content().front())) != nullptr
&& cce->begin_tag() == "xsd:complexType")
{
std::string r(begin + complexe_type_to_regex(cce, refs) + end);
refs[name] = r;
return r;
}
}
else
{
std::string r( begin + simple_element_to_regex(e, refs) + end);
refs[name] = r;
return r;
}
return "";
}
std::string simple_element_to_regex(Element * e,
std::map<std::string, std::string> &)
{
auto it_type = std::find_if(e->attributes().begin(), e->attributes().end(),
[](Attribute * a) { return a->name() == "type"; });
if (it_type == e->attributes().end())
return "";
auto type = (*it_type)->value();
if (type == "xsd:string")
return re_string;
else if (type == "xsd:date")
return re_date;
return "";
}
std::string complexe_type_to_regex(CompositeElement * e,
std::map<std::string, std::string> & refs)
{
if (e->content().size() < 1)
return "";
CompositeElement * ce = dynamic_cast<CompositeElement *>(e->content().front());
if (ce == nullptr)
return "";
bool mixed = false;
auto it_mixed = std::find_if(e->attributes().begin(), e->attributes().end(),
[](Attribute * a) { return a->name() == "mixed"; });
if (it_mixed != e->attributes().end()
&& (*it_mixed)->value() == "true")
mixed = true;
std::string s;
if (ce->begin_tag() == "xsd:choice")
{
if (mixed)
s += re_mixed;
s += choice_to_regex(ce, refs);
if (mixed)
s += re_mixed;
}
else if (ce->begin_tag() == "xsd:sequence")
{
s += sequence_to_regex(ce, refs, mixed);
}
return s;
}
std::string choice_to_regex(CompositeElement * e,
std::map<std::string, std::string> & refs)
{
std::string s;
for (auto c : e->content())
{
auto ce = dynamic_cast<Element *>(c);
if (ce)
{
s += element_to_regex(ce, refs);
if (c != e->content().back())
s += "|";
}
}
return re_blank + "(" + s + ")" + re_blank;
}
std::string sequence_to_regex(CompositeElement * e,
std::map<std::string, std::string> & refs, bool mixed)
{
std::string s;
std::string space = mixed ? re_mixed : re_blank;
for (auto c : e->content())
{
auto ce = dynamic_cast<Element *>(c);
if (ce)
{
auto it_maxOccurs = std::find_if(ce->attributes().begin(),
ce->attributes().end(),
[](Attribute * a) { return a->name() == "maxOccurs"; });
std::string reg = element_to_regex(ce, refs) + space;
if (it_maxOccurs != ce->attributes().end())
{
int maxOccurs = atoi((*it_maxOccurs)->value().c_str());
for (int i(0); i < maxOccurs; i++) {
s += reg;
}
}
else
{
s += reg;
}
}
}
return space + s;
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2017 deipi.com LLC and contributors. All rights reserved.
*
* 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 "test_serialise_list.h"
#include "../src/serialise_list.h"
#include "utils.h"
inline int testing(const std::vector<std::string>& strs) {
auto serialised = StringList::serialise(strs.begin(), strs.end());
int cont = 0;
StringList s(serialised);
if (s.size() != strs.size()) {
L_ERR(nullptr, "StringList is not working. Size: %zu Expected: %zu", s.size(), strs.size());
++cont;
}
std::vector<std::string> res;
StringList::unserialise(serialised, std::back_inserter(res));
if (res.size() != strs.size()) {
L_ERR(nullptr, "StringList::unserialise is not working. Size: %zu Expected: %zu", res.size(), strs.size());
++cont;
}
auto it_s = s.begin();
auto it_r = res.begin();
for (const auto& elem : strs) {
if (*it_s != elem || *it_r != elem) {
L_ERR(nullptr, "StringList is not working. Result: [%s, %s] Expected: %s", it_s->c_str(), it_r->c_str(), elem.c_str());
++cont;
}
++it_s;
++it_r;
}
return cont;
}
inline int testing(const std::vector<Cartesian>& ptos) {
auto serialised = CartesianList::serialise(ptos.begin(), ptos.end());
int cont = 0;
CartesianList s(serialised);
if (s.size() != ptos.size()) {
L_ERR(nullptr, "CartesianList is not working. Size: %zu Expected: %zu", s.size(), ptos.size());
++cont;
}
std::vector<Cartesian> res;
CartesianList::unserialise(serialised, std::back_inserter(res));
if (res.size() != ptos.size()) {
L_ERR(nullptr, "CartesianList::unserialise is not working. Size: %zu Expected: %zu", res.size(), ptos.size());
++cont;
}
auto it_s = s.begin();
auto it_r = res.begin();
for (const auto& elem : ptos) {
if (*it_s != elem || *it_r != elem) {
L_ERR(nullptr, "CartesianList is not working. Result: [%s, %s] Expected: %s", it_s->to_string().c_str(), it_r->to_string().c_str(), elem.to_string().c_str());
++cont;
}
++it_s;
++it_r;
}
return cont;
}
inline int testing(const std::vector<range_t>& ranges) {
auto serialised = RangeList::serialise(ranges.begin(), ranges.end());
int cont = 0;
RangeList s(serialised);
if (s.size() != ranges.size()) {
L_ERR(nullptr, "RangeList is not working. Size: %zu Expected: %zu", s.size(), ranges.size());
++cont;
}
std::vector<range_t> res;
RangeList::unserialise(serialised, std::back_inserter(res));
if (res.size() != ranges.size()) {
L_ERR(nullptr, "RangeList::unserialise is not working. Size: %zu Expected: %zu", res.size(), ranges.size());
++cont;
}
auto it_s = s.begin();
auto it_r = res.begin();
for (const auto& elem : ranges) {
if (*it_s != elem || *it_r != elem) {
L_ERR(nullptr, "RangeList is not working. Result: [%s, %s] Expected: %s", it_s->to_string().c_str(), it_r->to_string().c_str(), elem.to_string().c_str());
++cont;
}
++it_s;
++it_r;
}
return cont;
}
int test_StringList() {
std::vector<std::string> strs;
int cont = testing(strs);
strs.emplace_back("a");
cont += testing(strs);
strs.emplace_back("b");
strs.emplace_back("c");
strs.emplace_back("d");
strs.emplace_back("e");
strs.emplace_back("f");
strs.emplace_back("g");
strs.emplace_back("h");
strs.emplace_back("i");
strs.emplace_back("j");
cont += testing(strs);
RETURN(cont);
}
int test_CartesianList() {
std::vector<Cartesian> ptos;
int cont = testing(ptos);
ptos.emplace_back(-1, 0, 0);
cont += testing(ptos);
ptos.emplace_back(0.267261, 0.534522, 0.801784);
ptos.emplace_back(0.455842, 0.569803, 0.683763);
ptos.emplace_back(0.502571, 0.574367, 0.646162);
ptos.emplace_back(0.523424, 0.575766, 0.628109);
ptos.emplace_back(-0.267261, 0.534522, 0.801784);
ptos.emplace_back(0.455842, -0.569803, 0.683763);
ptos.emplace_back(0.502571, 0.574367, -0.646162);
ptos.emplace_back(-0.523424, -0.575766, -0.628109);
cont += testing(ptos);
RETURN(cont);
}
int test_RangeList() {
std::vector<range_t> ranges;
int cont = testing(ranges);
ranges.emplace_back(1, 10);
cont += testing(ranges);
ranges.emplace_back(20, 30);
ranges.emplace_back(40, 50);
ranges.emplace_back(60, 70);
ranges.emplace_back(80, 90);
ranges.emplace_back(100, 110);
ranges.emplace_back(120, 130);
ranges.emplace_back(140, 150);
cont += testing(ranges);
RETURN(cont);
}
<commit_msg>Serialise::range works for HTM with level 25<commit_after>/*
* Copyright (C) 2017 deipi.com LLC and contributors. All rights reserved.
*
* 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 "test_serialise_list.h"
#include "../src/serialise_list.h"
#include "utils.h"
inline int testing(const std::vector<std::string>& strs) {
auto serialised = StringList::serialise(strs.begin(), strs.end());
int cont = 0;
StringList s(serialised);
if (s.size() != strs.size()) {
L_ERR(nullptr, "StringList is not working. Size: %zu Expected: %zu", s.size(), strs.size());
++cont;
}
std::vector<std::string> res;
StringList::unserialise(serialised, std::back_inserter(res));
if (res.size() != strs.size()) {
L_ERR(nullptr, "StringList::unserialise is not working. Size: %zu Expected: %zu", res.size(), strs.size());
++cont;
}
auto it_s = s.begin();
auto it_r = res.begin();
for (const auto& elem : strs) {
if (*it_s != elem || *it_r != elem) {
L_ERR(nullptr, "StringList is not working. Result: [%s, %s] Expected: %s", it_s->c_str(), it_r->c_str(), elem.c_str());
++cont;
}
++it_s;
++it_r;
}
return cont;
}
inline int testing(const std::vector<Cartesian>& ptos) {
auto serialised = CartesianList::serialise(ptos.begin(), ptos.end());
int cont = 0;
CartesianList s(serialised);
if (s.size() != ptos.size()) {
L_ERR(nullptr, "CartesianList is not working. Size: %zu Expected: %zu", s.size(), ptos.size());
++cont;
}
std::vector<Cartesian> res;
CartesianList::unserialise(serialised, std::back_inserter(res));
if (res.size() != ptos.size()) {
L_ERR(nullptr, "CartesianList::unserialise is not working. Size: %zu Expected: %zu", res.size(), ptos.size());
++cont;
}
auto it_s = s.begin();
auto it_r = res.begin();
for (const auto& elem : ptos) {
if (*it_s != elem || *it_r != elem) {
L_ERR(nullptr, "CartesianList is not working. Result: [%s, %s] Expected: %s", it_s->to_string().c_str(), it_r->to_string().c_str(), elem.to_string().c_str());
++cont;
}
++it_s;
++it_r;
}
return cont;
}
inline int testing(const std::vector<range_t>& ranges) {
auto serialised = RangeList::serialise(ranges.begin(), ranges.end());
int cont = 0;
RangeList s(serialised);
if (s.size() != ranges.size()) {
L_ERR(nullptr, "RangeList is not working. Size: %zu Expected: %zu", s.size(), ranges.size());
++cont;
}
std::vector<range_t> res;
RangeList::unserialise(serialised, std::back_inserter(res));
if (res.size() != ranges.size()) {
L_ERR(nullptr, "RangeList::unserialise is not working. Size: %zu Expected: %zu", res.size(), ranges.size());
++cont;
}
auto it_s = s.begin();
auto it_r = res.begin();
for (const auto& elem : ranges) {
if (*it_s != elem || *it_r != elem) {
L_ERR(nullptr, "RangeList is not working. Result: [%s, %s] Expected: %s", it_s->to_string().c_str(), it_r->to_string().c_str(), elem.to_string().c_str());
++cont;
}
++it_s;
++it_r;
}
return cont;
}
int test_StringList() {
std::vector<std::string> strs;
int cont = testing(strs);
strs.emplace_back("a");
cont += testing(strs);
strs.emplace_back("b");
strs.emplace_back("c");
strs.emplace_back("d");
strs.emplace_back("e");
strs.emplace_back("f");
strs.emplace_back("g");
strs.emplace_back("h");
strs.emplace_back("i");
strs.emplace_back("j");
cont += testing(strs);
RETURN(cont);
}
int test_CartesianList() {
std::vector<Cartesian> ptos;
int cont = testing(ptos);
ptos.emplace_back(-1, 0, 0);
cont += testing(ptos);
ptos.emplace_back(0.267261, 0.534522, 0.801784);
ptos.emplace_back(0.455842, 0.569803, 0.683763);
ptos.emplace_back(0.502571, 0.574367, 0.646162);
ptos.emplace_back(0.523424, 0.575766, 0.628109);
ptos.emplace_back(-0.267261, 0.534522, 0.801784);
ptos.emplace_back(0.455842, -0.569803, 0.683763);
ptos.emplace_back(0.502571, 0.574367, -0.646162);
ptos.emplace_back(-0.523424, -0.575766, -0.628109);
cont += testing(ptos);
RETURN(cont);
}
int test_RangeList() {
std::vector<range_t> ranges;
int cont = testing(ranges);
// Small level range.
ranges.emplace_back(14363263991021568, 14363298350759935);
cont += testing(ranges);
ranges.emplace_back(14363315530629120, 14363332710498303);
ranges.emplace_back(14363367070236672, 14363384250105855);
ranges.emplace_back(14363401429975040, 14363418609844223);
ranges.emplace_back(14363607588405248, 14363624768274431);
ranges.emplace_back(14363641948143616, 14363676307881983);
ranges.emplace_back(14363745027358720, 14363813746835455);
ranges.emplace_back(14363899646181376, 14363916826050559);
ranges.emplace_back(14363968365658112, 14364019905265663);
cont += testing(ranges);
RETURN(cont);
}
<|endoftext|> |
<commit_before>#include "sipclienttransaction.h"
#include "siptransactionuser.h"
#include <QDebug>
// 2 seconds for a SIP reply
const unsigned int TIMEOUT = 2000;
// 1 minute for the user to react
const unsigned int INVITE_TIMEOUT = 60000;
SIPClientTransaction::SIPClientTransaction():
ongoingTransactionType_(SIP_UNKNOWN_REQUEST),
connected_(false),
sessionID_(0),
state_(INACTIVE),
pendingRequest_(SIP_UNKNOWN_REQUEST),
transactionUser_(NULL)
{}
void SIPClientTransaction::init(SIPTransactionUser* tu, uint32_t sessionID)
{
Q_ASSERT(sessionID != 0);
Q_ASSERT(tu);
transactionUser_ = tu;
sessionID_ = sessionID;
requestTimer_.setSingleShot(true);
connect(&requestTimer_, SIGNAL(timeout()), this, SLOT(requestTimeOut()));
}
//processes incoming response
bool SIPClientTransaction::processResponse(SIPResponse &response)
{
Q_ASSERT(sessionID_ != 0);
Q_ASSERT(transactionUser_ != NULL);
qDebug() << "Client starts processing response";
if(!sessionID_ || transactionUser_ == NULL)
{
qWarning() << "WARNING: SIP Client Transaction not initialized.";
return true;
}
int responseCode = response.type;
if(responseCode >= 300 && responseCode <= 399)
{
// TODO: 8.1.3.4 Processing 3xx Responses in RFC 3261
qDebug() << "Got a redirection response Code. Not implemented!";
return false;
}
if(responseCode >= 400 && responseCode <= 499)
{
// TODO: 8.1.3.5 Processing 4xx Responses in RFC 3261
qDebug() << "Got a Client Failure Response Code. Not implemented!";
// TODO: if the response is 481 or 408, terminate dialog
return false;
}
if(responseCode >= 500 && responseCode <= 599)
{
qDebug() << "Got a Server Failure Response Code. Not implemented!";
return false;
}
if(ongoingTransactionType_ == INVITE)
{
if(responseCode >= 600 && responseCode <= 699)
{
qDebug() << "Got a Global Failure Response Code for INVITE";
transactionUser_->callRejected(sessionID_);
return false;
}
else
{
switch (response.type) {
case SIP_RINGING:
transactionUser_->callRinging(sessionID_);
break;
case SIP_OK:
// the sdp has been check by transaction layer before this.
requestSender(ACK);
transactionUser_->callNegotiated(sessionID_);
break;
default:
break;
}
}
}
if(responseCode >= 200)
{
ongoingTransactionType_ = SIP_UNKNOWN_REQUEST;
}
return true;
}
bool SIPClientTransaction::startCall()
{
qDebug() << "Starting a call and sending an INVITE in session";
Q_ASSERT(sessionID_ != 0);
if(!sessionID_)
{
qWarning() << "WARNING: SIP Client Transaction not initialized";
return false;
}
if(state_ == INACTIVE)
{
requestSender(INVITE);
}
else
{
qWarning() << "WARNING: Trying to start a call, when it is already running or negotiating:" << state_;
return false;
}
return true;
}
void SIPClientTransaction::endCall()
{
if(state_ != RUNNNING)
{
qDebug() << "WARNING: Trying to end a non-active call!";
return;
}
requestSender(BYE);
}
void SIPClientTransaction::registerToServer()
{
requestSender(REGISTER);
}
void SIPClientTransaction::connectionReady(bool ready)
{
connected_ = ready;
if(pendingRequest_ != SIP_UNKNOWN_REQUEST)
{
requestSender(pendingRequest_);
pendingRequest_ = SIP_UNKNOWN_REQUEST;
}
}
void SIPClientTransaction::getRequestMessageInfo(RequestType type,
std::shared_ptr<SIPMessageInfo>& outMessage)
{
outMessage = std::shared_ptr<SIPMessageInfo> (new SIPMessageInfo);
if(type == ACK)
{
outMessage->transactionRequest = INVITE;
}
else if(type == CANCEL)
{
outMessage->transactionRequest = ongoingTransactionType_;
}
else
{
outMessage->transactionRequest = type;
}
outMessage->dialog = NULL;
outMessage->maxForwards = 71;
outMessage->version = "2.0";
outMessage->cSeq = 0; // invalid, should be set in dialog
}
void SIPClientTransaction::requestSender(RequestType type)
{
if(!connected_)
{
qDebug() << "Added a pending request:" << type;
pendingRequest_ = type;
}
else
{
qDebug() << "Client starts sending a request:" << type;
ongoingTransactionType_ = type;
emit sendRequest(sessionID_, type);
if(type != INVITE)
{
qDebug() << "Request timeout set to: " << TIMEOUT;
requestTimer_.start(TIMEOUT);
}
else
{
qDebug() << "INVITE timeout set to: " << INVITE_TIMEOUT;
requestTimer_.start(INVITE_TIMEOUT);
}
}
}
void SIPClientTransaction::requestTimeOut()
{
qDebug() << "No response. Request timed out";
if(ongoingTransactionType_ == INVITE)
{
sendRequest(sessionID_, BYE);
// TODO tell user we have failed
}
requestSender(CANCEL);
transactionUser_->callRejected(sessionID_);
ongoingTransactionType_ = SIP_UNKNOWN_REQUEST;
}
<commit_msg>Fixed bunch of issues with timeout triggering too soon or needlessly.<commit_after>#include "sipclienttransaction.h"
#include "siptransactionuser.h"
#include <QDebug>
// 2 seconds for a SIP reply
const unsigned int TIMEOUT = 2000;
// 1 minute for the user to react
const unsigned int INVITE_TIMEOUT = 60000;
SIPClientTransaction::SIPClientTransaction():
ongoingTransactionType_(SIP_UNKNOWN_REQUEST),
connected_(false),
sessionID_(0),
state_(INACTIVE),
pendingRequest_(SIP_UNKNOWN_REQUEST),
transactionUser_(NULL)
{}
void SIPClientTransaction::init(SIPTransactionUser* tu, uint32_t sessionID)
{
Q_ASSERT(sessionID != 0);
Q_ASSERT(tu);
transactionUser_ = tu;
sessionID_ = sessionID;
requestTimer_.setSingleShot(true);
connect(&requestTimer_, SIGNAL(timeout()), this, SLOT(requestTimeOut()));
}
//processes incoming response
bool SIPClientTransaction::processResponse(SIPResponse &response)
{
Q_ASSERT(sessionID_ != 0);
Q_ASSERT(transactionUser_ != NULL);
qDebug() << "Client starts processing response";
if(!sessionID_ || transactionUser_ == NULL)
{
qWarning() << "WARNING: SIP Client Transaction not initialized.";
return true;
}
int responseCode = response.type;
if(responseCode >= 100 && responseCode <= 199)
{
qDebug() << "Got provisional response. Restarting timer.";
if(response.message->transactionRequest == INVITE)
{
requestTimer_.start(INVITE_TIMEOUT);
}
else
{
requestTimer_.start(TIMEOUT);
}
}
else
{
qDebug() << "Got response. Stopping timout.";
requestTimer_.stop();
}
if(responseCode >= 300 && responseCode <= 399)
{
// TODO: 8.1.3.4 Processing 3xx Responses in RFC 3261
qDebug() << "Got a redirection response Code. Not implemented!";
return false;
}
if(responseCode >= 400 && responseCode <= 499)
{
// TODO: 8.1.3.5 Processing 4xx Responses in RFC 3261
qDebug() << "Got a Client Failure Response Code. Not implemented!";
// TODO: if the response is 481 or 408, terminate dialog
return false;
}
if(responseCode >= 500 && responseCode <= 599)
{
qDebug() << "Got a Server Failure Response Code. Not implemented!";
return false;
}
if(ongoingTransactionType_ == INVITE)
{
if(responseCode >= 600 && responseCode <= 699)
{
qDebug() << "Got a Global Failure Response Code for INVITE";
transactionUser_->callRejected(sessionID_);
return false;
}
else
{
switch (response.type) {
case SIP_RINGING:
transactionUser_->callRinging(sessionID_);
break;
case SIP_OK:
// the sdp has been check by transaction layer before this.
requestSender(ACK);
transactionUser_->callNegotiated(sessionID_);
break;
default:
break;
}
}
}
if(responseCode >= 200)
{
ongoingTransactionType_ = SIP_UNKNOWN_REQUEST;
}
return true;
}
bool SIPClientTransaction::startCall()
{
qDebug() << "Starting a call and sending an INVITE in session";
Q_ASSERT(sessionID_ != 0);
if(!sessionID_)
{
qWarning() << "WARNING: SIP Client Transaction not initialized";
return false;
}
if(state_ == INACTIVE)
{
requestSender(INVITE);
}
else
{
qWarning() << "WARNING: Trying to start a call, when it is already running or negotiating:" << state_;
return false;
}
return true;
}
void SIPClientTransaction::endCall()
{
if(state_ != RUNNNING)
{
qDebug() << "WARNING: Trying to end a non-active call!";
return;
}
requestSender(BYE);
}
void SIPClientTransaction::registerToServer()
{
requestSender(REGISTER);
}
void SIPClientTransaction::connectionReady(bool ready)
{
connected_ = ready;
if(pendingRequest_ != SIP_UNKNOWN_REQUEST)
{
requestSender(pendingRequest_);
pendingRequest_ = SIP_UNKNOWN_REQUEST;
}
}
void SIPClientTransaction::getRequestMessageInfo(RequestType type,
std::shared_ptr<SIPMessageInfo>& outMessage)
{
outMessage = std::shared_ptr<SIPMessageInfo> (new SIPMessageInfo);
if(type == ACK)
{
outMessage->transactionRequest = INVITE;
}
else if(type == CANCEL)
{
outMessage->transactionRequest = ongoingTransactionType_;
}
else
{
outMessage->transactionRequest = type;
}
outMessage->dialog = NULL;
outMessage->maxForwards = 71;
outMessage->version = "2.0";
outMessage->cSeq = 0; // invalid, should be set in dialog
}
void SIPClientTransaction::requestSender(RequestType type)
{
if(!connected_)
{
qDebug() << "Added a pending request:" << type;
pendingRequest_ = type;
}
else
{
qDebug() << "Client starts sending a request:" << type;
ongoingTransactionType_ = type;
emit sendRequest(sessionID_, type);
if(type != INVITE && type != CANCEL && type != ACK)
{
qDebug() << "Request timeout set to: " << TIMEOUT;
requestTimer_.start(TIMEOUT);
}
else if(type == INVITE)
{
qDebug() << "INVITE timeout set to: " << INVITE_TIMEOUT;
requestTimer_.start(INVITE_TIMEOUT);
}
else
{
requestTimer_.stop();
}
}
}
void SIPClientTransaction::requestTimeOut()
{
qDebug() << "No response. Request timed out";
if(ongoingTransactionType_ == INVITE)
{
sendRequest(sessionID_, BYE);
// TODO tell user we have failed
}
requestSender(CANCEL);
requestTimer_.stop();
transactionUser_->callRejected(sessionID_);
ongoingTransactionType_ = SIP_UNKNOWN_REQUEST;
}
<|endoftext|> |
<commit_before>/*-------------------------------------------------------------------------
* Vulkan Conformance Tests
* ------------------------
*
* Copyright (c) 2016 The Khronos Group Inc.
* Copyright (c) 2016 Samsung Electronics Co., Ltd.
* Copyright (c) 2014 The Android Open Source Project
*
* 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.
*
*//*!
* \file
* \brief Compressed texture tests.
*//*--------------------------------------------------------------------*/
#include "vktTextureCompressedFormatTests.hpp"
#include "deString.h"
#include "deStringUtil.hpp"
#include "tcuCompressedTexture.hpp"
#include "tcuTexture.hpp"
#include "tcuTextureUtil.hpp"
#include "vkImageUtil.hpp"
#include "vktTestGroupUtil.hpp"
#include "vktTextureTestUtil.hpp"
#include <string>
#include <vector>
namespace vkt
{
namespace texture
{
namespace
{
using namespace vk;
using namespace glu::TextureTestUtil;
using namespace texture::util;
using std::string;
using std::vector;
using tcu::Sampler;
using tcu::TestLog;
struct Compressed2DTestParameters : public Texture2DTestCaseParameters
{
};
class Compressed2DTestInstance : public TestInstance
{
public:
typedef Compressed2DTestParameters ParameterType;
Compressed2DTestInstance (Context& context,
const ParameterType& testParameters);
tcu::TestStatus iterate (void);
private:
Compressed2DTestInstance (const Compressed2DTestInstance& other);
Compressed2DTestInstance& operator= (const Compressed2DTestInstance& other);
const ParameterType& m_testParameters;
const tcu::CompressedTexFormat m_compressedFormat;
TestTexture2DSp m_texture;
TextureRenderer m_renderer;
};
Compressed2DTestInstance::Compressed2DTestInstance (Context& context,
const ParameterType& testParameters)
: TestInstance (context)
, m_testParameters (testParameters)
, m_compressedFormat (mapVkCompressedFormat(testParameters.format))
, m_texture (TestTexture2DSp(new pipeline::TestTexture2D(m_compressedFormat, testParameters.width, testParameters.height)))
, m_renderer (context, testParameters.sampleCount, testParameters.width, testParameters.height)
{
m_renderer.add2DTexture(m_texture);
}
tcu::TestStatus Compressed2DTestInstance::iterate (void)
{
tcu::TestLog& log = m_context.getTestContext().getLog();
const pipeline::TestTexture2D& texture = m_renderer.get2DTexture(0);
const tcu::TextureFormat textureFormat = texture.getTextureFormat();
const tcu::TextureFormatInfo formatInfo = tcu::getTextureFormatInfo(textureFormat);
ReferenceParams sampleParams (TEXTURETYPE_2D);
tcu::Surface rendered (m_renderer.getRenderWidth(), m_renderer.getRenderHeight());
vector<float> texCoord;
// Setup params for reference.
sampleParams.sampler = util::createSampler(m_testParameters.wrapS, m_testParameters.wrapT, m_testParameters.minFilter, m_testParameters.magFilter);
sampleParams.samplerType = SAMPLERTYPE_FLOAT;
sampleParams.lodMode = LODMODE_EXACT;
sampleParams.colorBias = formatInfo.lookupBias;
sampleParams.colorScale = formatInfo.lookupScale;
log << TestLog::Message << "Compare reference value = " << sampleParams.ref << TestLog::EndMessage;
// Compute texture coordinates.
computeQuadTexCoord2D(texCoord, tcu::Vec2(0.0f, 0.0f), tcu::Vec2(1.0f, 1.0f));
m_renderer.renderQuad(rendered, 0, &texCoord[0], sampleParams);
// Compute reference.
const tcu::IVec4 formatBitDepth = getTextureFormatBitDepth(vk::mapVkFormat(VK_FORMAT_R8G8B8A8_UNORM));
const tcu::PixelFormat pixelFormat (formatBitDepth[0], formatBitDepth[1], formatBitDepth[2], formatBitDepth[3]);
tcu::Surface referenceFrame (m_renderer.getRenderWidth(), m_renderer.getRenderHeight());
sampleTexture(tcu::SurfaceAccess(referenceFrame, pixelFormat), m_texture->getTexture(), &texCoord[0], sampleParams);
// Compare and log.
const bool isOk = compareImages(log, referenceFrame, rendered, pixelFormat.getColorThreshold() + tcu::RGBA(1, 1, 1, 1));
return isOk ? tcu::TestStatus::pass("Pass") : tcu::TestStatus::fail("Image verification failed");
}
void populateTextureCompressedFormatTests (tcu::TestCaseGroup* compressedTextureTests)
{
tcu::TestContext& testCtx = compressedTextureTests->getTestContext();
// ETC2 and EAC compressed formats.
const struct {
const VkFormat format;
} etc2Formats[] =
{
{ VK_FORMAT_ETC2_R8G8B8_UNORM_BLOCK },
{ VK_FORMAT_ETC2_R8G8B8_SRGB_BLOCK },
{ VK_FORMAT_ETC2_R8G8B8A1_UNORM_BLOCK },
{ VK_FORMAT_ETC2_R8G8B8A1_SRGB_BLOCK },
{ VK_FORMAT_ETC2_R8G8B8A8_UNORM_BLOCK },
{ VK_FORMAT_ETC2_R8G8B8A8_SRGB_BLOCK },
{ VK_FORMAT_EAC_R11_UNORM_BLOCK },
{ VK_FORMAT_EAC_R11_SNORM_BLOCK },
{ VK_FORMAT_EAC_R11G11_UNORM_BLOCK },
{ VK_FORMAT_EAC_R11G11_SNORM_BLOCK },
};
const struct {
const int width;
const int height;
const char* name;
} sizes[] =
{
{ 128, 64, "pot" },
{ 51, 65, "npot" },
};
for (int sizeNdx = 0; sizeNdx < DE_LENGTH_OF_ARRAY(sizes); sizeNdx++)
for (int formatNdx = 0; formatNdx < DE_LENGTH_OF_ARRAY(etc2Formats); formatNdx++)
{
const string formatStr = de::toString(getFormatStr(etc2Formats[formatNdx].format));
const string nameBase = de::toLower(formatStr.substr(10));
Compressed2DTestParameters testParameters;
testParameters.format = etc2Formats[formatNdx].format;
testParameters.width = sizes[sizeNdx].width;
testParameters.height = sizes[sizeNdx].height;
testParameters.programs.push_back(PROGRAM_2D_FLOAT);
compressedTextureTests->addChild(new TextureTestCase<Compressed2DTestInstance>(testCtx, (nameBase + "_2d_" + sizes[sizeNdx].name).c_str(), (formatStr + ", TEXTURETYPE_2D").c_str(), testParameters));
}
}
} // anonymous
tcu::TestCaseGroup* createTextureCompressedFormatTests (tcu::TestContext& testCtx)
{
return createTestGroup(testCtx, "compressed", "Texture compressed format tests.", populateTextureCompressedFormatTests);
}
} // texture
} // vkt
<commit_msg>Properly initialize minFilter/magFilter when setting up test cases<commit_after>/*-------------------------------------------------------------------------
* Vulkan Conformance Tests
* ------------------------
*
* Copyright (c) 2016 The Khronos Group Inc.
* Copyright (c) 2016 Samsung Electronics Co., Ltd.
* Copyright (c) 2014 The Android Open Source Project
*
* 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.
*
*//*!
* \file
* \brief Compressed texture tests.
*//*--------------------------------------------------------------------*/
#include "vktTextureCompressedFormatTests.hpp"
#include "deString.h"
#include "deStringUtil.hpp"
#include "tcuCompressedTexture.hpp"
#include "tcuTexture.hpp"
#include "tcuTextureUtil.hpp"
#include "vkImageUtil.hpp"
#include "vktTestGroupUtil.hpp"
#include "vktTextureTestUtil.hpp"
#include <string>
#include <vector>
namespace vkt
{
namespace texture
{
namespace
{
using namespace vk;
using namespace glu::TextureTestUtil;
using namespace texture::util;
using std::string;
using std::vector;
using tcu::Sampler;
using tcu::TestLog;
struct Compressed2DTestParameters : public Texture2DTestCaseParameters
{
};
class Compressed2DTestInstance : public TestInstance
{
public:
typedef Compressed2DTestParameters ParameterType;
Compressed2DTestInstance (Context& context,
const ParameterType& testParameters);
tcu::TestStatus iterate (void);
private:
Compressed2DTestInstance (const Compressed2DTestInstance& other);
Compressed2DTestInstance& operator= (const Compressed2DTestInstance& other);
const ParameterType& m_testParameters;
const tcu::CompressedTexFormat m_compressedFormat;
TestTexture2DSp m_texture;
TextureRenderer m_renderer;
};
Compressed2DTestInstance::Compressed2DTestInstance (Context& context,
const ParameterType& testParameters)
: TestInstance (context)
, m_testParameters (testParameters)
, m_compressedFormat (mapVkCompressedFormat(testParameters.format))
, m_texture (TestTexture2DSp(new pipeline::TestTexture2D(m_compressedFormat, testParameters.width, testParameters.height)))
, m_renderer (context, testParameters.sampleCount, testParameters.width, testParameters.height)
{
m_renderer.add2DTexture(m_texture);
}
tcu::TestStatus Compressed2DTestInstance::iterate (void)
{
tcu::TestLog& log = m_context.getTestContext().getLog();
const pipeline::TestTexture2D& texture = m_renderer.get2DTexture(0);
const tcu::TextureFormat textureFormat = texture.getTextureFormat();
const tcu::TextureFormatInfo formatInfo = tcu::getTextureFormatInfo(textureFormat);
ReferenceParams sampleParams (TEXTURETYPE_2D);
tcu::Surface rendered (m_renderer.getRenderWidth(), m_renderer.getRenderHeight());
vector<float> texCoord;
// Setup params for reference.
sampleParams.sampler = util::createSampler(m_testParameters.wrapS, m_testParameters.wrapT, m_testParameters.minFilter, m_testParameters.magFilter);
sampleParams.samplerType = SAMPLERTYPE_FLOAT;
sampleParams.lodMode = LODMODE_EXACT;
sampleParams.colorBias = formatInfo.lookupBias;
sampleParams.colorScale = formatInfo.lookupScale;
log << TestLog::Message << "Compare reference value = " << sampleParams.ref << TestLog::EndMessage;
// Compute texture coordinates.
computeQuadTexCoord2D(texCoord, tcu::Vec2(0.0f, 0.0f), tcu::Vec2(1.0f, 1.0f));
m_renderer.renderQuad(rendered, 0, &texCoord[0], sampleParams);
// Compute reference.
const tcu::IVec4 formatBitDepth = getTextureFormatBitDepth(vk::mapVkFormat(VK_FORMAT_R8G8B8A8_UNORM));
const tcu::PixelFormat pixelFormat (formatBitDepth[0], formatBitDepth[1], formatBitDepth[2], formatBitDepth[3]);
tcu::Surface referenceFrame (m_renderer.getRenderWidth(), m_renderer.getRenderHeight());
sampleTexture(tcu::SurfaceAccess(referenceFrame, pixelFormat), m_texture->getTexture(), &texCoord[0], sampleParams);
// Compare and log.
const bool isOk = compareImages(log, referenceFrame, rendered, pixelFormat.getColorThreshold() + tcu::RGBA(1, 1, 1, 1));
return isOk ? tcu::TestStatus::pass("Pass") : tcu::TestStatus::fail("Image verification failed");
}
void populateTextureCompressedFormatTests (tcu::TestCaseGroup* compressedTextureTests)
{
tcu::TestContext& testCtx = compressedTextureTests->getTestContext();
// ETC2 and EAC compressed formats.
const struct {
const VkFormat format;
} etc2Formats[] =
{
{ VK_FORMAT_ETC2_R8G8B8_UNORM_BLOCK },
{ VK_FORMAT_ETC2_R8G8B8_SRGB_BLOCK },
{ VK_FORMAT_ETC2_R8G8B8A1_UNORM_BLOCK },
{ VK_FORMAT_ETC2_R8G8B8A1_SRGB_BLOCK },
{ VK_FORMAT_ETC2_R8G8B8A8_UNORM_BLOCK },
{ VK_FORMAT_ETC2_R8G8B8A8_SRGB_BLOCK },
{ VK_FORMAT_EAC_R11_UNORM_BLOCK },
{ VK_FORMAT_EAC_R11_SNORM_BLOCK },
{ VK_FORMAT_EAC_R11G11_UNORM_BLOCK },
{ VK_FORMAT_EAC_R11G11_SNORM_BLOCK },
};
const struct {
const int width;
const int height;
const char* name;
} sizes[] =
{
{ 128, 64, "pot" },
{ 51, 65, "npot" },
};
for (int sizeNdx = 0; sizeNdx < DE_LENGTH_OF_ARRAY(sizes); sizeNdx++)
for (int formatNdx = 0; formatNdx < DE_LENGTH_OF_ARRAY(etc2Formats); formatNdx++)
{
const string formatStr = de::toString(getFormatStr(etc2Formats[formatNdx].format));
const string nameBase = de::toLower(formatStr.substr(10));
Compressed2DTestParameters testParameters;
testParameters.format = etc2Formats[formatNdx].format;
testParameters.width = sizes[sizeNdx].width;
testParameters.height = sizes[sizeNdx].height;
testParameters.minFilter = tcu::Sampler::NEAREST;
testParameters.magFilter = tcu::Sampler::NEAREST;
testParameters.programs.push_back(PROGRAM_2D_FLOAT);
compressedTextureTests->addChild(new TextureTestCase<Compressed2DTestInstance>(testCtx, (nameBase + "_2d_" + sizes[sizeNdx].name).c_str(), (formatStr + ", TEXTURETYPE_2D").c_str(), testParameters));
}
}
} // anonymous
tcu::TestCaseGroup* createTextureCompressedFormatTests (tcu::TestContext& testCtx)
{
return createTestGroup(testCtx, "compressed", "Texture compressed format tests.", populateTextureCompressedFormatTests);
}
} // texture
} // vkt
<|endoftext|> |
<commit_before>static void
show_type(Vec<CreationSet *> &t, FILE *fp) {
fprintf(fp, "( ");
forv_CreationSet(cs, t) if (cs) {
if (cs->sym->name)
fprintf(fp, "%s ", cs->sym->name);
else if (cs->sym->constant)
fprintf(fp, "\"%s\" ", cs->sym->constant);
else
fprintf(fp, "%d ", cs->sym->id);
}
fprintf(fp, ") ");
}
static void
show_sym(Sym *s, FILE *fp) {
if (s->is_pattern) {
fprintf(fp, "( ");
forv_Sym(ss, s->has) {
if (ss != s->has.v[0])
fprintf(fp, ", ");
show_sym(ss, fp);
}
fprintf(fp, ") ");
} else if (s->name)
fprintf(fp, "%s ", s->name);
else if (s->constant)
fprintf(fp, "\"%s\" ", s->constant);
if (s->type && s->type->name)
fprintf(fp, "= %s", s->type->name);
else if (s->must_implement &&
s->must_implement == s->must_specialize)
fprintf(fp, ": %s", s->must_implement->name);
else if (s->must_implement)
fprintf(fp, "< %s", s->must_implement->name);
else if (s->must_specialize)
fprintf(fp, "@ %s", s->must_specialize->name);
}
static void
show_fun(Fun *f, FILE *fp) {
fprintf(fp, "%s:%d: ", f->filename(), f->line());
forv_Sym(s, f->sym->has)
show_sym(s, fp);
}
void
fa_print_backward(AVar *v, FILE *fp) {
Vec<AVar *> done, todo;
todo.add(v);
done.set_add(v);
for (int i = 0; i < todo.n; i++) {
v = todo.v[i];
if (v->var) {
if (v->var->sym) {
if (v->var->sym->name)
fprintf(fp, "%s %d\n", v->var->sym->name, v->var->sym->id);
else
fprintf(fp, "%d\n", v->var->sym->id);
} else
fprintf(fp, "VAR %p\n", v->var);
} else
fprintf(fp, "AVAR %p\n", v);
show_type(*v->out, fp); fprintf(fp, "\n");
forv_AVar(vv, v->backward) if (vv) {
if (!done.set_in(vv)) {
todo.add(vv);
done.set_add(vv);
}
}
}
}
void
fa_dump_var_types(AVar *av, FILE *fp, int verbose = verbose_level) {
Var *v = av->var;
if (verbose < 2 && (!v->sym->name || v->sym->is_symbol))
return;
if (!v->sym->in)
fprintf(fp, "::");
else if (v->sym->in->name)
fprintf(fp, "%s::", v->sym->in->name);
else
fprintf(fp, "%d::", v->sym->in->id);
if (v->sym->name)
fprintf(fp, "%s(%d) ", v->sym->name, v->sym->id);
else
fprintf(fp, "(%d) ", v->sym->id);
if (v->sym->constant)
fprintf(fp, "\"%s\" ", v->sym->constant);
else {
fprintf(fp, "\"");
print(fp, v->sym->imm, v->sym->type);
fprintf(fp, "\" ");
}
show_type(*av->out, fp);
fprintf(fp, "\n");
}
void
fa_dump_types(FA *fa, FILE *fp) {
Vec<Var *> gvars;
forv_Fun(f, fa->funs) {
forv_EntrySet(es, f->ess) {
if (f->sym->name)
fprintf(fp, "function %s (%d) ", f->sym->name, f->sym->id);
else
fprintf(fp, "function %d ", f->sym->id);
fprintf(fp, "entry set with %d edges\n", es->edges.count());
Vec<Var *> vars;
f->collect_Vars(vars);
forv_Var(v, vars) {
if (v->sym->global_scope) {
gvars.set_add(v);
continue;
}
fa_dump_var_types(make_AVar(v, es), fp);
}
}
}
gvars.set_to_vec();
fprintf(fp, "globals\n");
forv_Var(v, gvars)
if (!v->sym->is_constant && !v->sym->is_symbol)
fa_dump_var_types(unique_AVar(v, GLOBAL_CONTOUR), fp);
}
static void
show_illegal_type(FILE *fp, ATypeViolation *v) {
AVar *av = v->av;
if (av->var->sym->name)
fprintf(stderr, "'%s' ", av->var->sym->name);
else if (verbose_level)
fprintf(stderr, "expr:%d ", av->var->sym->id);
else
fprintf(stderr, "expression ");
if (verbose_level) {
fprintf(stderr, "id:%d ", av->var->sym->id);
if (av->out->n) {
fprintf(stderr, ": ");
show_type(*av->out, fp);
}
}
fprintf(stderr, "illegal: ");
show_type(*v->type, fp);
fprintf(stderr, "\n");
}
static void
show_call_tree(FILE *fp, PNode *p, EntrySet *es, int depth = 0) {
depth++;
if (depth > print_call_depth || !p->code)
return;
if (depth > 1 && p->code->filename()) {
for (int x = 0; x < depth; x++)
fprintf(stderr, " ");
fprintf(stderr, "called from %s:%d\n", p->code->filename(), p->code->line());
}
AEdge **last = es->edges.last();
for (AEdge **x = es->edges.first(); x < last; x++) if (*x)
show_call_tree(fp, (*x)->pnode, (*x)->from, depth);
}
static void
show_call_tree(FILE *fp, AVar *av) {
EntrySet *es = (EntrySet*)av->contour;
AEdge **last = es->edges.last();
for (AEdge **x = es->edges.first(); x < last; x++) if (*x)
show_call_tree(fp, (*x)->pnode, (*x)->from, 1);
}
static int
compar_tv_pos(const void *aa, const void *bb) {
ATypeViolation *a = (*(ATypeViolation**)aa);
ATypeViolation *b = (*(ATypeViolation**)bb);
AST *aast = a->send ? a->send->var->def->code->ast : 0;
if (!aast) aast = a->av->var->sym->ast;
AST *bast = b->send ? b->send->var->def->code->ast : 0;
if (!bast) bast = b->av->var->sym->ast;
if (!aast || !bast) {
if (bast) return -1;
if (aast) return 1;
return 0;
}
if (!aast->pathname() || !bast->pathname()) {
if (bast->pathname()) return -1;
if (aast->pathname()) return 1;
} else {
int x = strcmp(aast->pathname(), bast->pathname());
if (x) return x;
}
int i = aast->line();
int j = bast->line();
return (i > j) ? 1 : ((i < j) ? -1 : 0);
}
static void
show_violations(FA *fa, FILE *fp) {
Vec<ATypeViolation *> vv;
forv_ATypeViolation(v, type_violations) if (v)
vv.add(v);
qsort(vv.v, vv.n, sizeof(vv.v[0]), compar_tv_pos);
forv_ATypeViolation(v, vv) if (v) {
if (!verbose_level && !v->av->var->sym->name)
continue;
if (v->send)
fprintf(stderr, "%s:%d: ", v->send->var->def->code->filename(),
v->send->var->def->code->line());
else if (v->av->var->sym->ast)
fprintf(stderr, "%s:%d: ", v->av->var->sym->filename(),
v->av->var->sym->line());
else
fprintf(stderr, "error: ");
switch (v->kind) {
default: assert(0);
case ATypeViolation_PRIMITIVE_ARGUMENT:
fprintf(stderr, "illegal primitive argument type ");
show_illegal_type(fp, v);
break;
case ATypeViolation_SEND_ARGUMENT:
if (v->av->var->sym->is_symbol &&
v->send->var->def->rvals.v[0] == v->av->var)
fprintf(stderr, "unresolved call '%s'\n", v->av->var->sym->name);
else {
fprintf(stderr, "illegal call argument type ");
show_illegal_type(fp, v);
}
break;
case ATypeViolation_DISPATCH_AMBIGUITY:
fprintf(stderr, "ambiguous call '%s'\n", v->av->var->sym->name);
fprintf(stderr, " candidate functions:\n");
forv_Fun(f, *v->funs) {
fprintf(stderr, " ");
show_fun(f, stderr);
fprintf(stderr, "\n");
}
break;
case ATypeViolation_MEMBER:
if (v->av->out->n == 1)
fprintf(stderr, "unresolved member '%s'", v->av->out->v[0]->sym->name);
else {
fprintf(stderr, "unresolved member\n");
forv_CreationSet(selector, *v->av->out)
fprintf(stderr, " selector '%s'\n", selector->sym->name);
}
if (v->type->n == 1)
fprintf(stderr, " class '%s'\n", v->type->v[0]->sym->name ? v->type->v[0]->sym->name :
"<anonymous>");
else {
fprintf(stderr, " classes\n");
forv_CreationSet(cs, *v->type)
fprintf(stderr, " class '%s'\n", cs->sym->name);
}
break;
case ATypeViolation_MATCH:
if (v->type->n == 1)
fprintf(stderr, "near '%s' unmatched type '%s'\n",
v->av->var->sym->name ? v->av->var->sym->name : "<anonymous>",
v->type->v[0]->sym->name);
else {
fprintf(stderr, "near '%s' unmatched type\n");
forv_CreationSet(cs, *v->type)
fprintf(stderr, " type '%s'\n", cs->sym->name);
}
break;
case ATypeViolation_NOTYPE:
if (v->av->var->sym->name)
fprintf(stderr, "'%s' ", v->av->var->sym->name);
else
fprintf(stderr, "expression ");
fprintf(stderr, "has no type\n");
break;
}
if (v->send)
show_call_tree(fp, v->send->var->def, (EntrySet*)v->send->contour);
else if (v->av->contour_is_entry_set)
show_call_tree(fp, v->av);
}
}
static char *fn(char *s) {
if (!s)
return "<none>";
char *filename = strrchr(s, '/');
if (filename)
return filename + 1;
return s;
}
void
log_var_types(Var *v, Fun *f) {
if (!v->sym->name || v->sym->is_symbol)
return;
if (!v->sym->in)
log(LOG_TEST_FA, "::");
else if (v->sym->in->name)
log(LOG_TEST_FA, "%s::", v->sym->in->name);
else
log(LOG_TEST_FA, "%d::", v->sym->in->id);
if (v->sym->name)
log(LOG_TEST_FA, "%s(%s:%d) ", v->sym->name, fn(v->sym->filename()), v->sym->line());
else
log(LOG_TEST_FA, "(%s:%d) ", fn(v->sym->filename()), v->sym->line());
Vec<CreationSet *> css;
for (int i = 0; i < v->avars.n; i++) if (v->avars.v[i].key) {
AVar *av = v->avars.v[i].value;
if (!f || f->ess.in(((EntrySet*)av->contour)))
css.set_union(*av->out);
}
assert(css.n);
log(LOG_TEST_FA, "( ");
Vec<Sym *> syms;
forv_CreationSet(cs, css) if (cs)
syms.set_add(cs->sym);
syms.set_to_vec();
qsort(syms.v, syms.n, sizeof(syms.v[0]), compar_syms);
forv_Sym(s, syms) {
if (s->name)
log(LOG_TEST_FA, "%s ", s->name);
else if (s->constant)
log(LOG_TEST_FA, "\"%s\" ", s->constant);
log(LOG_TEST_FA, "(%s:%d) ", fn(s->filename()), s->line());
}
log(LOG_TEST_FA, ")\n");
}
<commit_msg>SEGV in debug output of some constants<commit_after>static void
show_type(Vec<CreationSet *> &t, FILE *fp) {
fprintf(fp, "( ");
forv_CreationSet(cs, t) if (cs) {
if (cs->sym->name)
fprintf(fp, "%s ", cs->sym->name);
else if (cs->sym->constant)
fprintf(fp, "\"%s\" ", cs->sym->constant);
else
fprintf(fp, "%d ", cs->sym->id);
}
fprintf(fp, ") ");
}
static void
show_sym(Sym *s, FILE *fp) {
if (s->is_pattern) {
fprintf(fp, "( ");
forv_Sym(ss, s->has) {
if (ss != s->has.v[0])
fprintf(fp, ", ");
show_sym(ss, fp);
}
fprintf(fp, ") ");
} else if (s->name)
fprintf(fp, "%s ", s->name);
else if (s->constant)
fprintf(fp, "\"%s\" ", s->constant);
if (s->type && s->type->name)
fprintf(fp, "= %s", s->type->name);
else if (s->must_implement &&
s->must_implement == s->must_specialize)
fprintf(fp, ": %s", s->must_implement->name);
else if (s->must_implement)
fprintf(fp, "< %s", s->must_implement->name);
else if (s->must_specialize)
fprintf(fp, "@ %s", s->must_specialize->name);
}
static void
show_fun(Fun *f, FILE *fp) {
fprintf(fp, "%s:%d: ", f->filename(), f->line());
forv_Sym(s, f->sym->has)
show_sym(s, fp);
}
void
fa_print_backward(AVar *v, FILE *fp) {
Vec<AVar *> done, todo;
todo.add(v);
done.set_add(v);
for (int i = 0; i < todo.n; i++) {
v = todo.v[i];
if (v->var) {
if (v->var->sym) {
if (v->var->sym->name)
fprintf(fp, "%s %d\n", v->var->sym->name, v->var->sym->id);
else
fprintf(fp, "%d\n", v->var->sym->id);
} else
fprintf(fp, "VAR %p\n", v->var);
} else
fprintf(fp, "AVAR %p\n", v);
show_type(*v->out, fp); fprintf(fp, "\n");
forv_AVar(vv, v->backward) if (vv) {
if (!done.set_in(vv)) {
todo.add(vv);
done.set_add(vv);
}
}
}
}
void
fa_dump_var_types(AVar *av, FILE *fp, int verbose = verbose_level) {
Var *v = av->var;
if (verbose < 2 && (!v->sym->name || v->sym->is_symbol))
return;
if (!v->sym->in)
fprintf(fp, "::");
else if (v->sym->in->name)
fprintf(fp, "%s::", v->sym->in->name);
else
fprintf(fp, "%d::", v->sym->in->id);
if (v->sym->name)
fprintf(fp, "%s(%d) ", v->sym->name, v->sym->id);
else
fprintf(fp, "(%d) ", v->sym->id);
if (v->sym->is_constant) {
if (v->sym->constant)
fprintf(fp, "\"%s\" ", v->sym->constant);
else {
fprintf(fp, "\"");
print(fp, v->sym->imm, v->sym->type);
fprintf(fp, "\" ");
}
}
show_type(*av->out, fp);
fprintf(fp, "\n");
}
void
fa_dump_types(FA *fa, FILE *fp) {
Vec<Var *> gvars;
forv_Fun(f, fa->funs) {
forv_EntrySet(es, f->ess) {
if (f->sym->name)
fprintf(fp, "function %s (%d) ", f->sym->name, f->sym->id);
else
fprintf(fp, "function %d ", f->sym->id);
fprintf(fp, "entry set with %d edges\n", es->edges.count());
Vec<Var *> vars;
f->collect_Vars(vars);
forv_Var(v, vars) {
if (v->sym->global_scope) {
gvars.set_add(v);
continue;
}
fa_dump_var_types(make_AVar(v, es), fp);
}
}
}
gvars.set_to_vec();
fprintf(fp, "globals\n");
forv_Var(v, gvars)
if (!v->sym->is_constant && !v->sym->is_symbol)
fa_dump_var_types(unique_AVar(v, GLOBAL_CONTOUR), fp);
}
static void
show_illegal_type(FILE *fp, ATypeViolation *v) {
AVar *av = v->av;
if (av->var->sym->name)
fprintf(stderr, "'%s' ", av->var->sym->name);
else if (verbose_level)
fprintf(stderr, "expr:%d ", av->var->sym->id);
else
fprintf(stderr, "expression ");
if (verbose_level) {
fprintf(stderr, "id:%d ", av->var->sym->id);
if (av->out->n) {
fprintf(stderr, ": ");
show_type(*av->out, fp);
}
}
fprintf(stderr, "illegal: ");
show_type(*v->type, fp);
fprintf(stderr, "\n");
}
static void
show_call_tree(FILE *fp, PNode *p, EntrySet *es, int depth = 0) {
depth++;
if (depth > print_call_depth || !p->code)
return;
if (depth > 1 && p->code->filename()) {
for (int x = 0; x < depth; x++)
fprintf(stderr, " ");
fprintf(stderr, "called from %s:%d\n", p->code->filename(), p->code->line());
}
AEdge **last = es->edges.last();
for (AEdge **x = es->edges.first(); x < last; x++) if (*x)
show_call_tree(fp, (*x)->pnode, (*x)->from, depth);
}
static void
show_call_tree(FILE *fp, AVar *av) {
EntrySet *es = (EntrySet*)av->contour;
AEdge **last = es->edges.last();
for (AEdge **x = es->edges.first(); x < last; x++) if (*x)
show_call_tree(fp, (*x)->pnode, (*x)->from, 1);
}
static int
compar_tv_pos(const void *aa, const void *bb) {
ATypeViolation *a = (*(ATypeViolation**)aa);
ATypeViolation *b = (*(ATypeViolation**)bb);
AST *aast = a->send ? a->send->var->def->code->ast : 0;
if (!aast) aast = a->av->var->sym->ast;
AST *bast = b->send ? b->send->var->def->code->ast : 0;
if (!bast) bast = b->av->var->sym->ast;
if (!aast || !bast) {
if (bast) return -1;
if (aast) return 1;
return 0;
}
if (!aast->pathname() || !bast->pathname()) {
if (bast->pathname()) return -1;
if (aast->pathname()) return 1;
} else {
int x = strcmp(aast->pathname(), bast->pathname());
if (x) return x;
}
int i = aast->line();
int j = bast->line();
return (i > j) ? 1 : ((i < j) ? -1 : 0);
}
static void
show_violations(FA *fa, FILE *fp) {
Vec<ATypeViolation *> vv;
forv_ATypeViolation(v, type_violations) if (v)
vv.add(v);
qsort(vv.v, vv.n, sizeof(vv.v[0]), compar_tv_pos);
forv_ATypeViolation(v, vv) if (v) {
if (!verbose_level && !v->av->var->sym->name)
continue;
if (v->send)
fprintf(stderr, "%s:%d: ", v->send->var->def->code->filename(),
v->send->var->def->code->line());
else if (v->av->var->sym->ast)
fprintf(stderr, "%s:%d: ", v->av->var->sym->filename(),
v->av->var->sym->line());
else
fprintf(stderr, "error: ");
switch (v->kind) {
default: assert(0);
case ATypeViolation_PRIMITIVE_ARGUMENT:
fprintf(stderr, "illegal primitive argument type ");
show_illegal_type(fp, v);
break;
case ATypeViolation_SEND_ARGUMENT:
if (v->av->var->sym->is_symbol &&
v->send->var->def->rvals.v[0] == v->av->var)
fprintf(stderr, "unresolved call '%s'\n", v->av->var->sym->name);
else {
fprintf(stderr, "illegal call argument type ");
show_illegal_type(fp, v);
}
break;
case ATypeViolation_DISPATCH_AMBIGUITY:
fprintf(stderr, "ambiguous call '%s'\n", v->av->var->sym->name);
fprintf(stderr, " candidate functions:\n");
forv_Fun(f, *v->funs) {
fprintf(stderr, " ");
show_fun(f, stderr);
fprintf(stderr, "\n");
}
break;
case ATypeViolation_MEMBER:
if (v->av->out->n == 1)
fprintf(stderr, "unresolved member '%s'", v->av->out->v[0]->sym->name);
else {
fprintf(stderr, "unresolved member\n");
forv_CreationSet(selector, *v->av->out)
fprintf(stderr, " selector '%s'\n", selector->sym->name);
}
if (v->type->n == 1)
fprintf(stderr, " class '%s'\n", v->type->v[0]->sym->name ? v->type->v[0]->sym->name :
"<anonymous>");
else {
fprintf(stderr, " classes\n");
forv_CreationSet(cs, *v->type)
fprintf(stderr, " class '%s'\n", cs->sym->name);
}
break;
case ATypeViolation_MATCH:
if (v->type->n == 1)
fprintf(stderr, "near '%s' unmatched type '%s'\n",
v->av->var->sym->name ? v->av->var->sym->name : "<anonymous>",
v->type->v[0]->sym->name);
else {
fprintf(stderr, "near '%s' unmatched type\n");
forv_CreationSet(cs, *v->type)
fprintf(stderr, " type '%s'\n", cs->sym->name);
}
break;
case ATypeViolation_NOTYPE:
if (v->av->var->sym->name)
fprintf(stderr, "'%s' ", v->av->var->sym->name);
else
fprintf(stderr, "expression ");
fprintf(stderr, "has no type\n");
break;
}
if (v->send)
show_call_tree(fp, v->send->var->def, (EntrySet*)v->send->contour);
else if (v->av->contour_is_entry_set)
show_call_tree(fp, v->av);
}
}
static char *fn(char *s) {
if (!s)
return "<none>";
char *filename = strrchr(s, '/');
if (filename)
return filename + 1;
return s;
}
void
log_var_types(Var *v, Fun *f) {
if (!v->sym->name || v->sym->is_symbol)
return;
if (!v->sym->in)
log(LOG_TEST_FA, "::");
else if (v->sym->in->name)
log(LOG_TEST_FA, "%s::", v->sym->in->name);
else
log(LOG_TEST_FA, "%d::", v->sym->in->id);
if (v->sym->name)
log(LOG_TEST_FA, "%s(%s:%d) ", v->sym->name, fn(v->sym->filename()), v->sym->line());
else
log(LOG_TEST_FA, "(%s:%d) ", fn(v->sym->filename()), v->sym->line());
Vec<CreationSet *> css;
for (int i = 0; i < v->avars.n; i++) if (v->avars.v[i].key) {
AVar *av = v->avars.v[i].value;
if (!f || f->ess.in(((EntrySet*)av->contour)))
css.set_union(*av->out);
}
assert(css.n);
log(LOG_TEST_FA, "( ");
Vec<Sym *> syms;
forv_CreationSet(cs, css) if (cs)
syms.set_add(cs->sym);
syms.set_to_vec();
qsort(syms.v, syms.n, sizeof(syms.v[0]), compar_syms);
forv_Sym(s, syms) {
if (s->name)
log(LOG_TEST_FA, "%s ", s->name);
else if (s->constant)
log(LOG_TEST_FA, "\"%s\" ", s->constant);
log(LOG_TEST_FA, "(%s:%d) ", fn(s->filename()), s->line());
}
log(LOG_TEST_FA, ")\n");
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2015 Cloudius Systems, Ltd.
*/
#include "core/do_with.hh"
#include "cql_test_env.hh"
#include "cql3/query_processor.hh"
#include "cql3/query_options.hh"
#include "core/distributed.hh"
#include "core/shared_ptr.hh"
#include "utils/UUID_gen.hh"
#include "message/messaging_service.hh"
#include "service/storage_service.hh"
class in_memory_cql_env : public cql_test_env {
public:
static auto constexpr ks_name = "ks";
private:
::shared_ptr<distributed<database>> _db;
::shared_ptr<distributed<cql3::query_processor>> _qp;
::shared_ptr<distributed<service::storage_proxy>> _proxy;
private:
struct core_local_state {
service::client_state client_state;
core_local_state()
: client_state(service::client_state::for_internal_calls()) {
client_state.set_keyspace(ks_name);
}
future<> stop() {
return make_ready_future<>();
}
};
distributed<core_local_state> _core_local;
private:
auto make_query_state() {
return ::make_shared<service::query_state>(_core_local.local().client_state);
}
public:
in_memory_cql_env(
::shared_ptr<distributed<database>> db,
::shared_ptr<distributed<cql3::query_processor>> qp,
::shared_ptr<distributed<service::storage_proxy>> proxy)
: _db(db)
, _qp(qp)
, _proxy(proxy)
{ }
virtual future<::shared_ptr<transport::messages::result_message>> execute_cql(const sstring& text) override {
auto qs = make_query_state();
return _qp->local().process(text, *qs, cql3::query_options::DEFAULT).finally([qs] {});
}
virtual future<::shared_ptr<transport::messages::result_message>> execute_cql(
const sstring& text,
std::unique_ptr<cql3::query_options> qo) override
{
auto qs = make_query_state();
auto& lqo = *qo;
return _qp->local().process(text, *qs, lqo).finally([qs, qo = std::move(qo)] {});
}
virtual future<bytes> prepare(sstring query) override {
return _qp->invoke_on_all([query, this] (auto& local_qp) {
auto qs = this->make_query_state();
return local_qp.prepare(query, *qs).finally([qs] {}).discard_result();
}).then([query, this] {
return _qp->local().compute_id(query, ks_name);
});
}
virtual future<::shared_ptr<transport::messages::result_message>> execute_prepared(
bytes id,
std::vector<bytes_opt> values) override
{
auto prepared = _qp->local().get_prepared(id);
assert(bool(prepared));
auto stmt = prepared->statement;
assert(stmt->get_bound_terms() == values.size());
int32_t protocol_version = 3;
auto options = ::make_shared<cql3::query_options>(db::consistency_level::ONE, std::experimental::nullopt, std::move(values), false,
cql3::query_options::specific_options::DEFAULT, protocol_version, serialization_format::use_32_bit());
options->prepare(prepared->bound_names);
auto qs = make_query_state();
return _qp->local().process_statement(stmt, *qs, *options)
.finally([options, qs] {});
}
virtual future<> create_table(std::function<schema(const sstring&)> schema_maker) override {
auto id = utils::UUID_gen::get_time_UUID();
return _db->invoke_on_all([schema_maker, id, this] (database& db) {
auto cf_schema = make_lw_shared(schema_maker(ks_name));
cf_schema->set_id(id);
auto& ks = db.find_keyspace(ks_name);
auto cfg = ks.make_column_family_config(*cf_schema);
db.add_column_family(std::move(cf_schema), std::move(cfg));
});
}
virtual future<> require_keyspace_exists(const sstring& ks_name) override {
auto& db = _db->local();
assert(db.has_keyspace(ks_name));
return make_ready_future<>();
}
virtual future<> require_table_exists(const sstring& ks_name, const sstring& table_name) override {
auto& db = _db->local();
assert(db.has_schema(ks_name, table_name));
return make_ready_future<>();
}
virtual future<> require_column_has_value(const sstring& table_name,
std::vector<boost::any> pk,
std::vector<boost::any> ck,
const sstring& column_name,
boost::any expected) override {
auto& db = _db->local();
auto& cf = db.find_column_family(ks_name, table_name);
auto schema = cf.schema();
auto pkey = partition_key::from_deeply_exploded(*schema, pk);
auto dk = dht::global_partitioner().decorate_key(*schema, pkey);
auto shard = db.shard_of(dk._token);
return _db->invoke_on(shard, [pkey = std::move(pkey),
ck = std::move(ck),
ks_name = std::move(ks_name),
column_name = std::move(column_name),
expected = std::move(expected),
table_name = std::move(table_name)] (database& db) mutable {
auto& cf = db.find_column_family(ks_name, table_name);
auto schema = cf.schema();
return cf.find_partition_slow(pkey).then([schema, ck, column_name, expected] (column_family::const_mutation_partition_ptr p) {
assert(p != nullptr);
auto row = p->find_row(clustering_key::from_deeply_exploded(*schema, ck));
assert(row != nullptr);
auto col_def = schema->get_column_definition(utf8_type->decompose(column_name));
assert(col_def != nullptr);
const atomic_cell_or_collection* cell = row->find_cell(col_def->id);
if (!cell) {
assert(((void)"column not set", 0));
}
bytes actual;
if (!col_def->type->is_multi_cell()) {
auto c = cell->as_atomic_cell();
assert(c.is_live());
actual = { c.value().begin(), c.value().end() };
} else {
auto c = cell->as_collection_mutation();
auto type = dynamic_pointer_cast<const collection_type_impl>(col_def->type);
actual = type->to_value(type->deserialize_mutation_form(c),
serialization_format::internal());
}
assert(col_def->type->equal(actual, col_def->type->decompose(expected)));
});
});
}
virtual database& local_db() override {
return _db->local();
}
future<> start() {
return _core_local.start().then([this] () {
auto query = sprint("create keyspace %s with replication = { 'class' : 'org.apache.cassandra.locator.SimpleStrategy', 'replication_factor' : 1 };", sstring{ks_name});
return execute_cql(query).discard_result().then([] {
return make_ready_future<>();
});
});
}
virtual future<> stop() override {
return _core_local.stop().then([this] {
return _qp->stop().then([this] {
return _proxy->stop().then([this] {
return _db->stop().then([] {
return locator::i_endpoint_snitch::stop_snitch();
});
});
});
});
}
};
future<> init_once() {
static bool done = false;
if (!done) {
done = true;
return service::init_storage_service().then([] {
return net::init_messaging_service("127.0.0.1", db::config::seed_provider_type()).then([] {
});
});
} else {
return make_ready_future();
}
}
future<::shared_ptr<cql_test_env>> make_env_for_test() {
return init_once().then([] {
using namespace locator;
return i_endpoint_snitch::create_snitch("org.apache.cassandra.locator.SimpleSnitch").then([] {
auto db = ::make_shared<distributed<database>>();
auto cfg = make_lw_shared<db::config>();
cfg->data_file_directories() = {};
return db->start(std::move(*cfg)).then([db] {
auto proxy = ::make_shared<distributed<service::storage_proxy>>();
auto qp = ::make_shared<distributed<cql3::query_processor>>();
return proxy->start(std::ref(*db)).then([qp, db, proxy] {
return qp->start(std::ref(*proxy), std::ref(*db)).then([db, proxy, qp] {
auto env = ::make_shared<in_memory_cql_env>(db, qp, proxy);
return env->start().then([env] () -> ::shared_ptr<cql_test_env> {
return env;
});
});
});
});
});
});
}
future<> do_with_cql_env(std::function<future<>(cql_test_env&)> func) {
return make_env_for_test().then([func = std::move(func)] (auto e) mutable {
return do_with(std::move(func), [e] (auto& f) {
return f(*e);
}).finally([e] {
return e->stop().finally([e] {});
});
});
}
<commit_msg>cql_test_env: Start the global snitch before storage service<commit_after>/*
* Copyright (C) 2015 Cloudius Systems, Ltd.
*/
#include "core/do_with.hh"
#include "cql_test_env.hh"
#include "cql3/query_processor.hh"
#include "cql3/query_options.hh"
#include "core/distributed.hh"
#include "core/shared_ptr.hh"
#include "utils/UUID_gen.hh"
#include "message/messaging_service.hh"
#include "service/storage_service.hh"
class in_memory_cql_env : public cql_test_env {
public:
static auto constexpr ks_name = "ks";
private:
::shared_ptr<distributed<database>> _db;
::shared_ptr<distributed<cql3::query_processor>> _qp;
::shared_ptr<distributed<service::storage_proxy>> _proxy;
private:
struct core_local_state {
service::client_state client_state;
core_local_state()
: client_state(service::client_state::for_internal_calls()) {
client_state.set_keyspace(ks_name);
}
future<> stop() {
return make_ready_future<>();
}
};
distributed<core_local_state> _core_local;
private:
auto make_query_state() {
return ::make_shared<service::query_state>(_core_local.local().client_state);
}
public:
in_memory_cql_env(
::shared_ptr<distributed<database>> db,
::shared_ptr<distributed<cql3::query_processor>> qp,
::shared_ptr<distributed<service::storage_proxy>> proxy)
: _db(db)
, _qp(qp)
, _proxy(proxy)
{ }
virtual future<::shared_ptr<transport::messages::result_message>> execute_cql(const sstring& text) override {
auto qs = make_query_state();
return _qp->local().process(text, *qs, cql3::query_options::DEFAULT).finally([qs] {});
}
virtual future<::shared_ptr<transport::messages::result_message>> execute_cql(
const sstring& text,
std::unique_ptr<cql3::query_options> qo) override
{
auto qs = make_query_state();
auto& lqo = *qo;
return _qp->local().process(text, *qs, lqo).finally([qs, qo = std::move(qo)] {});
}
virtual future<bytes> prepare(sstring query) override {
return _qp->invoke_on_all([query, this] (auto& local_qp) {
auto qs = this->make_query_state();
return local_qp.prepare(query, *qs).finally([qs] {}).discard_result();
}).then([query, this] {
return _qp->local().compute_id(query, ks_name);
});
}
virtual future<::shared_ptr<transport::messages::result_message>> execute_prepared(
bytes id,
std::vector<bytes_opt> values) override
{
auto prepared = _qp->local().get_prepared(id);
assert(bool(prepared));
auto stmt = prepared->statement;
assert(stmt->get_bound_terms() == values.size());
int32_t protocol_version = 3;
auto options = ::make_shared<cql3::query_options>(db::consistency_level::ONE, std::experimental::nullopt, std::move(values), false,
cql3::query_options::specific_options::DEFAULT, protocol_version, serialization_format::use_32_bit());
options->prepare(prepared->bound_names);
auto qs = make_query_state();
return _qp->local().process_statement(stmt, *qs, *options)
.finally([options, qs] {});
}
virtual future<> create_table(std::function<schema(const sstring&)> schema_maker) override {
auto id = utils::UUID_gen::get_time_UUID();
return _db->invoke_on_all([schema_maker, id, this] (database& db) {
auto cf_schema = make_lw_shared(schema_maker(ks_name));
cf_schema->set_id(id);
auto& ks = db.find_keyspace(ks_name);
auto cfg = ks.make_column_family_config(*cf_schema);
db.add_column_family(std::move(cf_schema), std::move(cfg));
});
}
virtual future<> require_keyspace_exists(const sstring& ks_name) override {
auto& db = _db->local();
assert(db.has_keyspace(ks_name));
return make_ready_future<>();
}
virtual future<> require_table_exists(const sstring& ks_name, const sstring& table_name) override {
auto& db = _db->local();
assert(db.has_schema(ks_name, table_name));
return make_ready_future<>();
}
virtual future<> require_column_has_value(const sstring& table_name,
std::vector<boost::any> pk,
std::vector<boost::any> ck,
const sstring& column_name,
boost::any expected) override {
auto& db = _db->local();
auto& cf = db.find_column_family(ks_name, table_name);
auto schema = cf.schema();
auto pkey = partition_key::from_deeply_exploded(*schema, pk);
auto dk = dht::global_partitioner().decorate_key(*schema, pkey);
auto shard = db.shard_of(dk._token);
return _db->invoke_on(shard, [pkey = std::move(pkey),
ck = std::move(ck),
ks_name = std::move(ks_name),
column_name = std::move(column_name),
expected = std::move(expected),
table_name = std::move(table_name)] (database& db) mutable {
auto& cf = db.find_column_family(ks_name, table_name);
auto schema = cf.schema();
return cf.find_partition_slow(pkey).then([schema, ck, column_name, expected] (column_family::const_mutation_partition_ptr p) {
assert(p != nullptr);
auto row = p->find_row(clustering_key::from_deeply_exploded(*schema, ck));
assert(row != nullptr);
auto col_def = schema->get_column_definition(utf8_type->decompose(column_name));
assert(col_def != nullptr);
const atomic_cell_or_collection* cell = row->find_cell(col_def->id);
if (!cell) {
assert(((void)"column not set", 0));
}
bytes actual;
if (!col_def->type->is_multi_cell()) {
auto c = cell->as_atomic_cell();
assert(c.is_live());
actual = { c.value().begin(), c.value().end() };
} else {
auto c = cell->as_collection_mutation();
auto type = dynamic_pointer_cast<const collection_type_impl>(col_def->type);
actual = type->to_value(type->deserialize_mutation_form(c),
serialization_format::internal());
}
assert(col_def->type->equal(actual, col_def->type->decompose(expected)));
});
});
}
virtual database& local_db() override {
return _db->local();
}
future<> start() {
return _core_local.start().then([this] () {
auto query = sprint("create keyspace %s with replication = { 'class' : 'org.apache.cassandra.locator.SimpleStrategy', 'replication_factor' : 1 };", sstring{ks_name});
return execute_cql(query).discard_result().then([] {
return make_ready_future<>();
});
});
}
virtual future<> stop() override {
return _core_local.stop().then([this] {
return _qp->stop().then([this] {
return _proxy->stop().then([this] {
return _db->stop().then([] {
return locator::i_endpoint_snitch::stop_snitch();
});
});
});
});
}
};
future<> init_once() {
static bool done = false;
if (!done) {
done = true;
return service::init_storage_service().then([] {
return net::init_messaging_service("127.0.0.1", db::config::seed_provider_type()).then([] {
});
});
} else {
return make_ready_future();
}
}
future<::shared_ptr<cql_test_env>> make_env_for_test() {
return locator::i_endpoint_snitch::create_snitch("SimpleSnitch").then([] {
return init_once().then([] {
auto db = ::make_shared<distributed<database>>();
auto cfg = make_lw_shared<db::config>();
cfg->data_file_directories() = {};
return db->start(std::move(*cfg)).then([db] {
auto proxy = ::make_shared<distributed<service::storage_proxy>>();
auto qp = ::make_shared<distributed<cql3::query_processor>>();
return proxy->start(std::ref(*db)).then([qp, db, proxy] {
return qp->start(std::ref(*proxy), std::ref(*db)).then([db, proxy, qp] {
auto env = ::make_shared<in_memory_cql_env>(db, qp, proxy);
return env->start().then([env] () -> ::shared_ptr<cql_test_env> {
return env;
});
});
});
});
});
});
}
future<> do_with_cql_env(std::function<future<>(cql_test_env&)> func) {
return make_env_for_test().then([func = std::move(func)] (auto e) mutable {
return do_with(std::move(func), [e] (auto& f) {
return f(*e);
}).finally([e] {
return e->stop().finally([e] {});
});
});
}
<|endoftext|> |
<commit_before>//===--- TypeSerialization.cpp - Serialization of Decls ---------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by Ted Kremenek and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This files defines methods that implement bitcode serialization for Types.
//
//===----------------------------------------------------------------------===//
#include "clang/AST/Type.h"
#include "llvm/Bitcode/Serialize.h"
#include "llvm/Bitcode/Deserialize.h"
using namespace clang;
void QualType::Emit(llvm::Serializer& S) const {
S.EmitPtr(getAsOpaquePtr());
S.EmitInt(getQualifiers());
}
void QualType::Read(llvm::Deserializer& D) {
D.ReadPtr(ThePtr);
ThePtr |= D.ReadInt();
}
/* FIXME: Either remove this method or complete it.
void Type::Emit(llvm::Serializer& S) {
switch (getTypeClass()) {
default:
assert (false && "Serialization for type class not implemented.");
break;
case Type::Builtin:
cast<BuiltinType>(this)->Emit(S);
break;
}
}
*/
void Type::EmitTypeInternal(llvm::Serializer& S) const {
S.Emit(CanonicalType);
}
void Type::ReadTypeInternal(llvm::Deserializer& D) {
D.Read(CanonicalType);
}
void ComplexType::Emit(llvm::Serializer& S) const {
EmitTypeInternal(S);
S.Emit(ElementType);
}
ComplexType* ComplexType::Materialize(llvm::Deserializer& D) {
ComplexType* T = new ComplexType(QualType(),QualType());
T->ReadTypeInternal(D);
D.Read(T->ElementType);
return T;
}
void PointerType::Emit(llvm::Serializer& S) const {
EmitTypeInternal(S);
S.Emit(PointeeType);
}
PointerType* PointerType::Materialize(llvm::Deserializer& D) {
PointerType* T = new PointerType(QualType(),QualType());
T->ReadTypeInternal(D);
D.Read(T->PointeeType);
return T;
}
void ReferenceType::Emit(llvm::Serializer& S) const {
EmitTypeInternal(S);
S.Emit(ReferenceeType);
}
ReferenceType* ReferenceType::Materialize(llvm::Deserializer& D) {
ReferenceType* T = new ReferenceType(QualType(),QualType());
T->ReadTypeInternal(D);
D.Read(T->ReferenceeType);
return T;
}
void ArrayType::EmitArrayTypeInternal(llvm::Serializer& S) const {
EmitTypeInternal(S);
S.Emit(ElementType);
S.EmitInt(SizeModifier);
S.EmitInt(IndexTypeQuals);
}
void ArrayType::ReadArrayTypeInternal(llvm::Deserializer& D) {
ReadTypeInternal(D);
D.Read(ElementType);
SizeModifier = static_cast<ArraySizeModifier>(D.ReadInt());
IndexTypeQuals = D.ReadInt();
}
void ConstantArrayType::Emit(llvm::Serializer& S) const {
#if 0
// FIXME: APInt serialization
S.Emit(Size);
#endif
EmitArrayTypeInternal(S);
}
ConstantArrayType* ConstantArrayType::Materialize(llvm::Deserializer& D) {
#if 0
llvm::APInt x = S.ReadVal<llvm::APInt>(D);
// "Default" construct the array.
ConstantArrayType* T =
new ConstantArrayType(QualType(), QualType(), x, ArrayType::Normal, 0);
// Deserialize the internal values.
T->ReadArrayTypeInternal(D);
return T;
#else
return NULL;
#endif
}
<commit_msg>Completed serialization of ConstantArrayTypes (now that APInt serialization is in place).<commit_after>//===--- TypeSerialization.cpp - Serialization of Decls ---------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by Ted Kremenek and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This files defines methods that implement bitcode serialization for Types.
//
//===----------------------------------------------------------------------===//
#include "clang/AST/Type.h"
#include "llvm/Bitcode/Serialize.h"
#include "llvm/Bitcode/Deserialize.h"
using namespace clang;
void QualType::Emit(llvm::Serializer& S) const {
S.EmitPtr(getAsOpaquePtr());
S.EmitInt(getQualifiers());
}
void QualType::Read(llvm::Deserializer& D) {
D.ReadPtr(ThePtr);
ThePtr |= D.ReadInt();
}
/* FIXME: Either remove this method or complete it.
void Type::Emit(llvm::Serializer& S) {
switch (getTypeClass()) {
default:
assert (false && "Serialization for type class not implemented.");
break;
case Type::Builtin:
cast<BuiltinType>(this)->Emit(S);
break;
}
}
*/
void Type::EmitTypeInternal(llvm::Serializer& S) const {
S.Emit(CanonicalType);
}
void Type::ReadTypeInternal(llvm::Deserializer& D) {
D.Read(CanonicalType);
}
void ComplexType::Emit(llvm::Serializer& S) const {
EmitTypeInternal(S);
S.Emit(ElementType);
}
ComplexType* ComplexType::Materialize(llvm::Deserializer& D) {
ComplexType* T = new ComplexType(QualType(),QualType());
T->ReadTypeInternal(D);
D.Read(T->ElementType);
return T;
}
void PointerType::Emit(llvm::Serializer& S) const {
EmitTypeInternal(S);
S.Emit(PointeeType);
}
PointerType* PointerType::Materialize(llvm::Deserializer& D) {
PointerType* T = new PointerType(QualType(),QualType());
T->ReadTypeInternal(D);
D.Read(T->PointeeType);
return T;
}
void ReferenceType::Emit(llvm::Serializer& S) const {
EmitTypeInternal(S);
S.Emit(ReferenceeType);
}
ReferenceType* ReferenceType::Materialize(llvm::Deserializer& D) {
ReferenceType* T = new ReferenceType(QualType(),QualType());
T->ReadTypeInternal(D);
D.Read(T->ReferenceeType);
return T;
}
void ArrayType::EmitArrayTypeInternal(llvm::Serializer& S) const {
EmitTypeInternal(S);
S.Emit(ElementType);
S.EmitInt(SizeModifier);
S.EmitInt(IndexTypeQuals);
}
void ArrayType::ReadArrayTypeInternal(llvm::Deserializer& D) {
ReadTypeInternal(D);
D.Read(ElementType);
SizeModifier = static_cast<ArraySizeModifier>(D.ReadInt());
IndexTypeQuals = D.ReadInt();
}
void ConstantArrayType::Emit(llvm::Serializer& S) const {
EmitArrayTypeInternal(S);
S.Emit(Size);
}
ConstantArrayType* ConstantArrayType::Materialize(llvm::Deserializer& D) {
// "Default" construct the array.
ConstantArrayType* T =
new ConstantArrayType(QualType(), QualType(), llvm::APInt(),
ArrayType::Normal, 0);
// Deserialize the internal values.
T->ReadArrayTypeInternal(D);
D.Read(T->Size);
return T;
}
<|endoftext|> |
<commit_before>// Blink.cpp : Defines the entry point for the console application.
//
#include "ConnectionService.h"
#include "TreehopperUsb.h"
#include <string>
#include <vector>
#include <iostream>
using namespace Treehopper;
int main()
{
auto service = ConnectionService::instance();
TreehopperUsb& board = service.getFirstDevice();
board.connect();
board.pins[2].makeAnalogInput();
for(int i=0;i<20;i++)
{
board.led(!board.led());
//board.pins[1].toggleOutput();
cout << board.pins[2].adcValue() << endl;
this_thread::sleep_for(chrono::milliseconds(100));
}
board.disconnect();
while(true)
{
std:this_thread::sleep_for(chrono::seconds(5));
}
return 0;
}
<commit_msg>Don't hang after blink is finished<commit_after>// Blink.cpp : Defines the entry point for the console application.
//
#include "ConnectionService.h"
#include "TreehopperUsb.h"
#include <string>
#include <vector>
#include <iostream>
using namespace Treehopper;
int main()
{
auto service = ConnectionService::instance();
TreehopperUsb& board = service.getFirstDevice();
board.connect();
board.pins[2].makeAnalogInput();
for(int i=0;i<20;i++)
{
board.led(!board.led());
//board.pins[1].toggleOutput();
cout << board.pins[2].adcValue() << endl;
this_thread::sleep_for(chrono::milliseconds(100));
}
board.disconnect();
return 0;
}
<|endoftext|> |
<commit_before>/*
* Mediator
* Author: reimen
* Data: Oct.15.2014
*
*/
#include <iostream>
#include <cstdlib>
using std::cout;
using std::endl;
class Colleague;
class Mediator;
class ConcreteMediator;
class Mediator
{
protected:
Colleague* _colleague;
public:
virtual ~Mediator() {}
virtual void createColleague() = 0;
virtual void colleagueChanged() = 0;
};
class Colleague
{
protected:
Mediator* _mediator;
public:
virtual ~Colleague() {}
virtual void setMediator(Mediator* mediator) = 0;
virtual void controlColleague() = 0;
};
class ConcreteColleague : public Colleague
{
private:
public:
ConcreteColleague() {}
virtual ~ConcreteColleague() {}
void setMediator(Mediator* mediator)
{
_mediator = mediator;
}
void controlColleague()
{
cout << "Hello This is Colleague" << endl;
if(_mediator != NULL)
{
_mediator -> colleagueChanged();
}
else
{
cout << "There is no mediator" << endl;
}
}
};
class ConcreteMediator : Mediator
{
public:
virtual ~ConcreteMediator() { delete _colleague; }
void createColleague()
{
if(_colleague == NULL)
{
_colleague = new ConcreteColleague;
_colleague -> setMediator(this);
}
}
void colleagueChanged()
{
cout << "Hello I am mediator!!" << endl;
}
void zap()
{
if(_colleague != NULL)
{
_colleague->controlColleague();
}
else
{
cout << "No colleague" << endl;
}
}
};
int main()
{
ConcreteMediator mediator;
mediator.createColleague();
mediator.zap();
return EXIT_SUCCESS;
}
<commit_msg>Add Comments to Mediator.cpp<commit_after>/*
* Mediator
* Author: reimen
* Date: Oct.15.2014
* Define an object that encapsulates how a set of objects interact.
* Mediator promotes loose coupling by keeping objects from
* referring to each other explicitly, and it lets you vary their
* interaction independently.
*/
#include <iostream>
#include <cstdlib>
using std::cout;
using std::endl;
class Colleague;
class Mediator;
class ConcreteMediator;
class Mediator
{
protected:
Colleague* _colleague;
public:
virtual ~Mediator() {}
virtual void createColleague() = 0;
virtual void colleagueChanged() = 0;
};
class Colleague
{
protected:
Mediator* _mediator;
public:
virtual ~Colleague() {}
virtual void setMediator(Mediator* mediator) = 0;
virtual void controlColleague() = 0;
};
class ConcreteColleague : public Colleague
{
private:
public:
ConcreteColleague() {}
virtual ~ConcreteColleague() {}
void setMediator(Mediator* mediator)
{
_mediator = mediator;
}
void controlColleague()
{
cout << "Hello This is Colleague" << endl;
if(_mediator != NULL)
{
_mediator -> colleagueChanged();
}
else
{
cout << "There is no mediator" << endl;
}
}
};
class ConcreteMediator : Mediator
{
public:
virtual ~ConcreteMediator()
{
delete _colleague;
}
void createColleague()
{
if(_colleague == NULL)
{
_colleague = new ConcreteColleague;
_colleague -> setMediator(this);
}
}
void colleagueChanged()
{
cout << "Hello I am mediator!!" << endl;
}
void zap()
{
if(_colleague != NULL)
{
_colleague->controlColleague();
}
else
{
cout << "No colleague" << endl;
}
}
};
int main()
{
ConcreteMediator mediator;
mediator.createColleague();
mediator.zap();
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>#include <string>
#include <fstream>
#include <sstream>
#include <cstdlib>
#include <iostream>
#include <vector>
#include <algorithm>
#include "gtest/gtest.h"
// redefine class, private & protected to get access to
// private and protected members of rbtree & rbnode.
#define class struct
#define private public
#define protected public
#include "../rbtree.hpp"
#include "../rbnode.hpp"
#undef class
#undef private
#undef protected
using namespace std;
// Redirect the cout to a string
struct cout_redirect {
cout_redirect(std::streambuf* new_buffer)
: old( std::cout.rdbuf(new_buffer))
{
}
~cout_redirect() {
std::cout.rdbuf(old);
}
private:
std::streambuf* old;
};
class rbtree_tests : public ::testing::Test {
public:
// red black trees
rbtree* rbt;
rbtree_tests() {
rbt = new rbtree();
}
~rbtree_tests() {
delete rbt;
}
};
TEST_F(rbtree_tests, test_empty) {
EXPECT_TRUE(rbt->root == nullptr) << "root should be null";
}
TEST_F(rbtree_tests, test_rbtree_invalid) {
rbt->root = new rbnode(56, rbcolor::red);
EXPECT_FALSE(rbt->is_valid_rbtree()) << "tree with red root is invalid";
}
TEST_F(rbtree_tests, test_rbtree_valid_1) {
// build a red black tree.
auto root = new rbnode(45, rbcolor::black);
auto r1 = new rbnode(25);
r1->parent = root;
auto r2 = new rbnode(60);
r2->parent = root;
root->left = r1;
root->right = r2;
rbt->root = root;
EXPECT_TRUE(rbt->is_valid_rbtree());
}
TEST_F(rbtree_tests, test_rbtree_valid_2) {
auto root = new rbnode(10, rbcolor::black);
auto n7 = new rbnode(7, rbcolor::black, root);
auto n19 = new rbnode(19, rbcolor::red, root);
auto n13 = new rbnode(13, rbcolor::black, n19);
auto n23 = new rbnode(23, rbcolor::black, n19);
root->left = n7;
root->right = n19;
n19->left = n13;
n19->right = n23;
rbt->root = root;
EXPECT_TRUE(rbt->is_valid_rbtree());
}
TEST_F(rbtree_tests, test_rbtree_insert) {
}
TEST_F(rbtree_tests, test_rbtree_remove) {
}
TEST_F(rbtree_tests, test_rbtree_remove_all) {
}
<commit_msg>added test cases for rb insert, rotate<commit_after>#include <string>
#include <fstream>
#include <sstream>
#include <cstdlib>
#include <iostream>
#include <vector>
#include <cmath>
#include <algorithm>
#include "gtest/gtest.h"
// redefine class, private & protected to get access to
// private and protected members of rbtree & rbnode.
#define class struct
#define private public
#define protected public
#include "../rbtree.hpp"
#include "../rbnode.hpp"
#undef class
#undef private
#undef protected
using namespace std;
// Redirect the cout to a string
struct cout_redirect {
cout_redirect(std::streambuf* new_buffer)
: old( std::cout.rdbuf(new_buffer))
{
}
~cout_redirect() {
std::cout.rdbuf(old);
}
private:
std::streambuf* old;
};
class rbtree_tests : public ::testing::Test {
public:
// red black trees
rbtree* rbt;
rbtree_tests() {
rbt = new rbtree();
}
~rbtree_tests() {
delete rbt;
}
};
TEST_F(rbtree_tests, test_empty) {
EXPECT_TRUE(rbt->root == nullptr) << "root should be null!";
}
TEST_F(rbtree_tests, test_rbtree_invalid_1) {
rbt->root = new rbnode(56, rbcolor::red);
EXPECT_FALSE(rbt->is_valid_rbtree()) << "tree with red root should be invalid!";
}
TEST_F(rbtree_tests, test_rbtree_invalid_2) {
auto root = new rbnode(7, rbcolor::black);
auto n3 = new rbnode(3, rbcolor::red, root);
auto n18 = new rbnode(18, rbcolor::black, root);
auto n1 = new rbnode(1, rbcolor::black, n3);
auto n45 = new rbnode(45, rbcolor::black, n18);
auto n2 = new rbnode(2, rbcolor::black, n1);
root->left = n3;
root->right = n18;
n18->right = n45;
n3->left = n1;
n1->right = n2;
rbt->root = root;
EXPECT_FALSE(rbt->is_valid_rbtree());
}
TEST_F(rbtree_tests, test_rbtree_valid_1) {
// build a red black tree.
auto root = new rbnode(45, rbcolor::black);
auto r1 = new rbnode(25);
r1->parent = root;
auto r2 = new rbnode(60);
r2->parent = root;
root->left = r1;
root->right = r2;
rbt->root = root;
EXPECT_TRUE(rbt->is_valid_rbtree());
}
TEST_F(rbtree_tests, test_rbtree_valid_2) {
auto root = new rbnode(10, rbcolor::black);
auto n7 = new rbnode(7, rbcolor::black, root);
auto n19 = new rbnode(19, rbcolor::red, root);
auto n13 = new rbnode(13, rbcolor::black, n19);
auto n23 = new rbnode(23, rbcolor::black, n19);
root->left = n7;
root->right = n19;
n19->left = n13;
n19->right = n23;
rbt->root = root;
EXPECT_TRUE(rbt->is_valid_rbtree());
}
TEST_F(rbtree_tests, test_rbtree_insert) {
// generated using visualization tool: https://www.cs.usfca.edu/~galles/visualization/RedBlack.html
vector<string> expected = {
"0(black)\n",
"0(black)\n1(red)\n",
"0(red)\n1(black)\n2(red)\n",
"0(black)\n1(black)\n2(black)\n3(red)\n",
"0(black)\n1(black)\n2(red)\n3(black)\n4(red)\n",
"0(black)\n1(black)\n2(black)\n3(red)\n4(black)\n5(red)\n",
"0(black)\n1(black)\n2(black)\n3(red)\n4(red)\n5(black)\n6(red)\n",
"0(black)\n1(red)\n2(black)\n3(black)\n4(black)\n5(red)\n6(black)\n7(red)\n",
"0(black)\n1(red)\n2(black)\n3(black)\n4(black)\n5(red)\n6(red)\n7(black)\n8(red)\n",
"0(black)\n1(black)\n2(black)\n3(black)\n4(black)\n5(black)\n6(black)\n7(red)\n8(black)\n9(red)\n"
};
for (int i = 0; i < expected.size(); i++) {
auto n = i+1;
rbt->insert(i);
stringstream buffer; {
cout_redirect activate(buffer.rdbuf());
rbt->inorder();
}
string got = buffer.str();
EXPECT_TRUE(expected[i] == got) << "insert of " << i << " is incorrect!";
// max heigth of rb tree <= 2 * log(n+1)
EXPECT_TRUE(rbt->depth() < 2 * ceil(log2(n+1))) << "depth of rb tree is incorrect!";
}
}
TEST_F(rbtree_tests, test_rbtree_remove) {
}
TEST_F(rbtree_tests, test_rbtree_remove_all) {
rbt->remove_all(rbt->root);
EXPECT_TRUE(rbt->root == nullptr);
EXPECT_TRUE(rbt->depth() == 0) << "depth of empty rb tree should be zero!";
}
TEST_F(rbtree_tests, test_left_rotate) {
/*
x y
/ \ left rotate around x / \
a y ------------------------> x c
/ \ / \
b c a b
*/
auto x = new rbnode(50, rbcolor::black);
auto y = new rbnode(60, rbcolor::red, x);
auto a = new rbnode(25, rbcolor::black, x);
auto b = new rbnode(55, rbcolor::black, y);
auto c = new rbnode(70, rbcolor::black, y);
x->left = a;
x->right = y;
y->right = c;
y->left = b;
rbt->root = x;
rbt->left_rotate(x);
stringstream buffer; {
cout_redirect activate(buffer.rdbuf());
rbt->inorder();
}
string expected = "25(black)\n50(black)\n55(black)\n60(red)\n70(black)\n";
string got = buffer.str();
EXPECT_TRUE(expected == got) << "left rotation is incorrect!";
EXPECT_TRUE(rbt->depth() == 3) << "left rotation is of incorrect depth!";
}
TEST_F(rbtree_tests, test_right_rotate) {
/*
y x
/ \ right rotate around y / \
x c -----------------------> a y
/ \ / \
a b b c
*/
auto y = new rbnode(50, rbcolor::black);
auto x = new rbnode(25, rbcolor::red, y);
auto a = new rbnode(10, rbcolor::black, x);
auto b = new rbnode(30, rbcolor::black, x);
auto c = new rbnode(60, rbcolor::black);
x->left = a;
x->right = b;
y->right = c;
y->left = x;
rbt->root = y;
rbt->right_rotate(y);
stringstream buffer; {
cout_redirect activate(buffer.rdbuf());
rbt->inorder();
}
string expected = "10(black)\n25(red)\n30(black)\n50(black)\n60(black)\n";
string got = buffer.str();
EXPECT_TRUE(expected == got) << "right rotation is incorrect.";
EXPECT_TRUE(rbt->depth() == 3) << "right rotation is of incorrect depth";
}
<|endoftext|> |
<commit_before>using namespace System;
using namespace System::Reflection;
using namespace System::Runtime::CompilerServices;
using namespace System::Runtime::InteropServices;
using namespace System::Security::Permissions;
//
// Les informations gnrales relatives un assembly dpendent de
// l'ensemble d'attributs suivant. Changez les valeurs de ces attributs pour modifier les informations
// associes un assembly.
//
[assembly:AssemblyTitleAttribute(L"ClrPhlib")];
[assembly:AssemblyDescriptionAttribute(L"")];
[assembly:AssemblyConfigurationAttribute(L"")];
[assembly:AssemblyCompanyAttribute(L"")];
[assembly:AssemblyProductAttribute(L"ClrPhlib")];
[assembly:AssemblyCopyrightAttribute(L"Copyright (c) 2017")];
[assembly:AssemblyTrademarkAttribute(L"")];
[assembly:AssemblyCultureAttribute(L"")];
//
// Les informations de version pour un assembly se composent des quatre valeurs suivantes:
//
// Version principale
// Version secondaire
// Numro de build
// Rvision
//
// Vous pouvez spcifier toutes les valeurs ou indiquer les numros de rvision et de build par dfaut
// en utilisant '*', comme indiqu ci-dessous:
[assembly:AssemblyVersionAttribute("1.9.*")];
[assembly:ComVisible(false)];
[assembly:CLSCompliantAttribute(true)];<commit_msg>Save encoding of AssemblyInfo.cpp to UTF-8 because of the diacritics of comment may cause compile error (we treat compile warning as error).<commit_after>using namespace System;
using namespace System::Reflection;
using namespace System::Runtime::CompilerServices;
using namespace System::Runtime::InteropServices;
using namespace System::Security::Permissions;
//
// Les informations générales relatives à un assembly dépendent de
// l'ensemble d'attributs suivant. Changez les valeurs de ces attributs pour modifier les informations
// associées à un assembly.
//
[assembly:AssemblyTitleAttribute(L"ClrPhlib")];
[assembly:AssemblyDescriptionAttribute(L"")];
[assembly:AssemblyConfigurationAttribute(L"")];
[assembly:AssemblyCompanyAttribute(L"")];
[assembly:AssemblyProductAttribute(L"ClrPhlib")];
[assembly:AssemblyCopyrightAttribute(L"Copyright (c) 2017")];
[assembly:AssemblyTrademarkAttribute(L"")];
[assembly:AssemblyCultureAttribute(L"")];
//
// Les informations de version pour un assembly se composent des quatre valeurs suivantes :
//
// Version principale
// Version secondaire
// Numéro de build
// Révision
//
// Vous pouvez spécifier toutes les valeurs ou indiquer les numéros de révision et de build par défaut
// en utilisant '*', comme indiqué ci-dessous :
[assembly:AssemblyVersionAttribute("1.9.*")];
[assembly:ComVisible(false)];
[assembly:CLSCompliantAttribute(true)];<|endoftext|> |
<commit_before>/*=========================================================================
Program: Monteverdi2
Language: C++
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See Copyright.txt for details.
Monteverdi2 is distributed under the CeCILL licence version 2. See
Licence_CeCILL_V2-en.txt or
http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt for more details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
//
// Configuration include.
//// Included at first position before any other ones.
#include "ConfigureMonteverdi2.h"
//
// Qt includes (sorted by alphabetic order)
//// Must be included before system/custom includes.
//
// System includes (sorted by alphabetic order)
// Monteverdi includes (sorted by alphabetic order)
#include "mvdApplication.h"
#include "mvdMainWindow.h"
#include "mvdDatasetModel.h"
//
// OTB includes (sorted by alphabetic order)
//
// MAIN
//
int
main( int argc, char* argv[] )
{
mvd::Application application( argc, argv );
//
// Force numeric options of locale to "C"
// See issue #635
//
// TODO: Move into I18nApplication.
setlocale( LC_NUMERIC, "C" );
// Check if the application have a settings file already available
bool appHasSettingsFile = application.HasSettingsFile();
bool appHasIncorrectCacheDir(false);
if (appHasSettingsFile)
{
// Read cache dir from settings
application.ReadCacheDirFromSettings();
// Check the cache dir
if (!application.CheckCacheDirIsCorrect() )
{
appHasIncorrectCacheDir = true;
}
}
else // TODO MSD: should be removed
{
std::cout << "Application has no settings file";
}
mvd::MainWindow mainWindow;
if (!appHasSettingsFile || appHasIncorrectCacheDir)
{
// Loop until the directory will be correct
while (true)
{
// Select a new location for the cache director
try
{
// Create the cache directory
application.MakeCacheDir(mainWindow.SelectCacheDir(appHasIncorrectCacheDir));
break;
}
catch (...)
{
appHasIncorrectCacheDir = true;
}
}
// Save the cache directory into the settings file
application.WriteCacheDirIntoSettings();
}
#if defined( _DEBUG )
// Usefull when developping/debugging to avoid overlapping other windows.
mainWindow.show();
#else
// TODO: Correctly manage main-window state via application settings.
mainWindow.showMaximized();
#endif
// This code is here to propagate events from maximization to child
// widgets, so that an image loaded from command-line will get the
// appropriate widget size and occupy as much space as possible on screen.
application.processEvents();
// TODO: Move into mvd::Application.
// Handle passing image filename from command-line
if(argc>1)
{
mainWindow.OpenImage( QString(argv[1]) );
}
return application.exec();
}
//
// Main functions implementations.
//
<commit_msg>BUG: fix resource loading on Windows<commit_after>/*=========================================================================
Program: Monteverdi2
Language: C++
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See Copyright.txt for details.
Monteverdi2 is distributed under the CeCILL licence version 2. See
Licence_CeCILL_V2-en.txt or
http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt for more details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
//
// Configuration include.
//// Included at first position before any other ones.
#include "ConfigureMonteverdi2.h"
//
// Qt includes (sorted by alphabetic order)
//// Must be included before system/custom includes.
//
// System includes (sorted by alphabetic order)
// Monteverdi includes (sorted by alphabetic order)
#include "mvdApplication.h"
#include "mvdMainWindow.h"
#include "mvdDatasetModel.h"
//
// OTB includes (sorted by alphabetic order)
//
// MAIN
//
int
main( int argc, char* argv[] )
{
Q_INIT_RESOURCE(mvdMainWindow);
mvd::Application application( argc, argv );
//
// Force numeric options of locale to "C"
// See issue #635
//
// TODO: Move into I18nApplication.
setlocale( LC_NUMERIC, "C" );
// Check if the application have a settings file already available
bool appHasSettingsFile = application.HasSettingsFile();
bool appHasIncorrectCacheDir(false);
if (appHasSettingsFile)
{
// Read cache dir from settings
application.ReadCacheDirFromSettings();
// Check the cache dir
if (!application.CheckCacheDirIsCorrect() )
{
appHasIncorrectCacheDir = true;
}
}
else // TODO MSD: should be removed
{
std::cout << "Application has no settings file";
}
mvd::MainWindow mainWindow;
if (!appHasSettingsFile || appHasIncorrectCacheDir)
{
// Loop until the directory will be correct
while (true)
{
// Select a new location for the cache director
try
{
// Create the cache directory
application.MakeCacheDir(mainWindow.SelectCacheDir(appHasIncorrectCacheDir));
break;
}
catch (...)
{
appHasIncorrectCacheDir = true;
}
}
// Save the cache directory into the settings file
application.WriteCacheDirIntoSettings();
}
#if defined( _DEBUG )
// Usefull when developping/debugging to avoid overlapping other windows.
mainWindow.show();
#else
// TODO: Correctly manage main-window state via application settings.
mainWindow.showMaximized();
#endif
// This code is here to propagate events from maximization to child
// widgets, so that an image loaded from command-line will get the
// appropriate widget size and occupy as much space as possible on screen.
application.processEvents();
// TODO: Move into mvd::Application.
// Handle passing image filename from command-line
if(argc>1)
{
mainWindow.OpenImage( QString(argv[1]) );
}
return application.exec();
}
//
// Main functions implementations.
//
<|endoftext|> |
<commit_before>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "otbMsgReporter.h"
#include <FL/Fl_Text_Buffer.H>
namespace otb
{
/** Initialize the singleton */
MsgReporter::Pointer MsgReporter::m_Instance = NULL;
/// Constructor
MsgReporter
::MsgReporter()
{
this->Build();
wMainWindow->show();
Fl_Text_Buffer * buffer = new Fl_Text_Buffer();
this->textArea->buffer(buffer);
}
/** Manage the singleton */
MsgReporter::Pointer
MsgReporter
::GetInstance()
{
if(!m_Instance)
{
m_Instance = MsgReporter::New();
}
return m_Instance;
}
//Show
void
MsgReporter
::Show()
{
this->wMainWindow->show();
}
//Hide
void
MsgReporter
::Hide()
{
this->wMainWindow->hide();
}
//Set title
void
MsgReporter
::SetTitle(const std::string & title)
{
std::string str(title);
str = str + " message reporter window";
this->wMainWindow->label(str.c_str());
}
//Send Msg
void
MsgReporter
::SendMsg(const std::string & msg)
{
this->textArea->insert(msg.c_str());
this->textArea->insert("\n");
this->textArea->show_insert_position();
Fl::check();
}
//Send Error
void
MsgReporter
::SendError(const std::string & msg)
{
this->textArea->insert("ERROR: ");
this->textArea->insert(msg.c_str());
this->textArea->insert("\n");
this->textArea->show_insert_position();
this->Show();
Fl::check();
}
}
<commit_msg>STYLE: tab replaced by 2 spaces<commit_after>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "otbMsgReporter.h"
#include <FL/Fl_Text_Buffer.H>
namespace otb
{
/** Initialize the singleton */
MsgReporter::Pointer MsgReporter::m_Instance = NULL;
/// Constructor
MsgReporter
::MsgReporter()
{
this->Build();
wMainWindow->show();
Fl_Text_Buffer * buffer = new Fl_Text_Buffer();
this->textArea->buffer(buffer);
}
/** Manage the singleton */
MsgReporter::Pointer
MsgReporter
::GetInstance()
{
if(!m_Instance)
{
m_Instance = MsgReporter::New();
}
return m_Instance;
}
//Show
void
MsgReporter
::Show()
{
this->wMainWindow->show();
}
//Hide
void
MsgReporter
::Hide()
{
this->wMainWindow->hide();
}
//Set title
void
MsgReporter
::SetTitle(const std::string & title)
{
std::string str(title);
str = str + " message reporter window";
this->wMainWindow->label(str.c_str());
}
//Send Msg
void
MsgReporter
::SendMsg(const std::string & msg)
{
this->textArea->insert(msg.c_str());
this->textArea->insert("\n");
this->textArea->show_insert_position();
Fl::check();
}
//Send Error
void
MsgReporter
::SendError(const std::string & msg)
{
this->textArea->insert("ERROR: ");
this->textArea->insert(msg.c_str());
this->textArea->insert("\n");
this->textArea->show_insert_position();
this->Show();
Fl::check();
}
}
<|endoftext|> |
<commit_before>/******************************************************************************
This source file is part of the TEM tomography project.
Copyright Kitware, Inc.
This source code is released under the New BSD License, (the "License").
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 "Behaviors.h"
#include "pqAlwaysConnectedBehavior.h"
#include "pqApplicationCore.h"
#include "pqDefaultViewBehavior.h"
#include "pqInterfaceTracker.h"
#include "pqPersistentMainWindowStateBehavior.h"
#include "pqQtMessageHandlerBehavior.h"
#include "pqStandardPropertyWidgetInterface.h"
#include "pqStandardViewModules.h"
#include "pqViewFrameActionsBehavior.h"
#include "ProgressBehavior.h"
#include <QMainWindow>
namespace TEM
{
//-----------------------------------------------------------------------------
Behaviors::Behaviors(QMainWindow* mainWindow)
{
Q_ASSERT(mainWindow);
// Register ParaView interfaces.
pqInterfaceTracker* pgm = pqApplicationCore::instance()->interfaceTracker();
// * adds support for standard paraview views.
pgm->addInterface(new pqStandardViewModules(pgm));
// * add support for ParaView properties panel widgets.
pgm->addInterface(new pqStandardPropertyWidgetInterface(pgm));
// Load plugins distributed with application.
pqApplicationCore::instance()->loadDistributedPlugins();
new pqQtMessageHandlerBehavior(this);
new pqViewFrameActionsBehavior(this);
new pqDefaultViewBehavior(this);
new pqAlwaysConnectedBehavior(this);
new pqPersistentMainWindowStateBehavior(mainWindow);
new TEM::ProgressBehavior(mainWindow);
// this will trigger the logic to setup reader/writer factories, etc.
pqApplicationCore::instance()->loadConfigurationXML("<xml/>");
}
//-----------------------------------------------------------------------------
Behaviors::~Behaviors()
{
}
} // end of namespace TEM
<commit_msg>Updates to build with ParaView/master.<commit_after>/******************************************************************************
This source file is part of the TEM tomography project.
Copyright Kitware, Inc.
This source code is released under the New BSD License, (the "License").
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 "Behaviors.h"
#include "pqAlwaysConnectedBehavior.h"
#include "pqApplicationCore.h"
#include "pqDefaultViewBehavior.h"
#include "pqInterfaceTracker.h"
#include "pqPersistentMainWindowStateBehavior.h"
#include "pqQtMessageHandlerBehavior.h"
#include "pqStandardPropertyWidgetInterface.h"
#include "pqStandardViewFrameActionsImplementation.h"
#include "ProgressBehavior.h"
#include <QMainWindow>
namespace TEM
{
//-----------------------------------------------------------------------------
Behaviors::Behaviors(QMainWindow* mainWindow)
{
Q_ASSERT(mainWindow);
// Register ParaView interfaces.
pqInterfaceTracker* pgm = pqApplicationCore::instance()->interfaceTracker();
// * add support for ParaView properties panel widgets.
pgm->addInterface(new pqStandardPropertyWidgetInterface(pgm));
// * register standard types of view-frame actions.
pgm->addInterface(new pqStandardViewFrameActionsImplementation(pgm));
// Load plugins distributed with application.
pqApplicationCore::instance()->loadDistributedPlugins();
new pqQtMessageHandlerBehavior(this);
new pqDefaultViewBehavior(this);
new pqAlwaysConnectedBehavior(this);
new pqPersistentMainWindowStateBehavior(mainWindow);
new TEM::ProgressBehavior(mainWindow);
// this will trigger the logic to setup reader/writer factories, etc.
pqApplicationCore::instance()->loadConfigurationXML("<xml/>");
}
//-----------------------------------------------------------------------------
Behaviors::~Behaviors()
{
}
} // end of namespace TEM
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.