text
stringlengths 54
60.6k
|
---|
<commit_before>#include <fftw3.h>
#include "common.h"
#include "metrix.h"
// Very simple. Only for even sizes.
// And for even sizes fftshift and ifftshift coinside.
template<int N> void fftshift_even(complexd data[N][N]){
complexd tmp;
for (int i = 0; i < N/2; i++) {
for (int j = 0; j < N/2; j++) {
tmp = data[i+N/2][j+N/2];
data[i+N/2][j+N/2] = data[i][j];
data[i][j] = tmp;
}
}
}
#define dp reinterpret_cast<fftw_complex*>(&data[0][0])
template<int N> void __fft_inplace(complexd data[N][N]){
fftshift_even<N>(data);
fftw_plan p = fftw_plan_dft_2d(N, N, dp, dp, FFTW_FORWARD, FFTW_ESTIMATE);
fftw_execute(p);
fftw_destroy_plan(p);
fftshift_even<N>(data);
}
extern "C"
void fft_inplace_even(complexd data[GRID_SIZE][GRID_SIZE]){
__fft_inplace<GRID_SIZE>(data);
}
<commit_msg>Try to improve FFT. Replace ifftshift with center.<commit_after>#include <fftw3.h>
#include "common.h"
#include "metrix.h"
// Very simple. Only for even sizes.
// And for even sizes fftshift and ifftshift coinside.
template<int N> void fft_center(complexd data[N][N]){
bool flip = false;
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (flip) data[i][j] = std::complex<double>(-data[i][j].real(), -data[i][j].imag());
flip = !flip;
}
}
}
template<int N> void fftshift_even(complexd data[N][N]){
complexd tmp;
for (int i = 0; i < N/2; i++) {
for (int j = 0; j < N/2; j++) {
tmp = data[i+N/2][j+N/2];
data[i+N/2][j+N/2] = data[i][j];
data[i][j] = tmp;
}
}
}
#define dp reinterpret_cast<fftw_complex*>(&data[0][0])
template<int N> void __fft_inplace(complexd data[N][N]){
fft_center<N>(data);
fftw_plan p = fftw_plan_dft_2d(N, N, dp, dp, FFTW_FORWARD, FFTW_ESTIMATE);
fftw_execute(p);
fftw_destroy_plan(p);
// Temporarily disable the shifting of the result because
// of slowness
// fftshift_even<N>(data);
}
extern "C"
void fft_inplace_even(complexd data[GRID_SIZE][GRID_SIZE]){
__fft_inplace<GRID_SIZE>(data);
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: VCartesianCoordinateSystem.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: fa $ $Date: 2004-03-08 16:03:51 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2003 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#include "VCartesianCoordinateSystem.hxx"
#include "VCartesianGrid.hxx"
#include "VCartesianAxis.hxx"
//for auto_ptr
#include <memory>
//.............................................................................
namespace chart
{
//.............................................................................
using namespace ::com::sun::star;
using namespace ::com::sun::star::chart2;
VCartesianCoordinateSystem::VCartesianCoordinateSystem( const uno::Reference< XBoundedCoordinateSystem >& xCooSys )
: VCoordinateSystem(xCooSys)
{
}
VCartesianCoordinateSystem::~VCartesianCoordinateSystem()
{
}
void VCartesianCoordinateSystem::createGridShapes()
{
sal_Int32 nDimensionCount = m_xCooSysModel->getDimension();
for( sal_Int32 nDim=0; nDim<3; nDim++)
{
uno::Sequence< uno::Reference< XGrid > >& rGridList
= getGridListByDimension( nDim );
for( sal_Int32 nN=0; nN<rGridList.getLength(); nN++ )
{
VCartesianGrid aGrid(rGridList[nN],nDimensionCount);
aGrid.setMeterData( m_aExplicitScales[nDim], m_aExplicitIncrements[nDim] );
aGrid.init(m_xLogicTargetForGrids,m_xFinalTarget,m_xShapeFactory);
if(2==nDimensionCount)
aGrid.setTransformationSceneToScreen( m_aMatrixSceneToScreen );
aGrid.setScales( m_aExplicitScales );
aGrid.createShapes();
}
}
}
void VCartesianCoordinateSystem::createAxesShapes( const awt::Size& rReferenceSize, NumberFormatterWrapper* pNumberFormatterWrapper )
{
sal_Int32 nDimensionCount = m_xCooSysModel->getDimension();
double fCoordinateOrigin[3] = { 0.0, 0.0, 0.0 };
sal_Int32 nDim = 0;
for( nDim = 0; nDim < 3; nDim++ )
fCoordinateOrigin[nDim] = this->getOriginByDimension( nDim );
for( nDim = 0; nDim < 3; nDim++ )
{
uno::Reference< XAxis > xAxis = this->getAxisByDimension(nDim);
if(!xAxis.is())
continue;
AxisProperties aAxisProperties(xAxis,rReferenceSize);
aAxisProperties.m_pfExrtaLinePositionAtOtherAxis =
new double(nDim==1?fCoordinateOrigin[0]:fCoordinateOrigin[1]);
aAxisProperties.m_bIsMainAxis = true;
aAxisProperties.init(true);
//-------------------
VCartesianAxis aAxis(aAxisProperties,pNumberFormatterWrapper,nDimensionCount);
aAxis.setMeterData( m_aExplicitScales[nDim], m_aExplicitIncrements[nDim] );
aAxis.init(m_xLogicTargetForAxes,m_xFinalTarget,m_xShapeFactory);
if(2==nDimensionCount)
aAxis.setTransformationSceneToScreen( m_aMatrixSceneToScreen );
aAxis.setScales( m_aExplicitScales );
aAxis.createShapes();
}
}
//.............................................................................
} //namespace chart
//.............................................................................
<commit_msg>INTEGRATION: CWS ooo19126 (1.4.106); FILE MERGED 2005/09/05 18:43:39 rt 1.4.106.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: VCartesianCoordinateSystem.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: rt $ $Date: 2005-09-08 01:38:30 $
*
* 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 "VCartesianCoordinateSystem.hxx"
#include "VCartesianGrid.hxx"
#include "VCartesianAxis.hxx"
//for auto_ptr
#include <memory>
//.............................................................................
namespace chart
{
//.............................................................................
using namespace ::com::sun::star;
using namespace ::com::sun::star::chart2;
VCartesianCoordinateSystem::VCartesianCoordinateSystem( const uno::Reference< XBoundedCoordinateSystem >& xCooSys )
: VCoordinateSystem(xCooSys)
{
}
VCartesianCoordinateSystem::~VCartesianCoordinateSystem()
{
}
void VCartesianCoordinateSystem::createGridShapes()
{
sal_Int32 nDimensionCount = m_xCooSysModel->getDimension();
for( sal_Int32 nDim=0; nDim<3; nDim++)
{
uno::Sequence< uno::Reference< XGrid > >& rGridList
= getGridListByDimension( nDim );
for( sal_Int32 nN=0; nN<rGridList.getLength(); nN++ )
{
VCartesianGrid aGrid(rGridList[nN],nDimensionCount);
aGrid.setMeterData( m_aExplicitScales[nDim], m_aExplicitIncrements[nDim] );
aGrid.init(m_xLogicTargetForGrids,m_xFinalTarget,m_xShapeFactory);
if(2==nDimensionCount)
aGrid.setTransformationSceneToScreen( m_aMatrixSceneToScreen );
aGrid.setScales( m_aExplicitScales );
aGrid.createShapes();
}
}
}
void VCartesianCoordinateSystem::createAxesShapes( const awt::Size& rReferenceSize, NumberFormatterWrapper* pNumberFormatterWrapper )
{
sal_Int32 nDimensionCount = m_xCooSysModel->getDimension();
double fCoordinateOrigin[3] = { 0.0, 0.0, 0.0 };
sal_Int32 nDim = 0;
for( nDim = 0; nDim < 3; nDim++ )
fCoordinateOrigin[nDim] = this->getOriginByDimension( nDim );
for( nDim = 0; nDim < 3; nDim++ )
{
uno::Reference< XAxis > xAxis = this->getAxisByDimension(nDim);
if(!xAxis.is())
continue;
AxisProperties aAxisProperties(xAxis,rReferenceSize);
aAxisProperties.m_pfExrtaLinePositionAtOtherAxis =
new double(nDim==1?fCoordinateOrigin[0]:fCoordinateOrigin[1]);
aAxisProperties.m_bIsMainAxis = true;
aAxisProperties.init(true);
//-------------------
VCartesianAxis aAxis(aAxisProperties,pNumberFormatterWrapper,nDimensionCount);
aAxis.setMeterData( m_aExplicitScales[nDim], m_aExplicitIncrements[nDim] );
aAxis.init(m_xLogicTargetForAxes,m_xFinalTarget,m_xShapeFactory);
if(2==nDimensionCount)
aAxis.setTransformationSceneToScreen( m_aMatrixSceneToScreen );
aAxis.setScales( m_aExplicitScales );
aAxis.createShapes();
}
}
//.............................................................................
} //namespace chart
//.............................................................................
<|endoftext|>
|
<commit_before>/*
* @(#)$Id$
*
* Copyright (c) 2004 Intel Corporation. All rights reserved.
*
* This file is distributed under the terms in the attached INTEL-LICENSE file.
* If you do not find these files, copies can be found by writing to:
* Intel Research Berkeley, 2150 Shattuck Avenue, Suite 1300,
* Berkeley, CA, 94704. Attention: Intel License Inquiry.
*
* DESCRIPTION: P2's concrete type system: String type.
*
*/
#include <iostream>
#include "val_str.h"
#include "val_double.h"
class OperStr : public opr::OperCompare<Val_Str> {
virtual ValuePtr _plus (const ValueRef& v1, const ValueRef& v2) const {
str s1 = Val_Str::cast(v1);
str s2 = Val_Str::cast(v2);
return Val_Str::mk((strbuf() << s2 << s1));
};
};
const opr::Oper* Val_Str::oper_ = New OperStr();
//
// Marshal a string
//
void Val_Str::xdr_marshal_subtype( XDR *x )
{
//const char *st = s.cstr();
// xdr_wrapstring(x,(char **)&st);
rpc_str<RPC_INFINITY> rs(s);
rpc_traverse(x,rs);
}
ValueRef Val_Str::xdr_unmarshal( XDR *x )
{
// Note that this looks like a yucky double copy, but at least the
// string data itself isn't copied (since rpc_str <: str).
//char *st;
//xdr_wrapstring(x,&st);
rpc_str<RPC_INFINITY> rs;
rpc_traverse(x,rs);
return mk(str(rs));
}
int Val_Str::compareTo(ValueRef other) const
{
if (other->typeCode() != Value::STR) {
return false;
}
return s.cmp(cast(other));
}
//
// Casting: we special-case doubles...
//
str Val_Str::cast(ValueRef v)
{
if (v->typeCode() == Value::DOUBLE ) {
char dbuf[100];
sprintf(dbuf,"%a",Val_Double::cast(v));
return strbuf() << dbuf;
} else {
return v->toString();
}
}
/*
* End of file
*/
<commit_msg>*** empty log message ***<commit_after>/*
* @(#)$Id$
*
* Copyright (c) 2004 Intel Corporation. All rights reserved.
*
* This file is distributed under the terms in the attached INTEL-LICENSE file.
* If you do not find these files, copies can be found by writing to:
* Intel Research Berkeley, 2150 Shattuck Avenue, Suite 1300,
* Berkeley, CA, 94704. Attention: Intel License Inquiry.
*
* DESCRIPTION: P2's concrete type system: String type.
*
*/
#include <iostream>
#include "val_str.h"
#include "val_double.h"
class OperStr : public opr::OperCompare<Val_Str> {
virtual ValuePtr _plus (const ValueRef& v1, const ValueRef& v2) const {
str s1 = Val_Str::cast(v1);
str s2 = Val_Str::cast(v2);
return Val_Str::mk((strbuf() << s1 << s2));
};
};
const opr::Oper* Val_Str::oper_ = New OperStr();
//
// Marshal a string
//
void Val_Str::xdr_marshal_subtype( XDR *x )
{
//const char *st = s.cstr();
// xdr_wrapstring(x,(char **)&st);
rpc_str<RPC_INFINITY> rs(s);
rpc_traverse(x,rs);
}
ValueRef Val_Str::xdr_unmarshal( XDR *x )
{
// Note that this looks like a yucky double copy, but at least the
// string data itself isn't copied (since rpc_str <: str).
//char *st;
//xdr_wrapstring(x,&st);
rpc_str<RPC_INFINITY> rs;
rpc_traverse(x,rs);
return mk(str(rs));
}
int Val_Str::compareTo(ValueRef other) const
{
if (other->typeCode() != Value::STR) {
return false;
}
return s.cmp(cast(other));
}
//
// Casting: we special-case doubles...
//
str Val_Str::cast(ValueRef v)
{
if (v->typeCode() == Value::DOUBLE ) {
char dbuf[100];
sprintf(dbuf,"%a",Val_Double::cast(v));
return strbuf() << dbuf;
} else {
return v->toString();
}
}
/*
* End of file
*/
<|endoftext|>
|
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/tab_contents/tab_contents_wrapper.h"
#include "base/command_line.h"
#include "base/lazy_instance.h"
#include "chrome/browser/autocomplete_history_manager.h"
#include "chrome/browser/autofill/autofill_external_delegate.h"
#include "chrome/browser/autofill/autofill_manager.h"
#include "chrome/browser/automation/automation_tab_helper.h"
#include "chrome/browser/content_settings/tab_specific_content_settings.h"
#include "chrome/browser/download/download_request_limiter_observer.h"
#include "chrome/browser/extensions/extension_tab_helper.h"
#include "chrome/browser/extensions/extension_webnavigation_api.h"
#include "chrome/browser/external_protocol/external_protocol_observer.h"
#include "chrome/browser/favicon/favicon_tab_helper.h"
#include "chrome/browser/history/history_tab_helper.h"
#include "chrome/browser/infobars/infobar_tab_helper.h"
#include "chrome/browser/omnibox_search_hint.h"
#include "chrome/browser/password_manager/password_manager.h"
#include "chrome/browser/password_manager_delegate_impl.h"
#include "chrome/browser/plugin_observer.h"
#include "chrome/browser/prerender/prerender_tab_helper.h"
#include "chrome/browser/printing/print_preview_message_handler.h"
#include "chrome/browser/printing/print_view_manager.h"
#include "chrome/browser/safe_browsing/safe_browsing_tab_observer.h"
#include "chrome/browser/sessions/restore_tab_helper.h"
#include "chrome/browser/tab_contents/tab_contents_ssl_helper.h"
#include "chrome/browser/tab_contents/thumbnail_generator.h"
#include "chrome/browser/translate/translate_tab_helper.h"
#include "chrome/browser/ui/alternate_error_tab_observer.h"
#include "chrome/browser/ui/blocked_content/blocked_content_tab_helper.h"
#include "chrome/browser/ui/bookmarks/bookmark_tab_helper.h"
#include "chrome/browser/ui/constrained_window_tab_helper.h"
#include "chrome/browser/ui/find_bar/find_tab_helper.h"
#include "chrome/browser/ui/intents/web_intent_picker_controller.h"
#include "chrome/browser/ui/pdf/pdf_tab_observer.h"
#include "chrome/browser/ui/prefs/prefs_tab_helper.h"
#include "chrome/browser/ui/sad_tab_helper.h"
#include "chrome/browser/ui/search_engines/search_engine_tab_helper.h"
#include "chrome/browser/ui/snapshot_tab_helper.h"
#include "chrome/browser/ui/sync/one_click_signin_helper.h"
#include "chrome/browser/ui/sync/tab_contents_wrapper_synced_tab_delegate.h"
#include "chrome/browser/ui/tab_contents/core_tab_helper.h"
#include "chrome/common/chrome_switches.h"
#include "content/public/browser/web_contents.h"
using content::WebContents;
namespace {
static base::LazyInstance<base::PropertyAccessor<TabContentsWrapper*> >
g_tab_contents_wrapper_property_accessor = LAZY_INSTANCE_INITIALIZER;
} // namespace
////////////////////////////////////////////////////////////////////////////////
// TabContentsWrapper, public:
TabContentsWrapper::TabContentsWrapper(WebContents* contents)
: content::WebContentsObserver(contents),
in_destructor_(false),
web_contents_(contents) {
DCHECK(contents);
DCHECK(!GetCurrentWrapperForContents(contents));
// Stash this in the property bag so it can be retrieved without having to
// go to a Browser.
property_accessor()->SetProperty(contents->GetPropertyBag(), this);
// Create the tab helpers.
autocomplete_history_manager_.reset(new AutocompleteHistoryManager(contents));
autofill_manager_ = new AutofillManager(this);
if (CommandLine::ForCurrentProcess()->HasSwitch(
switches::kExternalAutofillPopup)) {
autofill_external_delegate_.reset(
AutofillExternalDelegate::Create(this, autofill_manager_.get()));
autofill_manager_->SetExternalDelegate(autofill_external_delegate_.get());
autocomplete_history_manager_->SetExternalDelegate(
autofill_external_delegate_.get());
}
automation_tab_helper_.reset(new AutomationTabHelper(contents));
blocked_content_tab_helper_.reset(new BlockedContentTabHelper(this));
bookmark_tab_helper_.reset(new BookmarkTabHelper(this));
constrained_window_tab_helper_.reset(new ConstrainedWindowTabHelper(this));
core_tab_helper_.reset(new CoreTabHelper(contents));
extension_tab_helper_.reset(new ExtensionTabHelper(this));
favicon_tab_helper_.reset(new FaviconTabHelper(contents));
find_tab_helper_.reset(new FindTabHelper(contents));
history_tab_helper_.reset(new HistoryTabHelper(contents));
infobar_tab_helper_.reset(new InfoBarTabHelper(contents));
password_manager_delegate_.reset(new PasswordManagerDelegateImpl(this));
password_manager_.reset(
new PasswordManager(contents, password_manager_delegate_.get()));
prefs_tab_helper_.reset(new PrefsTabHelper(contents));
prerender_tab_helper_.reset(new prerender::PrerenderTabHelper(this));
restore_tab_helper_.reset(new RestoreTabHelper(contents));
sad_tab_helper_.reset(new SadTabHelper(contents));
search_engine_tab_helper_.reset(new SearchEngineTabHelper(contents));
snapshot_tab_helper_.reset(new SnapshotTabHelper(contents));
ssl_helper_.reset(new TabContentsSSLHelper(this));
synced_tab_delegate_.reset(new TabContentsWrapperSyncedTabDelegate(this));
content_settings_.reset(new TabSpecificContentSettings(contents));
translate_tab_helper_.reset(new TranslateTabHelper(contents));
web_intent_picker_controller_.reset(new WebIntentPickerController(this));
#if !defined(OS_ANDROID)
print_view_manager_.reset(new printing::PrintViewManager(this));
#endif
// Create the per-tab observers.
alternate_error_page_tab_observer_.reset(
new AlternateErrorPageTabObserver(contents));
download_request_limiter_observer_.reset(
new DownloadRequestLimiterObserver(contents));
webnavigation_observer_.reset(
new ExtensionWebNavigationTabObserver(contents));
external_protocol_observer_.reset(new ExternalProtocolObserver(contents));
if (OmniboxSearchHint::IsEnabled(profile()))
omnibox_search_hint_.reset(new OmniboxSearchHint(this));
pdf_tab_observer_.reset(new PDFTabObserver(this));
plugin_observer_.reset(new PluginObserver(this));
safe_browsing_tab_observer_.reset(
new safe_browsing::SafeBrowsingTabObserver(this));
#if !defined(OS_ANDROID)
print_preview_.reset(new printing::PrintPreviewMessageHandler(contents));
#endif
// Start the in-browser thumbnailing if the feature is enabled.
if (CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableInBrowserThumbnailing)) {
thumbnail_generation_observer_.reset(new ThumbnailGenerator);
thumbnail_generation_observer_->StartThumbnailing(web_contents_.get());
}
// If this is not an incognito window, setup to handle one-click login.
#if defined(ENABLE_ONE_CLICK_SIGNIN)
if (OneClickSigninHelper::CanOffer(contents))
one_click_signin_helper_.reset(new OneClickSigninHelper(contents));
#endif
}
TabContentsWrapper::~TabContentsWrapper() {
in_destructor_ = true;
// Need to tear down infobars before the TabContents goes away.
// TODO(avi): Can we get this handled by the tab helper itself?
infobar_tab_helper_.reset();
}
base::PropertyAccessor<TabContentsWrapper*>*
TabContentsWrapper::property_accessor() {
return g_tab_contents_wrapper_property_accessor.Pointer();
}
TabContentsWrapper* TabContentsWrapper::Clone() {
WebContents* new_contents = web_contents()->Clone();
TabContentsWrapper* new_wrapper = new TabContentsWrapper(new_contents);
// TODO(avi): Can we generalize this so that knowledge of the functionings of
// the tab helpers isn't required here?
new_wrapper->extension_tab_helper()->CopyStateFrom(
*extension_tab_helper_.get());
return new_wrapper;
}
// static
TabContentsWrapper* TabContentsWrapper::GetCurrentWrapperForContents(
WebContents* contents) {
TabContentsWrapper** wrapper =
property_accessor()->GetProperty(contents->GetPropertyBag());
return wrapper ? *wrapper : NULL;
}
// static
const TabContentsWrapper* TabContentsWrapper::GetCurrentWrapperForContents(
const WebContents* contents) {
TabContentsWrapper* const* wrapper =
property_accessor()->GetProperty(contents->GetPropertyBag());
return wrapper ? *wrapper : NULL;
}
WebContents* TabContentsWrapper::web_contents() const {
return web_contents_.get();
}
Profile* TabContentsWrapper::profile() const {
return Profile::FromBrowserContext(web_contents()->GetBrowserContext());
}
////////////////////////////////////////////////////////////////////////////////
// WebContentsObserver overrides
void TabContentsWrapper::WebContentsDestroyed(WebContents* tab) {
// Destruction of the WebContents should only be done by us from our
// destructor. Otherwise it's very likely we (or one of the helpers we own)
// will attempt to access the TabContents and we'll crash.
DCHECK(in_destructor_);
}
<commit_msg>Fix link error in TabContentsWrapper.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/tab_contents/tab_contents_wrapper.h"
#include "base/command_line.h"
#include "base/lazy_instance.h"
#include "chrome/browser/autocomplete_history_manager.h"
#include "chrome/browser/autofill/autofill_external_delegate.h"
#include "chrome/browser/autofill/autofill_manager.h"
#include "chrome/browser/automation/automation_tab_helper.h"
#include "chrome/browser/content_settings/tab_specific_content_settings.h"
#include "chrome/browser/download/download_request_limiter_observer.h"
#include "chrome/browser/extensions/extension_tab_helper.h"
#include "chrome/browser/extensions/extension_webnavigation_api.h"
#include "chrome/browser/external_protocol/external_protocol_observer.h"
#include "chrome/browser/favicon/favicon_tab_helper.h"
#include "chrome/browser/history/history_tab_helper.h"
#include "chrome/browser/infobars/infobar_tab_helper.h"
#include "chrome/browser/omnibox_search_hint.h"
#include "chrome/browser/password_manager/password_manager.h"
#include "chrome/browser/password_manager_delegate_impl.h"
#include "chrome/browser/plugin_observer.h"
#include "chrome/browser/prerender/prerender_tab_helper.h"
#include "chrome/browser/printing/print_preview_message_handler.h"
#include "chrome/browser/printing/print_view_manager.h"
#include "chrome/browser/safe_browsing/safe_browsing_tab_observer.h"
#include "chrome/browser/sessions/restore_tab_helper.h"
#include "chrome/browser/tab_contents/tab_contents_ssl_helper.h"
#include "chrome/browser/tab_contents/thumbnail_generator.h"
#include "chrome/browser/translate/translate_tab_helper.h"
#include "chrome/browser/ui/alternate_error_tab_observer.h"
#include "chrome/browser/ui/blocked_content/blocked_content_tab_helper.h"
#include "chrome/browser/ui/bookmarks/bookmark_tab_helper.h"
#include "chrome/browser/ui/constrained_window_tab_helper.h"
#include "chrome/browser/ui/find_bar/find_tab_helper.h"
#include "chrome/browser/ui/intents/web_intent_picker_controller.h"
#include "chrome/browser/ui/pdf/pdf_tab_observer.h"
#include "chrome/browser/ui/prefs/prefs_tab_helper.h"
#include "chrome/browser/ui/sad_tab_helper.h"
#include "chrome/browser/ui/search_engines/search_engine_tab_helper.h"
#include "chrome/browser/ui/snapshot_tab_helper.h"
#include "chrome/browser/ui/sync/one_click_signin_helper.h"
#include "chrome/browser/ui/sync/tab_contents_wrapper_synced_tab_delegate.h"
#include "chrome/browser/ui/tab_contents/core_tab_helper.h"
#include "chrome/common/chrome_switches.h"
#include "content/public/browser/web_contents.h"
using content::WebContents;
namespace {
static base::LazyInstance<base::PropertyAccessor<TabContentsWrapper*> >
g_tab_contents_wrapper_property_accessor = LAZY_INSTANCE_INITIALIZER;
} // namespace
////////////////////////////////////////////////////////////////////////////////
// TabContentsWrapper, public:
TabContentsWrapper::TabContentsWrapper(WebContents* contents)
: content::WebContentsObserver(contents),
in_destructor_(false),
web_contents_(contents) {
DCHECK(contents);
DCHECK(!GetCurrentWrapperForContents(contents));
// Stash this in the property bag so it can be retrieved without having to
// go to a Browser.
property_accessor()->SetProperty(contents->GetPropertyBag(), this);
// Create the tab helpers.
autocomplete_history_manager_.reset(new AutocompleteHistoryManager(contents));
autofill_manager_ = new AutofillManager(this);
if (CommandLine::ForCurrentProcess()->HasSwitch(
switches::kExternalAutofillPopup)) {
autofill_external_delegate_.reset(
AutofillExternalDelegate::Create(this, autofill_manager_.get()));
autofill_manager_->SetExternalDelegate(autofill_external_delegate_.get());
autocomplete_history_manager_->SetExternalDelegate(
autofill_external_delegate_.get());
}
automation_tab_helper_.reset(new AutomationTabHelper(contents));
blocked_content_tab_helper_.reset(new BlockedContentTabHelper(this));
bookmark_tab_helper_.reset(new BookmarkTabHelper(this));
constrained_window_tab_helper_.reset(new ConstrainedWindowTabHelper(this));
core_tab_helper_.reset(new CoreTabHelper(contents));
extension_tab_helper_.reset(new ExtensionTabHelper(this));
favicon_tab_helper_.reset(new FaviconTabHelper(contents));
find_tab_helper_.reset(new FindTabHelper(contents));
history_tab_helper_.reset(new HistoryTabHelper(contents));
infobar_tab_helper_.reset(new InfoBarTabHelper(contents));
password_manager_delegate_.reset(new PasswordManagerDelegateImpl(this));
password_manager_.reset(
new PasswordManager(contents, password_manager_delegate_.get()));
prefs_tab_helper_.reset(new PrefsTabHelper(contents));
prerender_tab_helper_.reset(new prerender::PrerenderTabHelper(this));
restore_tab_helper_.reset(new RestoreTabHelper(contents));
search_engine_tab_helper_.reset(new SearchEngineTabHelper(contents));
snapshot_tab_helper_.reset(new SnapshotTabHelper(contents));
ssl_helper_.reset(new TabContentsSSLHelper(this));
synced_tab_delegate_.reset(new TabContentsWrapperSyncedTabDelegate(this));
content_settings_.reset(new TabSpecificContentSettings(contents));
translate_tab_helper_.reset(new TranslateTabHelper(contents));
web_intent_picker_controller_.reset(new WebIntentPickerController(this));
#if !defined(OS_ANDROID)
print_view_manager_.reset(new printing::PrintViewManager(this));
sad_tab_helper_.reset(new SadTabHelper(contents));
#endif
// Create the per-tab observers.
alternate_error_page_tab_observer_.reset(
new AlternateErrorPageTabObserver(contents));
download_request_limiter_observer_.reset(
new DownloadRequestLimiterObserver(contents));
webnavigation_observer_.reset(
new ExtensionWebNavigationTabObserver(contents));
external_protocol_observer_.reset(new ExternalProtocolObserver(contents));
if (OmniboxSearchHint::IsEnabled(profile()))
omnibox_search_hint_.reset(new OmniboxSearchHint(this));
pdf_tab_observer_.reset(new PDFTabObserver(this));
plugin_observer_.reset(new PluginObserver(this));
safe_browsing_tab_observer_.reset(
new safe_browsing::SafeBrowsingTabObserver(this));
#if !defined(OS_ANDROID)
print_preview_.reset(new printing::PrintPreviewMessageHandler(contents));
#endif
// Start the in-browser thumbnailing if the feature is enabled.
if (CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableInBrowserThumbnailing)) {
thumbnail_generation_observer_.reset(new ThumbnailGenerator);
thumbnail_generation_observer_->StartThumbnailing(web_contents_.get());
}
// If this is not an incognito window, setup to handle one-click login.
#if defined(ENABLE_ONE_CLICK_SIGNIN)
if (OneClickSigninHelper::CanOffer(contents))
one_click_signin_helper_.reset(new OneClickSigninHelper(contents));
#endif
}
TabContentsWrapper::~TabContentsWrapper() {
in_destructor_ = true;
// Need to tear down infobars before the TabContents goes away.
// TODO(avi): Can we get this handled by the tab helper itself?
infobar_tab_helper_.reset();
}
base::PropertyAccessor<TabContentsWrapper*>*
TabContentsWrapper::property_accessor() {
return g_tab_contents_wrapper_property_accessor.Pointer();
}
TabContentsWrapper* TabContentsWrapper::Clone() {
WebContents* new_contents = web_contents()->Clone();
TabContentsWrapper* new_wrapper = new TabContentsWrapper(new_contents);
// TODO(avi): Can we generalize this so that knowledge of the functionings of
// the tab helpers isn't required here?
new_wrapper->extension_tab_helper()->CopyStateFrom(
*extension_tab_helper_.get());
return new_wrapper;
}
// static
TabContentsWrapper* TabContentsWrapper::GetCurrentWrapperForContents(
WebContents* contents) {
TabContentsWrapper** wrapper =
property_accessor()->GetProperty(contents->GetPropertyBag());
return wrapper ? *wrapper : NULL;
}
// static
const TabContentsWrapper* TabContentsWrapper::GetCurrentWrapperForContents(
const WebContents* contents) {
TabContentsWrapper* const* wrapper =
property_accessor()->GetProperty(contents->GetPropertyBag());
return wrapper ? *wrapper : NULL;
}
WebContents* TabContentsWrapper::web_contents() const {
return web_contents_.get();
}
Profile* TabContentsWrapper::profile() const {
return Profile::FromBrowserContext(web_contents()->GetBrowserContext());
}
////////////////////////////////////////////////////////////////////////////////
// WebContentsObserver overrides
void TabContentsWrapper::WebContentsDestroyed(WebContents* tab) {
// Destruction of the WebContents should only be done by us from our
// destructor. Otherwise it's very likely we (or one of the helpers we own)
// will attempt to access the TabContents and we'll crash.
DCHECK(in_destructor_);
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/login/signed_settings_cache.h"
#include <string>
#include "base/base64.h"
#include "base/bind.h"
#include "chrome/browser/chromeos/cros_settings.h"
#include "chrome/browser/chromeos/login/ownership_service.h"
#include "chrome/browser/chromeos/login/ownership_status_checker.h"
#include "chrome/browser/chromeos/login/signed_settings_helper.h"
#include "chrome/browser/policy/proto/device_management_backend.pb.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/common/pref_names.h"
using content::BrowserThread;
namespace em = enterprise_management;
namespace chromeos {
namespace {
void OnStorePolicyCompleted(SignedSettings::ReturnCode code) {
if (code != SignedSettings::SUCCESS)
LOG(ERROR) << "Couldn't save temp store to the policy blob. code: " << code;
else
CrosSettings::Get()->ReloadProviders();
}
void FinishFinalize(PrefService* local_state,
SignedSettings::ReturnCode code,
const em::PolicyFetchResponse& policy) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (code != SignedSettings::SUCCESS) {
LOG(ERROR) << "Can't finalize temp store error code:" << code;
return;
}
if (local_state) {
std::string encoded =
local_state->GetString(prefs::kSignedSettingsCache);
std::string policy_string;
if (!base::Base64Decode(encoded, &policy_string)) {
LOG(WARNING) << "Can't decode policy from base64 on finalizing.";
return;
}
em::PolicyData merging_policy_data;
if (!merging_policy_data.ParseFromString(policy_string)) {
LOG(WARNING) << "Can't decode policy from string on finalizing.";
return;
}
em::PolicyFetchResponse policy_envelope = policy;
DCHECK(policy_envelope.has_policy_data());
em::PolicyData base_policy_data;
base_policy_data.ParseFromString(policy_envelope.policy_data());
// Merge only the policy value as we should never ever rewrite the other
// fields of the PolicyData protobuf.
base_policy_data.set_policy_value(merging_policy_data.policy_value());
policy_envelope.set_policy_data(base_policy_data.SerializeAsString());
DCHECK(base_policy_data.has_username());
policy_envelope.clear_policy_data_signature();
SignedSettingsHelper::Get()->StartStorePolicyOp(
policy_envelope, base::Bind(&OnStorePolicyCompleted));
}
}
// Reload the initial policy blob, and if successful apply the settings from
// temp storage, and write them back the blob in FinishFinalize.
void ReloadSignedSettingsAndFinalize(
PrefService* local_state,
OwnershipStatusChecker* ownership_checker,
OwnershipService::Status status,
bool current_user_is_owner) {
if (current_user_is_owner) {
SignedSettingsHelper::Get()->StartRetrievePolicyOp(
base::Bind(FinishFinalize, local_state));
}
delete ownership_checker;
}
} // namespace
namespace signed_settings_cache {
void RegisterPrefs(PrefService* local_state) {
local_state->RegisterStringPref(prefs::kSignedSettingsCache,
"invalid",
PrefService::UNSYNCABLE_PREF);
}
bool Store(const em::PolicyData& policy, PrefService* local_state) {
if (local_state) {
std::string policy_string = policy.SerializeAsString();
std::string encoded;
if (!base::Base64Encode(policy_string, &encoded)) {
LOG(WARNING) << "Can't encode policy in base64.";
return false;
}
local_state->SetString(prefs::kSignedSettingsCache, encoded);
return true;
}
return false;
}
bool Retrieve(em::PolicyData *policy, PrefService* local_state) {
if (local_state) {
std::string encoded =
local_state->GetString(prefs::kSignedSettingsCache);
std::string policy_string;
if (!base::Base64Decode(encoded, &policy_string)) {
LOG(WARNING) << "Can't decode policy from base64.";
return false;
}
return policy->ParseFromString(policy_string);
}
return false;
}
void Finalize(PrefService* local_state) {
// First we have to make sure the owner is really logged in because the key
// notification is generated on every cloud policy key rotation too.
OwnershipStatusChecker* ownership_checker = new OwnershipStatusChecker();
ownership_checker->Check(base::Bind(&ReloadSignedSettingsAndFinalize,
local_state, ownership_checker));
}
} // namespace signed_settings_cache
} // namespace chromeos
<commit_msg>Change the levels of the debug output of the SignedSettingsCache.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/login/signed_settings_cache.h"
#include <string>
#include "base/base64.h"
#include "base/bind.h"
#include "chrome/browser/chromeos/cros_settings.h"
#include "chrome/browser/chromeos/login/ownership_service.h"
#include "chrome/browser/chromeos/login/ownership_status_checker.h"
#include "chrome/browser/chromeos/login/signed_settings_helper.h"
#include "chrome/browser/policy/proto/device_management_backend.pb.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/common/pref_names.h"
using content::BrowserThread;
namespace em = enterprise_management;
namespace chromeos {
namespace {
void OnStorePolicyCompleted(SignedSettings::ReturnCode code) {
if (code != SignedSettings::SUCCESS)
LOG(ERROR) << "Couldn't save temp store to the policy blob. code: " << code;
else
CrosSettings::Get()->ReloadProviders();
}
void FinishFinalize(PrefService* local_state,
SignedSettings::ReturnCode code,
const em::PolicyFetchResponse& policy) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (code != SignedSettings::SUCCESS) {
LOG(ERROR) << "Can't finalize temp store error code:" << code;
return;
}
if (local_state) {
std::string encoded =
local_state->GetString(prefs::kSignedSettingsCache);
std::string policy_string;
if (!base::Base64Decode(encoded, &policy_string)) {
LOG(ERROR) << "Can't decode policy from base64 on finalizing.";
return;
}
em::PolicyData merging_policy_data;
if (!merging_policy_data.ParseFromString(policy_string)) {
LOG(ERROR) << "Can't decode policy from string on finalizing.";
return;
}
em::PolicyFetchResponse policy_envelope = policy;
DCHECK(policy_envelope.has_policy_data());
em::PolicyData base_policy_data;
base_policy_data.ParseFromString(policy_envelope.policy_data());
// Merge only the policy value as we should never ever rewrite the other
// fields of the PolicyData protobuf.
base_policy_data.set_policy_value(merging_policy_data.policy_value());
policy_envelope.set_policy_data(base_policy_data.SerializeAsString());
DCHECK(base_policy_data.has_username());
policy_envelope.clear_policy_data_signature();
SignedSettingsHelper::Get()->StartStorePolicyOp(
policy_envelope, base::Bind(&OnStorePolicyCompleted));
}
}
// Reload the initial policy blob, and if successful apply the settings from
// temp storage, and write them back the blob in FinishFinalize.
void ReloadSignedSettingsAndFinalize(
PrefService* local_state,
OwnershipStatusChecker* ownership_checker,
OwnershipService::Status status,
bool current_user_is_owner) {
if (current_user_is_owner) {
SignedSettingsHelper::Get()->StartRetrievePolicyOp(
base::Bind(FinishFinalize, local_state));
}
delete ownership_checker;
}
} // namespace
namespace signed_settings_cache {
void RegisterPrefs(PrefService* local_state) {
local_state->RegisterStringPref(prefs::kSignedSettingsCache,
"invalid",
PrefService::UNSYNCABLE_PREF);
}
bool Store(const em::PolicyData& policy, PrefService* local_state) {
if (local_state) {
std::string policy_string = policy.SerializeAsString();
std::string encoded;
if (!base::Base64Encode(policy_string, &encoded)) {
LOG(ERROR) << "Can't encode policy in base64.";
return false;
}
local_state->SetString(prefs::kSignedSettingsCache, encoded);
return true;
}
return false;
}
bool Retrieve(em::PolicyData *policy, PrefService* local_state) {
if (local_state) {
std::string encoded =
local_state->GetString(prefs::kSignedSettingsCache);
std::string policy_string;
if (!base::Base64Decode(encoded, &policy_string)) {
// This is normal and happens on first boot.
VLOG(1) << "Can't decode policy from base64.";
return false;
}
return policy->ParseFromString(policy_string);
}
return false;
}
void Finalize(PrefService* local_state) {
// First we have to make sure the owner is really logged in because the key
// notification is generated on every cloud policy key rotation too.
OwnershipStatusChecker* ownership_checker = new OwnershipStatusChecker();
ownership_checker->Check(base::Bind(&ReloadSignedSettingsAndFinalize,
local_state, ownership_checker));
}
} // namespace signed_settings_cache
} // namespace chromeos
<|endoftext|>
|
<commit_before>// Copyright 2021 The XLS Authors
//
// 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.
// This file contains the main function (entry point) of the xlscc
// front-end. It accepts as input a C/C++ file and produces as textual output
// the equivalent XLS intermediate representation (IR).
#include <cstdlib>
#include <fstream>
#include <streambuf>
#include "absl/flags/flag.h"
#include "absl/status/status.h"
#include "absl/strings/str_format.h"
#include "absl/strings/str_split.h"
#include "xls/common/file/filesystem.h"
#include "xls/common/init_xls.h"
#include "xls/common/logging/log_flags.h"
#include "xls/common/logging/logging.h"
#include "xls/common/status/status_macros.h"
#include "xls/contrib/xlscc/hls_block.pb.h"
#include "xls/contrib/xlscc/metadata_output.pb.h"
#include "xls/contrib/xlscc/translator.h"
const char kUsage[] = R"(
Generates XLS IR from a given C++ file, or generates Verilog in the special
case of a combinational module.
Emit XLS IR:
xlscc foo.cc
Emit combinational Verilog module:
xlscc foo.cc --block_pb block_info.pb
)";
ABSL_FLAG(std::string, out, "",
"Path at which to output verilog / IR. Stdout if not specified.");
ABSL_FLAG(std::string, block_pb, "",
"HLSBlock protobuf for generating as HLS block / XLS proc");
ABSL_FLAG(std::string, top, "", "Top function name");
ABSL_FLAG(std::string, package, "", "Package name to generate");
ABSL_FLAG(std::string, clang_args_file, "",
"File containing on each line one command line argument for clang");
ABSL_FLAG(std::vector<std::string>, defines, std::vector<std::string>(),
"Comma separated list of defines to pass to clang");
ABSL_FLAG(std::vector<std::string>, include_dirs, std::vector<std::string>(),
"Comma separated list of include directories to pass to clang");
ABSL_FLAG(std::string, meta_out, "",
"Path at which to output metadata protobuf");
ABSL_FLAG(bool, meta_out_text, false, "Output metadata as textproto?");
ABSL_FLAG(std::string, verilog_line_map_out, "",
"Path at which to output Verilog line map protobuf");
ABSL_FLAG(bool, error_on_init_interval, false,
"Generate an error when an initiation interval is requested greater "
"than supported");
ABSL_FLAG(int, top_level_init_interval, 1,
"Initiation interval of block top level (Run/main function)");
ABSL_FLAG(int, max_unroll_iters, 1000,
"Maximum number of iterations to allow loops to be unrolled");
ABSL_FLAG(int, warn_unroll_iters, 100,
"Maximum number of iterations to allow loops to be unrolled");
namespace xlscc {
absl::Status Run(absl::string_view cpp_path) {
// Warnings should print by default
absl::SetFlag(&FLAGS_logtostderr, true);
xlscc::Translator translator(absl::GetFlag(FLAGS_error_on_init_interval),
absl::GetFlag(FLAGS_max_unroll_iters),
absl::GetFlag(FLAGS_warn_unroll_iters));
const std::string block_pb_name = absl::GetFlag(FLAGS_block_pb);
HLSBlock block;
if (!block_pb_name.empty()) {
std::ifstream file_in(block_pb_name);
if (!block.ParseFromIstream(&file_in)) {
return absl::InvalidArgumentError("Couldn't parse protobuf");
}
}
const std::string top_function_name = absl::GetFlag(FLAGS_top);
if (!top_function_name.empty()) {
XLS_RETURN_IF_ERROR(translator.SelectTop(top_function_name));
}
std::vector<std::string> clang_argvs;
const std::string clang_args_file = absl::GetFlag(FLAGS_clang_args_file);
if (!clang_args_file.empty()) {
XLS_ASSIGN_OR_RETURN(std::string clang_args_content,
xls::GetFileContents(clang_args_file));
for (auto arg :
absl::StrSplit(clang_args_content, '\n', absl::SkipWhitespace())) {
clang_argvs.push_back(std::string(absl::StripAsciiWhitespace(arg)));
}
}
for (std::string& def : absl::GetFlag(FLAGS_defines)) {
clang_argvs.push_back(absl::StrCat("-D", def));
}
for (std::string& dir : absl::GetFlag(FLAGS_include_dirs)) {
clang_argvs.push_back(absl::StrCat("-I", dir));
}
std::vector<absl::string_view> clang_argv;
for (size_t i = 0; i < clang_argvs.size(); ++i) {
clang_argv.push_back(clang_argvs[i]);
}
std::cerr << "Parsing file '" << cpp_path << "' with clang..." << std::endl;
XLS_RETURN_IF_ERROR(translator.ScanFile(
cpp_path, clang_argv.empty()
? absl::Span<absl::string_view>()
: absl::MakeSpan(&clang_argv[0], clang_argv.size())));
XLS_ASSIGN_OR_RETURN(std::string top_name, translator.GetEntryFunctionName());
std::string package_name = absl::GetFlag(FLAGS_package);
if (package_name.empty()) {
package_name = "my_package";
}
std::filesystem::path output_file(absl::GetFlag(FLAGS_out));
std::filesystem::path output_absolute = output_file;
if (output_file.is_relative()) {
XLS_ASSIGN_OR_RETURN(std::filesystem::path cwd, xls::GetCurrentDirectory());
output_absolute = cwd / output_file;
}
auto write_to_output = [&](absl::string_view output) -> absl::Status {
if (output_file.empty()) {
std::cout << output;
} else {
XLS_RETURN_IF_ERROR(xls::SetFileContents(output_file, output));
}
return absl::OkStatus();
};
std::cerr << "Generating IR..." << std::endl;
xls::Package package(package_name);
if (block_pb_name.empty()) {
XLS_RETURN_IF_ERROR(translator.GenerateIR_Top_Function(&package).status());
// TODO(seanhaskell): Simplify IR
XLS_RETURN_IF_ERROR(package.SetTopByName(top_name));
translator.AddSourceInfoToPackage(package);
XLS_RETURN_IF_ERROR(write_to_output(absl::StrCat(package.DumpIr(), "\n")));
} else {
XLS_ASSIGN_OR_RETURN(
xls::Proc * proc,
translator.GenerateIR_Block(
&package, block, absl::GetFlag(FLAGS_top_level_init_interval)));
XLS_RETURN_IF_ERROR(package.SetTop(proc));
std::cerr << "Saving Package IR..." << std::endl;
translator.AddSourceInfoToPackage(package);
XLS_RETURN_IF_ERROR(write_to_output(absl::StrCat(package.DumpIr(), "\n")));
}
const std::string metadata_out_path = absl::GetFlag(FLAGS_meta_out);
if (!metadata_out_path.empty()) {
XLS_ASSIGN_OR_RETURN(xlscc_metadata::MetadataOutput meta,
translator.GenerateMetadata());
if (absl::GetFlag(FLAGS_meta_out_text)) {
XLS_RETURN_IF_ERROR(xls::SetTextProtoFile(metadata_out_path, meta));
} else {
std::ofstream ostr(metadata_out_path);
if (!ostr.good()) {
return absl::NotFoundError(absl::StrFormat(
"Couldn't open metadata output path: %s", metadata_out_path));
}
if (!meta.SerializeToOstream(&ostr)) {
return absl::UnknownError("Error writing metadata proto");
}
}
}
return absl::OkStatus();
}
} // namespace xlscc
int main(int argc, char** argv) {
std::vector<absl::string_view> positional_arguments =
xls::InitXls(kUsage, argc, argv);
if (positional_arguments.size() != 1) {
XLS_LOG(QFATAL) << absl::StreamFormat("Expected invocation: %s CPP_FILE",
argv[0]);
}
absl::string_view cpp_path = positional_arguments[0];
// XLS_QCHECK_OK(xlscc::Run(cpp_path));
absl::Status status = xlscc::Run(cpp_path);
if (!status.ok()) {
std::cerr << status.ToString() << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<commit_msg>Add --block_pb_text to xlscc for inputting text protos.<commit_after>// Copyright 2021 The XLS Authors
//
// 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.
// This file contains the main function (entry point) of the xlscc
// front-end. It accepts as input a C/C++ file and produces as textual output
// the equivalent XLS intermediate representation (IR).
#include <cstdlib>
#include <fstream>
#include <streambuf>
#include "absl/flags/flag.h"
#include "absl/status/status.h"
#include "absl/strings/str_format.h"
#include "absl/strings/str_split.h"
#include "xls/common/file/filesystem.h"
#include "xls/common/init_xls.h"
#include "xls/common/logging/log_flags.h"
#include "xls/common/logging/logging.h"
#include "xls/common/status/status_macros.h"
#include "xls/contrib/xlscc/hls_block.pb.h"
#include "xls/contrib/xlscc/metadata_output.pb.h"
#include "xls/contrib/xlscc/translator.h"
const char kUsage[] = R"(
Generates XLS IR from a given C++ file, or generates Verilog in the special
case of a combinational module.
Emit XLS IR:
xlscc foo.cc
Emit combinational Verilog module:
xlscc foo.cc --block_pb block_info.pb
)";
ABSL_FLAG(std::string, out, "",
"Path at which to output verilog / IR. Stdout if not specified.");
ABSL_FLAG(std::string, block_pb, "",
"HLSBlock protobuf for generating as HLS block / XLS proc");
ABSL_FLAG(bool, block_pb_text, false, "Input HLSBlock protobuf as textproto?");
ABSL_FLAG(std::string, top, "", "Top function name");
ABSL_FLAG(std::string, package, "", "Package name to generate");
ABSL_FLAG(std::string, clang_args_file, "",
"File containing on each line one command line argument for clang");
ABSL_FLAG(std::vector<std::string>, defines, std::vector<std::string>(),
"Comma separated list of defines to pass to clang");
ABSL_FLAG(std::vector<std::string>, include_dirs, std::vector<std::string>(),
"Comma separated list of include directories to pass to clang");
ABSL_FLAG(std::string, meta_out, "",
"Path at which to output metadata protobuf");
ABSL_FLAG(bool, meta_out_text, false, "Output metadata as textproto?");
ABSL_FLAG(std::string, verilog_line_map_out, "",
"Path at which to output Verilog line map protobuf");
ABSL_FLAG(bool, error_on_init_interval, false,
"Generate an error when an initiation interval is requested greater "
"than supported");
ABSL_FLAG(int, top_level_init_interval, 1,
"Initiation interval of block top level (Run/main function)");
ABSL_FLAG(int, max_unroll_iters, 1000,
"Maximum number of iterations to allow loops to be unrolled");
ABSL_FLAG(int, warn_unroll_iters, 100,
"Maximum number of iterations to allow loops to be unrolled");
namespace xlscc {
absl::Status Run(absl::string_view cpp_path) {
// Warnings should print by default
absl::SetFlag(&FLAGS_logtostderr, true);
xlscc::Translator translator(absl::GetFlag(FLAGS_error_on_init_interval),
absl::GetFlag(FLAGS_max_unroll_iters),
absl::GetFlag(FLAGS_warn_unroll_iters));
const std::string block_pb_name = absl::GetFlag(FLAGS_block_pb);
HLSBlock block;
if (!block_pb_name.empty()) {
if (!absl::GetFlag(FLAGS_block_pb_text)) {
std::ifstream file_in(block_pb_name);
if (!block.ParseFromIstream(&file_in)) {
return absl::InvalidArgumentError("Couldn't parse protobuf");
}
} else {
XLS_RETURN_IF_ERROR(xls::ParseTextProtoFile(block_pb_name, &block));
}
}
const std::string top_function_name = absl::GetFlag(FLAGS_top);
if (!top_function_name.empty()) {
XLS_RETURN_IF_ERROR(translator.SelectTop(top_function_name));
}
std::vector<std::string> clang_argvs;
const std::string clang_args_file = absl::GetFlag(FLAGS_clang_args_file);
if (!clang_args_file.empty()) {
XLS_ASSIGN_OR_RETURN(std::string clang_args_content,
xls::GetFileContents(clang_args_file));
for (auto arg :
absl::StrSplit(clang_args_content, '\n', absl::SkipWhitespace())) {
clang_argvs.push_back(std::string(absl::StripAsciiWhitespace(arg)));
}
}
for (std::string& def : absl::GetFlag(FLAGS_defines)) {
clang_argvs.push_back(absl::StrCat("-D", def));
}
for (std::string& dir : absl::GetFlag(FLAGS_include_dirs)) {
clang_argvs.push_back(absl::StrCat("-I", dir));
}
std::vector<absl::string_view> clang_argv;
for (size_t i = 0; i < clang_argvs.size(); ++i) {
clang_argv.push_back(clang_argvs[i]);
}
std::cerr << "Parsing file '" << cpp_path << "' with clang..." << std::endl;
XLS_RETURN_IF_ERROR(translator.ScanFile(
cpp_path, clang_argv.empty()
? absl::Span<absl::string_view>()
: absl::MakeSpan(&clang_argv[0], clang_argv.size())));
XLS_ASSIGN_OR_RETURN(std::string top_name, translator.GetEntryFunctionName());
std::string package_name = absl::GetFlag(FLAGS_package);
if (package_name.empty()) {
package_name = "my_package";
}
std::filesystem::path output_file(absl::GetFlag(FLAGS_out));
std::filesystem::path output_absolute = output_file;
if (output_file.is_relative()) {
XLS_ASSIGN_OR_RETURN(std::filesystem::path cwd, xls::GetCurrentDirectory());
output_absolute = cwd / output_file;
}
auto write_to_output = [&](absl::string_view output) -> absl::Status {
if (output_file.empty()) {
std::cout << output;
} else {
XLS_RETURN_IF_ERROR(xls::SetFileContents(output_file, output));
}
return absl::OkStatus();
};
std::cerr << "Generating IR..." << std::endl;
xls::Package package(package_name);
if (block_pb_name.empty()) {
XLS_RETURN_IF_ERROR(translator.GenerateIR_Top_Function(&package).status());
// TODO(seanhaskell): Simplify IR
XLS_RETURN_IF_ERROR(package.SetTopByName(top_name));
translator.AddSourceInfoToPackage(package);
XLS_RETURN_IF_ERROR(write_to_output(absl::StrCat(package.DumpIr(), "\n")));
} else {
XLS_ASSIGN_OR_RETURN(
xls::Proc * proc,
translator.GenerateIR_Block(
&package, block, absl::GetFlag(FLAGS_top_level_init_interval)));
XLS_RETURN_IF_ERROR(package.SetTop(proc));
std::cerr << "Saving Package IR..." << std::endl;
translator.AddSourceInfoToPackage(package);
XLS_RETURN_IF_ERROR(write_to_output(absl::StrCat(package.DumpIr(), "\n")));
}
const std::string metadata_out_path = absl::GetFlag(FLAGS_meta_out);
if (!metadata_out_path.empty()) {
XLS_ASSIGN_OR_RETURN(xlscc_metadata::MetadataOutput meta,
translator.GenerateMetadata());
if (absl::GetFlag(FLAGS_meta_out_text)) {
XLS_RETURN_IF_ERROR(xls::SetTextProtoFile(metadata_out_path, meta));
} else {
std::ofstream ostr(metadata_out_path);
if (!ostr.good()) {
return absl::NotFoundError(absl::StrFormat(
"Couldn't open metadata output path: %s", metadata_out_path));
}
if (!meta.SerializeToOstream(&ostr)) {
return absl::UnknownError("Error writing metadata proto");
}
}
}
return absl::OkStatus();
}
} // namespace xlscc
int main(int argc, char** argv) {
std::vector<absl::string_view> positional_arguments =
xls::InitXls(kUsage, argc, argv);
if (positional_arguments.size() != 1) {
XLS_LOG(QFATAL) << absl::StreamFormat("Expected invocation: %s CPP_FILE",
argv[0]);
}
absl::string_view cpp_path = positional_arguments[0];
// XLS_QCHECK_OK(xlscc::Run(cpp_path));
absl::Status status = xlscc::Run(cpp_path);
if (!status.ok()) {
std::cerr << status.ToString() << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "dialogopen.h"
#include "dialognew.h"
#include <QDirModel>
#include <QFileDialog>
#include <QProgressDialog>
#include <QDebug>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
// Setup the UI
ui->setupUi(this);
// Setup history stuff
folderHistory = new QStack<QString>();
folderForwardHistory = new QStack<QString>();
// Create the partition safe instance
psInstance = new PartitionSafe();
// Setup models
model = new PSFileSystemModel(this, psInstance);
modelDirs = new PSFileSystemModel(this, psInstance);
#ifdef QT_DEBUG
// Debug mode only, load a default vault
initializeVault("/tmp/marc.vault", "/tmp/marc.keystore");
// Show path in status bar
this->setPath();
#endif
}
MainWindow::~MainWindow()
{
delete ui;
delete folderHistory;
delete folderForwardHistory;
delete model;
delete modelDirs;
}
void MainWindow::on_treeViewExplorer_doubleClicked(const QModelIndex &index)
{
// We should get the selected item
Entry* item = model->getFile(index);
// Only continue if it's a directory
if(!item->isDirectory()) return;
// Get the path
QString path = QString(item->getFullPath().c_str());
// Enter given directory and add to history
model->enterDirectory(path, *folderHistory, *folderForwardHistory);
// Show path in status bar
this->setPath();
}
void MainWindow::on_buttonBack_clicked()
{
model->navigation_buttons(*folderHistory, *folderForwardHistory);
// Show path in status bar
this->setPath();
}
void MainWindow::on_buttonForward_clicked()
{
model->navigation_buttons(*folderForwardHistory, *folderHistory);
// Show path in status bar
this->setPath();
}
void MainWindow::on_actionOpen_triggered()
{
// Open the dialog
DialogOpen *open = new DialogOpen(this);
int dialogResult = open->exec();
// Accepted dialog?
if(dialogResult == QDialog::Accepted) {
// Open the vault
initializeVault(open->locationVault, open->locationKeyStore);
}
}
void MainWindow::on_actionNew_triggered()
{
DialogNew *newDialog = new DialogNew(this);
newDialog->exec();
}
void MainWindow::on_buttonExport_clicked()
{
exportFiles();
}
void MainWindow::on_buttonImport_clicked()
{
importFiles();
}
void MainWindow::on_buttonDelete_clicked()
{
deleteFileDirectory();
}
void MainWindow::on_actionFolder_triggered()
{
importFolder();
}
void MainWindow::on_actionFile_triggered()
{
importFiles();
}
void MainWindow::on_actionExport_triggered()
{
exportFiles();
}
void MainWindow::importFiles()
{
QFileDialog qFile;
// Allow selecting of multiple files
qFile.setFileMode(QFileDialog::ExistingFiles);
// Open File dialog
qFile.exec();
int filesSelected =qFile.selectedFiles().count();
int current = 0;
QProgressDialog dialog(this);
dialog.setLabelText(tr("Importing file..."));
dialog.setRange(0, filesSelected);
dialog.setVisible(true);
dialog.setModal(true);
// Import files one by one
foreach (QString filePath, qFile.selectedFiles()) {
qDebug() << filePath;
QFileInfo fileInfo(filePath);
dialog.setLabelText(tr("Importing file: %1").arg(fileInfo.fileName()));
qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
QString destinationPath = model->getCurrentDirectory().append("/").append(fileInfo.fileName());
qDebug() << destinationPath;
model->importFile(filePath.toLatin1().data(),destinationPath.toLatin1().data());
//psInstance->importFile(filePath.toLatin1().data(),destinationPath.toLatin1().data());
dialog.setValue(++current);
qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
}
qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
}
void MainWindow::importFolder()
{
qDebug() << "importFolder() called";
QFileDialog qFile;
// Allow selecting of multiple files
qFile.setFileMode(QFileDialog::Directory);
// Open File dialog
qFile.exec();
foreach (QString folderPath, qFile.selectedFiles()) {
qDebug() << folderPath;
// TODO: import folder from filePath
}
}
void MainWindow::exportFiles()
{
QFileDialog qFile;
// Allow selecting of multiple files
qFile.setFileMode(QFileDialog::DirectoryOnly);
// Get the destination directory from the user
QString destinationDir = qFile.getExistingDirectory();
foreach (QModelIndex index, selectedRowsList)
{
QFileInfo fileInfo(model->getFile(index)->getFullPath().data());
// Get the source and destination paths
QString sourcePath = model->getFile(index)->getFullPath().data();
QString destinationPath = destinationDir + "/" + fileInfo.fileName();
qDebug() << sourcePath;
qDebug() << destinationDir;
qDebug() << destinationPath;
// export the current file
psInstance->exportFile(sourcePath.toLatin1().data(), destinationPath.toLatin1().data());
}
}
void MainWindow::deleteFileDirectory()
{
model->deleteFileDirectory(selectedRowsList);
}
void MainWindow::initializeVault(const std::string vaultPath, const std::string keyStorePath)
{
try {
// Convert names
const char *cVaultPath = vaultPath.c_str();
const char *cKeyStorePath = keyStorePath.c_str();
// Setup vault
psInstance->init(cVaultPath, cKeyStorePath);
psInstance->open();
// Create file system models and other instances
folderHistory->clear();
folderForwardHistory->clear();
// Initialize models
model->init();
modelDirs->init();
// Set models in views
ui->treeViewExplorer->setModel(model);
ui->treeViewFiles->setModel(modelDirs);
// TreeViewExplorer: Add signal slot for detecting selection.
connect(ui->treeViewExplorer->selectionModel(), SIGNAL(selectionChanged(const QItemSelection&, const QItemSelection&)), this, SLOT(on_treeViewExplorer_selectionChanged()));
// Enable import/export/Delete
ui->buttonImport->setEnabled(true);
ui->actionImports->setEnabled(true);
ui->actionFile->setEnabled(true);
// Set paths
this->setPath();
} catch(const char *exception) {
std::cout << "Exception: " << exception << std::endl;
}
}
void MainWindow::setPath()
{
// Show message
if(model != nullptr) ui->statusBar->showMessage(model->getCurrentDirectory());
// At last item? Disable back button.
ui->buttonBack->setEnabled(folderHistory->size() > 0);
// At last forward item? Disable forward button.
ui->buttonForward->setEnabled(folderForwardHistory->size() > 0);
}
void MainWindow::on_treeViewExplorer_selectionChanged()
{
//checks if someting is selected
selectedRowsList = ui->treeViewExplorer->selectionModel()->selectedRows();
bool hasSelection = selectedRowsList.size()>=1;
// Enable export/delete
ui->buttonDelete->setEnabled(hasSelection);
ui->buttonExport->setEnabled(hasSelection);
ui->actionExport->setEnabled(hasSelection);
}
<commit_msg>#5 check selection after deleting file(s)<commit_after>#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "dialogopen.h"
#include "dialognew.h"
#include <QDirModel>
#include <QFileDialog>
#include <QProgressDialog>
#include <QDebug>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
// Setup the UI
ui->setupUi(this);
// Setup history stuff
folderHistory = new QStack<QString>();
folderForwardHistory = new QStack<QString>();
// Create the partition safe instance
psInstance = new PartitionSafe();
// Setup models
model = new PSFileSystemModel(this, psInstance);
modelDirs = new PSFileSystemModel(this, psInstance);
#ifdef QT_DEBUG
// Debug mode only, load a default vault
initializeVault("/tmp/marc.vault", "/tmp/marc.keystore");
// Show path in status bar
this->setPath();
#endif
}
MainWindow::~MainWindow()
{
delete ui;
delete folderHistory;
delete folderForwardHistory;
delete model;
delete modelDirs;
}
void MainWindow::on_treeViewExplorer_doubleClicked(const QModelIndex &index)
{
// We should get the selected item
Entry* item = model->getFile(index);
// Only continue if it's a directory
if(!item->isDirectory()) return;
// Get the path
QString path = QString(item->getFullPath().c_str());
// Enter given directory and add to history
model->enterDirectory(path, *folderHistory, *folderForwardHistory);
// Show path in status bar
this->setPath();
}
void MainWindow::on_buttonBack_clicked()
{
model->navigation_buttons(*folderHistory, *folderForwardHistory);
// Show path in status bar
this->setPath();
}
void MainWindow::on_buttonForward_clicked()
{
model->navigation_buttons(*folderForwardHistory, *folderHistory);
// Show path in status bar
this->setPath();
}
void MainWindow::on_actionOpen_triggered()
{
// Open the dialog
DialogOpen *open = new DialogOpen(this);
int dialogResult = open->exec();
// Accepted dialog?
if(dialogResult == QDialog::Accepted) {
// Open the vault
initializeVault(open->locationVault, open->locationKeyStore);
}
}
void MainWindow::on_actionNew_triggered()
{
DialogNew *newDialog = new DialogNew(this);
newDialog->exec();
}
void MainWindow::on_buttonExport_clicked()
{
exportFiles();
}
void MainWindow::on_buttonImport_clicked()
{
importFiles();
}
void MainWindow::on_buttonDelete_clicked()
{
deleteFileDirectory();
}
void MainWindow::on_actionFolder_triggered()
{
importFolder();
}
void MainWindow::on_actionFile_triggered()
{
importFiles();
}
void MainWindow::on_actionExport_triggered()
{
exportFiles();
}
void MainWindow::importFiles()
{
QFileDialog qFile;
// Allow selecting of multiple files
qFile.setFileMode(QFileDialog::ExistingFiles);
// Open File dialog
qFile.exec();
int filesSelected =qFile.selectedFiles().count();
int current = 0;
QProgressDialog dialog(this);
dialog.setLabelText(tr("Importing file..."));
dialog.setRange(0, filesSelected);
dialog.setVisible(true);
dialog.setModal(true);
// Import files one by one
foreach (QString filePath, qFile.selectedFiles()) {
qDebug() << filePath;
QFileInfo fileInfo(filePath);
dialog.setLabelText(tr("Importing file: %1").arg(fileInfo.fileName()));
qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
QString destinationPath = model->getCurrentDirectory().append("/").append(fileInfo.fileName());
qDebug() << destinationPath;
model->importFile(filePath.toLatin1().data(),destinationPath.toLatin1().data());
//psInstance->importFile(filePath.toLatin1().data(),destinationPath.toLatin1().data());
dialog.setValue(++current);
qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
}
qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
}
void MainWindow::importFolder()
{
qDebug() << "importFolder() called";
QFileDialog qFile;
// Allow selecting of multiple files
qFile.setFileMode(QFileDialog::Directory);
// Open File dialog
qFile.exec();
foreach (QString folderPath, qFile.selectedFiles()) {
qDebug() << folderPath;
// TODO: import folder from filePath
}
}
void MainWindow::exportFiles()
{
QFileDialog qFile;
// Allow selecting of multiple files
qFile.setFileMode(QFileDialog::DirectoryOnly);
// Get the destination directory from the user
QString destinationDir = qFile.getExistingDirectory();
foreach (QModelIndex index, selectedRowsList)
{
QFileInfo fileInfo(model->getFile(index)->getFullPath().data());
// Get the source and destination paths
QString sourcePath = model->getFile(index)->getFullPath().data();
QString destinationPath = destinationDir + "/" + fileInfo.fileName();
qDebug() << sourcePath;
qDebug() << destinationDir;
qDebug() << destinationPath;
// export the current file
psInstance->exportFile(sourcePath.toLatin1().data(), destinationPath.toLatin1().data());
}
}
void MainWindow::deleteFileDirectory()
{
model->deleteFileDirectory(selectedRowsList);
on_treeViewExplorer_selectionChanged();
}
void MainWindow::initializeVault(const std::string vaultPath, const std::string keyStorePath)
{
try {
// Convert names
const char *cVaultPath = vaultPath.c_str();
const char *cKeyStorePath = keyStorePath.c_str();
// Setup vault
psInstance->init(cVaultPath, cKeyStorePath);
psInstance->open();
// Create file system models and other instances
folderHistory->clear();
folderForwardHistory->clear();
// Initialize models
model->init();
modelDirs->init();
// Set models in views
ui->treeViewExplorer->setModel(model);
ui->treeViewFiles->setModel(modelDirs);
// TreeViewExplorer: Add signal slot for detecting selection.
connect(ui->treeViewExplorer->selectionModel(), SIGNAL(selectionChanged(const QItemSelection&, const QItemSelection&)), this, SLOT(on_treeViewExplorer_selectionChanged()));
// Enable import/export/Delete
ui->buttonImport->setEnabled(true);
ui->actionImports->setEnabled(true);
ui->actionFile->setEnabled(true);
// Set paths
this->setPath();
} catch(const char *exception) {
std::cout << "Exception: " << exception << std::endl;
}
}
void MainWindow::setPath()
{
// Show message
if(model != nullptr) ui->statusBar->showMessage(model->getCurrentDirectory());
// At last item? Disable back button.
ui->buttonBack->setEnabled(folderHistory->size() > 0);
// At last forward item? Disable forward button.
ui->buttonForward->setEnabled(folderForwardHistory->size() > 0);
}
void MainWindow::on_treeViewExplorer_selectionChanged()
{
//checks if someting is selected
selectedRowsList = ui->treeViewExplorer->selectionModel()->selectedRows();
bool hasSelection = selectedRowsList.size()>=1;
// Enable export/delete
ui->buttonDelete->setEnabled(hasSelection);
ui->buttonExport->setEnabled(hasSelection);
ui->actionExport->setEnabled(hasSelection);
}
<|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 "base/command_line.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/common/chrome_switches.h"
#include "net/base/mock_host_resolver.h"
// Flaky, http://crbug.com/26296.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, FLAKY_History) {
host_resolver()->AddRule("www.a.com", "127.0.0.1");
host_resolver()->AddRule("www.b.com", "127.0.0.1");
ASSERT_TRUE(StartTestServer());
ASSERT_TRUE(RunExtensionTest("history")) << message_;
}
<commit_msg>Disable crashy ExtensionApiTest.History<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 "base/command_line.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/common/chrome_switches.h"
#include "net/base/mock_host_resolver.h"
// Disabled, http://crbug.com/26296.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_History) {
host_resolver()->AddRule("www.a.com", "127.0.0.1");
host_resolver()->AddRule("www.b.com", "127.0.0.1");
ASSERT_TRUE(StartTestServer());
ASSERT_TRUE(RunExtensionTest("history")) << message_;
}
<|endoftext|>
|
<commit_before>/*************************************************************************/
/* video_stream_gdnative.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
/* */
/* 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 "video_stream_gdnative.h"
#include "core/project_settings.h"
#include "servers/audio_server.h"
VideoDecoderServer *VideoDecoderServer::instance = NULL;
static VideoDecoderServer decoder_server;
const int AUX_BUFFER_SIZE = 1024; // Buffer 1024 samples.
// NOTE: Callbacks for the GDNative libraries.
extern "C" {
godot_int GDAPI godot_videodecoder_file_read(void *ptr, uint8_t *buf, int buf_size) {
// ptr is a FileAccess
FileAccess *file = reinterpret_cast<FileAccess *>(ptr);
// if file exists
if (file) {
long bytes_read = file->get_buffer(buf, buf_size);
// No bytes to read => EOF
if (bytes_read == 0) {
return 0;
}
return bytes_read;
}
return -1;
}
int64_t GDAPI godot_videodecoder_file_seek(void *ptr, int64_t pos, int whence) {
// file
FileAccess *file = reinterpret_cast<FileAccess *>(ptr);
size_t len = file->get_len();
if (file) {
switch (whence) {
case SEEK_SET: {
// Just for explicitness
size_t new_pos = static_cast<size_t>(pos);
if (new_pos > len) {
return -1;
}
file->seek(new_pos);
pos = static_cast<int64_t>(file->get_position());
return pos;
} break;
case SEEK_CUR: {
// Just in case it doesn't exist
if (pos < 0 && (size_t)-pos > file->get_position()) {
return -1;
}
pos = pos + static_cast<int>(file->get_position());
file->seek(pos);
pos = static_cast<int64_t>(file->get_position());
return pos;
} break;
case SEEK_END: {
// Just in case something goes wrong
if ((size_t)-pos > len) {
return -1;
}
file->seek_end(pos);
pos = static_cast<int64_t>(file->get_position());
return pos;
} break;
default: {
// Only 4 possible options, hence default = AVSEEK_SIZE
// Asks to return the length of file
return static_cast<int64_t>(len);
} break;
}
}
// In case nothing works out.
return -1;
}
void GDAPI godot_videodecoder_register_decoder(const godot_videodecoder_interface_gdnative *p_interface) {
decoder_server.register_decoder_interface(p_interface);
}
}
// VideoStreamPlaybackGDNative starts here.
bool VideoStreamPlaybackGDNative::open_file(const String &p_file) {
ERR_FAIL_COND_V(interface == NULL, false);
file = FileAccess::open(p_file, FileAccess::READ);
bool file_opened = interface->open_file(data_struct, file);
num_channels = interface->get_channels(data_struct);
mix_rate = interface->get_mix_rate(data_struct);
godot_vector2 vec = interface->get_texture_size(data_struct);
texture_size = *(Vector2 *)&vec;
pcm = (float *)memalloc(num_channels * AUX_BUFFER_SIZE * sizeof(float));
memset(pcm, 0, num_channels * AUX_BUFFER_SIZE * sizeof(float));
pcm_write_idx = -1;
samples_decoded = 0;
texture->create((int)texture_size.width, (int)texture_size.height, Image::FORMAT_RGBA8, Texture::FLAG_FILTER | Texture::FLAG_VIDEO_SURFACE);
return file_opened;
}
void VideoStreamPlaybackGDNative::update(float p_delta) {
if (!playing || paused) {
return;
}
if (!file) {
return;
}
time += p_delta;
ERR_FAIL_COND(interface == NULL);
interface->update(data_struct, p_delta);
if (pcm_write_idx >= 0) {
// Previous remains
int mixed = mix_callback(mix_udata, pcm, samples_decoded);
if (mixed == samples_decoded) {
pcm_write_idx = -1;
} else {
samples_decoded -= mixed;
pcm_write_idx += mixed;
}
}
if (pcm_write_idx < 0) {
samples_decoded = interface->get_audioframe(data_struct, pcm, AUX_BUFFER_SIZE);
pcm_write_idx = mix_callback(mix_udata, pcm, samples_decoded);
if (pcm_write_idx == samples_decoded) {
pcm_write_idx = -1;
} else {
samples_decoded -= pcm_write_idx;
}
}
while (interface->get_playback_position(data_struct) < time && playing) {
update_texture();
}
}
void VideoStreamPlaybackGDNative::update_texture() {
PoolByteArray *pba = (PoolByteArray *)interface->get_videoframe(data_struct);
if (pba == NULL) {
playing = false;
return;
}
Ref<Image> img = memnew(Image(texture_size.width, texture_size.height, 0, Image::FORMAT_RGBA8, *pba));
texture->set_data(img);
}
// ctor and dtor
VideoStreamPlaybackGDNative::VideoStreamPlaybackGDNative() :
texture(Ref<ImageTexture>(memnew(ImageTexture))),
playing(false),
paused(false),
mix_udata(NULL),
mix_callback(NULL),
num_channels(-1),
time(0),
mix_rate(0),
delay_compensation(0),
pcm(NULL),
pcm_write_idx(0),
samples_decoded(0),
file(NULL),
interface(NULL),
data_struct(NULL) {}
VideoStreamPlaybackGDNative::~VideoStreamPlaybackGDNative() {
cleanup();
}
void VideoStreamPlaybackGDNative::cleanup() {
if (data_struct)
interface->destructor(data_struct);
if (pcm)
memfree(pcm);
pcm = NULL;
time = 0;
num_channels = -1;
interface = NULL;
data_struct = NULL;
}
void VideoStreamPlaybackGDNative::set_interface(const godot_videodecoder_interface_gdnative *p_interface) {
ERR_FAIL_COND(p_interface == NULL);
if (interface != NULL) {
cleanup();
}
interface = p_interface;
data_struct = interface->constructor((godot_object *)this);
}
// controls
bool VideoStreamPlaybackGDNative::is_playing() const {
return playing;
}
bool VideoStreamPlaybackGDNative::is_paused() const {
return paused;
}
void VideoStreamPlaybackGDNative::play() {
stop();
playing = true;
delay_compensation = ProjectSettings::get_singleton()->get("audio/video_delay_compensation_ms");
delay_compensation /= 1000.0;
}
void VideoStreamPlaybackGDNative::stop() {
if (playing) {
seek(0);
}
playing = false;
}
void VideoStreamPlaybackGDNative::seek(float p_time) {
ERR_FAIL_COND(interface == NULL);
interface->seek(data_struct, p_time);
}
void VideoStreamPlaybackGDNative::set_paused(bool p_paused) {
paused = p_paused;
}
Ref<Texture> VideoStreamPlaybackGDNative::get_texture() {
return texture;
}
float VideoStreamPlaybackGDNative::get_length() const {
ERR_FAIL_COND_V(interface == NULL, 0);
return interface->get_length(data_struct);
}
float VideoStreamPlaybackGDNative::get_playback_position() const {
ERR_FAIL_COND_V(interface == NULL, 0);
return interface->get_playback_position(data_struct);
}
bool VideoStreamPlaybackGDNative::has_loop() const {
// TODO: Implement looping?
return false;
}
void VideoStreamPlaybackGDNative::set_loop(bool p_enable) {
// Do nothing
}
void VideoStreamPlaybackGDNative::set_audio_track(int p_idx) {
ERR_FAIL_COND(interface == NULL);
interface->set_audio_track(data_struct, p_idx);
}
void VideoStreamPlaybackGDNative::set_mix_callback(AudioMixCallback p_callback, void *p_userdata) {
mix_udata = p_userdata;
mix_callback = p_callback;
}
int VideoStreamPlaybackGDNative::get_channels() const {
ERR_FAIL_COND_V(interface == NULL, 0);
return (num_channels > 0) ? num_channels : 0;
}
int VideoStreamPlaybackGDNative::get_mix_rate() const {
ERR_FAIL_COND_V(interface == NULL, 0);
return mix_rate;
}
/* --- NOTE VideoStreamGDNative starts here. ----- */
Ref<VideoStreamPlayback> VideoStreamGDNative::instance_playback() {
Ref<VideoStreamPlaybackGDNative> pb = memnew(VideoStreamPlaybackGDNative);
VideoDecoderGDNative *decoder = decoder_server.get_decoder(file.get_extension().to_lower());
if (decoder == NULL)
return NULL;
pb->set_interface(decoder->interface);
pb->set_audio_track(audio_track);
if (pb->open_file(file))
return pb;
return NULL;
}
void VideoStreamGDNative::set_file(const String &p_file) {
file = p_file;
}
String VideoStreamGDNative::get_file() {
return file;
}
void VideoStreamGDNative::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_file", "file"), &VideoStreamGDNative::set_file);
ClassDB::bind_method(D_METHOD("get_file"), &VideoStreamGDNative::get_file);
ADD_PROPERTY(PropertyInfo(Variant::STRING, "file", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR | PROPERTY_USAGE_INTERNAL), "set_file", "get_file");
}
void VideoStreamGDNative::set_audio_track(int p_track) {
audio_track = p_track;
}
/* --- NOTE ResourceFormatLoaderVideoStreamGDNative starts here. ----- */
RES ResourceFormatLoaderVideoStreamGDNative::load(const String &p_path, const String &p_original_path, Error *r_error) {
FileAccess *f = FileAccess::open(p_path, FileAccess::READ);
if (!f) {
if (r_error) {
*r_error = ERR_CANT_OPEN;
}
return RES();
}
memdelete(f);
VideoStreamGDNative *stream = memnew(VideoStreamGDNative);
stream->set_file(p_path);
Ref<VideoStreamGDNative> ogv_stream = Ref<VideoStreamGDNative>(stream);
if (r_error) {
*r_error = OK;
}
return ogv_stream;
}
void ResourceFormatLoaderVideoStreamGDNative::get_recognized_extensions(List<String> *p_extensions) const {
Map<String, int>::Element *el = VideoDecoderServer::get_instance()->get_extensions().front();
while (el) {
p_extensions->push_back(el->key());
el = el->next();
}
}
bool ResourceFormatLoaderVideoStreamGDNative::handles_type(const String &p_type) const {
return ClassDB::is_parent_class(p_type, "VideoStream");
}
String ResourceFormatLoaderVideoStreamGDNative::get_resource_type(const String &p_path) const {
String el = p_path.get_extension().to_lower();
if (VideoDecoderServer::get_instance()->get_extensions().has(el))
return "VideoStreamGDNative";
return "";
}
<commit_msg>Fixes segfault on opening incompatible files.<commit_after>/*************************************************************************/
/* video_stream_gdnative.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
/* */
/* 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 "video_stream_gdnative.h"
#include "core/project_settings.h"
#include "servers/audio_server.h"
VideoDecoderServer *VideoDecoderServer::instance = NULL;
static VideoDecoderServer decoder_server;
const int AUX_BUFFER_SIZE = 1024; // Buffer 1024 samples.
// NOTE: Callbacks for the GDNative libraries.
extern "C" {
godot_int GDAPI godot_videodecoder_file_read(void *ptr, uint8_t *buf, int buf_size) {
// ptr is a FileAccess
FileAccess *file = reinterpret_cast<FileAccess *>(ptr);
// if file exists
if (file) {
long bytes_read = file->get_buffer(buf, buf_size);
// No bytes to read => EOF
if (bytes_read == 0) {
return 0;
}
return bytes_read;
}
return -1;
}
int64_t GDAPI godot_videodecoder_file_seek(void *ptr, int64_t pos, int whence) {
// file
FileAccess *file = reinterpret_cast<FileAccess *>(ptr);
size_t len = file->get_len();
if (file) {
switch (whence) {
case SEEK_SET: {
// Just for explicitness
size_t new_pos = static_cast<size_t>(pos);
if (new_pos > len) {
return -1;
}
file->seek(new_pos);
pos = static_cast<int64_t>(file->get_position());
return pos;
} break;
case SEEK_CUR: {
// Just in case it doesn't exist
if (pos < 0 && (size_t)-pos > file->get_position()) {
return -1;
}
pos = pos + static_cast<int>(file->get_position());
file->seek(pos);
pos = static_cast<int64_t>(file->get_position());
return pos;
} break;
case SEEK_END: {
// Just in case something goes wrong
if ((size_t)-pos > len) {
return -1;
}
file->seek_end(pos);
pos = static_cast<int64_t>(file->get_position());
return pos;
} break;
default: {
// Only 4 possible options, hence default = AVSEEK_SIZE
// Asks to return the length of file
return static_cast<int64_t>(len);
} break;
}
}
// In case nothing works out.
return -1;
}
void GDAPI godot_videodecoder_register_decoder(const godot_videodecoder_interface_gdnative *p_interface) {
decoder_server.register_decoder_interface(p_interface);
}
}
// VideoStreamPlaybackGDNative starts here.
bool VideoStreamPlaybackGDNative::open_file(const String &p_file) {
ERR_FAIL_COND_V(interface == NULL, false);
file = FileAccess::open(p_file, FileAccess::READ);
bool file_opened = interface->open_file(data_struct, file);
if (file_opened) {
num_channels = interface->get_channels(data_struct);
mix_rate = interface->get_mix_rate(data_struct);
godot_vector2 vec = interface->get_texture_size(data_struct);
texture_size = *(Vector2 *)&vec;
pcm = (float *)memalloc(num_channels * AUX_BUFFER_SIZE * sizeof(float));
memset(pcm, 0, num_channels * AUX_BUFFER_SIZE * sizeof(float));
pcm_write_idx = -1;
samples_decoded = 0;
texture->create((int)texture_size.width, (int)texture_size.height, Image::FORMAT_RGBA8, Texture::FLAG_FILTER | Texture::FLAG_VIDEO_SURFACE);
}
return file_opened;
}
void VideoStreamPlaybackGDNative::update(float p_delta) {
if (!playing || paused) {
return;
}
if (!file) {
return;
}
time += p_delta;
ERR_FAIL_COND(interface == NULL);
interface->update(data_struct, p_delta);
if (pcm_write_idx >= 0) {
// Previous remains
int mixed = mix_callback(mix_udata, pcm, samples_decoded);
if (mixed == samples_decoded) {
pcm_write_idx = -1;
} else {
samples_decoded -= mixed;
pcm_write_idx += mixed;
}
}
if (pcm_write_idx < 0) {
samples_decoded = interface->get_audioframe(data_struct, pcm, AUX_BUFFER_SIZE);
pcm_write_idx = mix_callback(mix_udata, pcm, samples_decoded);
if (pcm_write_idx == samples_decoded) {
pcm_write_idx = -1;
} else {
samples_decoded -= pcm_write_idx;
}
}
while (interface->get_playback_position(data_struct) < time && playing) {
update_texture();
}
}
void VideoStreamPlaybackGDNative::update_texture() {
PoolByteArray *pba = (PoolByteArray *)interface->get_videoframe(data_struct);
if (pba == NULL) {
playing = false;
return;
}
Ref<Image> img = memnew(Image(texture_size.width, texture_size.height, 0, Image::FORMAT_RGBA8, *pba));
texture->set_data(img);
}
// ctor and dtor
VideoStreamPlaybackGDNative::VideoStreamPlaybackGDNative() :
texture(Ref<ImageTexture>(memnew(ImageTexture))),
playing(false),
paused(false),
mix_udata(NULL),
mix_callback(NULL),
num_channels(-1),
time(0),
mix_rate(0),
delay_compensation(0),
pcm(NULL),
pcm_write_idx(0),
samples_decoded(0),
file(NULL),
interface(NULL),
data_struct(NULL) {}
VideoStreamPlaybackGDNative::~VideoStreamPlaybackGDNative() {
cleanup();
}
void VideoStreamPlaybackGDNative::cleanup() {
if (data_struct)
interface->destructor(data_struct);
if (pcm)
memfree(pcm);
pcm = NULL;
time = 0;
num_channels = -1;
interface = NULL;
data_struct = NULL;
}
void VideoStreamPlaybackGDNative::set_interface(const godot_videodecoder_interface_gdnative *p_interface) {
ERR_FAIL_COND(p_interface == NULL);
if (interface != NULL) {
cleanup();
}
interface = p_interface;
data_struct = interface->constructor((godot_object *)this);
}
// controls
bool VideoStreamPlaybackGDNative::is_playing() const {
return playing;
}
bool VideoStreamPlaybackGDNative::is_paused() const {
return paused;
}
void VideoStreamPlaybackGDNative::play() {
stop();
playing = true;
delay_compensation = ProjectSettings::get_singleton()->get("audio/video_delay_compensation_ms");
delay_compensation /= 1000.0;
}
void VideoStreamPlaybackGDNative::stop() {
if (playing) {
seek(0);
}
playing = false;
}
void VideoStreamPlaybackGDNative::seek(float p_time) {
ERR_FAIL_COND(interface == NULL);
interface->seek(data_struct, p_time);
}
void VideoStreamPlaybackGDNative::set_paused(bool p_paused) {
paused = p_paused;
}
Ref<Texture> VideoStreamPlaybackGDNative::get_texture() {
return texture;
}
float VideoStreamPlaybackGDNative::get_length() const {
ERR_FAIL_COND_V(interface == NULL, 0);
return interface->get_length(data_struct);
}
float VideoStreamPlaybackGDNative::get_playback_position() const {
ERR_FAIL_COND_V(interface == NULL, 0);
return interface->get_playback_position(data_struct);
}
bool VideoStreamPlaybackGDNative::has_loop() const {
// TODO: Implement looping?
return false;
}
void VideoStreamPlaybackGDNative::set_loop(bool p_enable) {
// Do nothing
}
void VideoStreamPlaybackGDNative::set_audio_track(int p_idx) {
ERR_FAIL_COND(interface == NULL);
interface->set_audio_track(data_struct, p_idx);
}
void VideoStreamPlaybackGDNative::set_mix_callback(AudioMixCallback p_callback, void *p_userdata) {
mix_udata = p_userdata;
mix_callback = p_callback;
}
int VideoStreamPlaybackGDNative::get_channels() const {
ERR_FAIL_COND_V(interface == NULL, 0);
return (num_channels > 0) ? num_channels : 0;
}
int VideoStreamPlaybackGDNative::get_mix_rate() const {
ERR_FAIL_COND_V(interface == NULL, 0);
return mix_rate;
}
/* --- NOTE VideoStreamGDNative starts here. ----- */
Ref<VideoStreamPlayback> VideoStreamGDNative::instance_playback() {
Ref<VideoStreamPlaybackGDNative> pb = memnew(VideoStreamPlaybackGDNative);
VideoDecoderGDNative *decoder = decoder_server.get_decoder(file.get_extension().to_lower());
if (decoder == NULL)
return NULL;
pb->set_interface(decoder->interface);
pb->set_audio_track(audio_track);
if (pb->open_file(file))
return pb;
return NULL;
}
void VideoStreamGDNative::set_file(const String &p_file) {
file = p_file;
}
String VideoStreamGDNative::get_file() {
return file;
}
void VideoStreamGDNative::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_file", "file"), &VideoStreamGDNative::set_file);
ClassDB::bind_method(D_METHOD("get_file"), &VideoStreamGDNative::get_file);
ADD_PROPERTY(PropertyInfo(Variant::STRING, "file", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR | PROPERTY_USAGE_INTERNAL), "set_file", "get_file");
}
void VideoStreamGDNative::set_audio_track(int p_track) {
audio_track = p_track;
}
/* --- NOTE ResourceFormatLoaderVideoStreamGDNative starts here. ----- */
RES ResourceFormatLoaderVideoStreamGDNative::load(const String &p_path, const String &p_original_path, Error *r_error) {
FileAccess *f = FileAccess::open(p_path, FileAccess::READ);
if (!f) {
if (r_error) {
*r_error = ERR_CANT_OPEN;
}
return RES();
}
memdelete(f);
VideoStreamGDNative *stream = memnew(VideoStreamGDNative);
stream->set_file(p_path);
Ref<VideoStreamGDNative> ogv_stream = Ref<VideoStreamGDNative>(stream);
if (r_error) {
*r_error = OK;
}
return ogv_stream;
}
void ResourceFormatLoaderVideoStreamGDNative::get_recognized_extensions(List<String> *p_extensions) const {
Map<String, int>::Element *el = VideoDecoderServer::get_instance()->get_extensions().front();
while (el) {
p_extensions->push_back(el->key());
el = el->next();
}
}
bool ResourceFormatLoaderVideoStreamGDNative::handles_type(const String &p_type) const {
return ClassDB::is_parent_class(p_type, "VideoStream");
}
String ResourceFormatLoaderVideoStreamGDNative::get_resource_type(const String &p_path) const {
String el = p_path.get_extension().to_lower();
if (VideoDecoderServer::get_instance()->get_extensions().has(el))
return "VideoStreamGDNative";
return "";
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/extension_message_service.h"
#include "base/atomic_sequence_num.h"
#include "base/json/json_writer.h"
#include "base/stl_util.h"
#include "base/values.h"
#include "chrome/browser/extensions/extension_process_manager.h"
#include "chrome/browser/extensions/extension_tab_util.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/tab_contents/tab_util.h"
#include "chrome/browser/ui/tab_contents/tab_contents_wrapper.h"
#include "chrome/common/extensions/extension.h"
#include "chrome/common/extensions/extension_messages.h"
#include "content/browser/child_process_security_policy.h"
#include "content/browser/renderer_host/render_process_host.h"
#include "content/browser/renderer_host/render_view_host.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "content/common/notification_service.h"
// Since we have 2 ports for every channel, we just index channels by half the
// port ID.
#define GET_CHANNEL_ID(port_id) ((port_id) / 2)
#define GET_CHANNEL_OPENER_ID(channel_id) ((channel_id) * 2)
#define GET_CHANNEL_RECEIVERS_ID(channel_id) ((channel_id) * 2 + 1)
// Port1 is always even, port2 is always odd.
#define IS_OPENER_PORT_ID(port_id) (((port_id) & 1) == 0)
// Change even to odd and vice versa, to get the other side of a given channel.
#define GET_OPPOSITE_PORT_ID(source_port_id) ((source_port_id) ^ 1)
struct ExtensionMessageService::MessagePort {
IPC::Message::Sender* sender;
int routing_id;
explicit MessagePort(IPC::Message::Sender* sender = NULL,
int routing_id = MSG_ROUTING_CONTROL)
: sender(sender), routing_id(routing_id) {}
};
struct ExtensionMessageService::MessageChannel {
ExtensionMessageService::MessagePort opener;
ExtensionMessageService::MessagePort receiver;
};
const char ExtensionMessageService::kDispatchOnConnect[] =
"Port.dispatchOnConnect";
const char ExtensionMessageService::kDispatchOnDisconnect[] =
"Port.dispatchOnDisconnect";
namespace {
static base::AtomicSequenceNumber g_next_channel_id(base::LINKER_INITIALIZED);
static void DispatchOnConnect(const ExtensionMessageService::MessagePort& port,
int dest_port_id,
const std::string& channel_name,
const std::string& tab_json,
const std::string& source_extension_id,
const std::string& target_extension_id) {
ListValue args;
args.Set(0, Value::CreateIntegerValue(dest_port_id));
args.Set(1, Value::CreateStringValue(channel_name));
args.Set(2, Value::CreateStringValue(tab_json));
args.Set(3, Value::CreateStringValue(source_extension_id));
args.Set(4, Value::CreateStringValue(target_extension_id));
CHECK(port.sender);
port.sender->Send(
new ExtensionMsg_MessageInvoke(
port.routing_id,
target_extension_id,
ExtensionMessageService::kDispatchOnConnect, args, GURL()));
}
static void DispatchOnDisconnect(
const ExtensionMessageService::MessagePort& port, int source_port_id,
bool connection_error) {
ListValue args;
args.Set(0, Value::CreateIntegerValue(source_port_id));
args.Set(1, Value::CreateBooleanValue(connection_error));
port.sender->Send(new ExtensionMsg_MessageInvoke(port.routing_id,
"", ExtensionMessageService::kDispatchOnDisconnect, args, GURL()));
}
static void DispatchOnMessage(const ExtensionMessageService::MessagePort& port,
const std::string& message, int target_port_id) {
port.sender->Send(
new ExtensionMsg_DeliverMessage(
port.routing_id, target_port_id, message));
}
} // namespace
// static
void ExtensionMessageService::AllocatePortIdPair(int* port1, int* port2) {
int channel_id = g_next_channel_id.GetNext();
int port1_id = channel_id * 2;
int port2_id = channel_id * 2 + 1;
// Sanity checks to make sure our channel<->port converters are correct.
DCHECK(IS_OPENER_PORT_ID(port1_id));
DCHECK(GET_OPPOSITE_PORT_ID(port1_id) == port2_id);
DCHECK(GET_OPPOSITE_PORT_ID(port2_id) == port1_id);
DCHECK(GET_CHANNEL_ID(port1_id) == GET_CHANNEL_ID(port2_id));
DCHECK(GET_CHANNEL_ID(port1_id) == channel_id);
DCHECK(GET_CHANNEL_OPENER_ID(channel_id) == port1_id);
DCHECK(GET_CHANNEL_RECEIVERS_ID(channel_id) == port2_id);
*port1 = port1_id;
*port2 = port2_id;
}
ExtensionMessageService::ExtensionMessageService(Profile* profile)
: profile_(profile) {
registrar_.Add(this, content::NOTIFICATION_RENDERER_PROCESS_TERMINATED,
NotificationService::AllSources());
registrar_.Add(this, content::NOTIFICATION_RENDERER_PROCESS_CLOSED,
NotificationService::AllSources());
registrar_.Add(this, content::NOTIFICATION_RENDER_VIEW_HOST_DELETED,
NotificationService::AllSources());
}
ExtensionMessageService::~ExtensionMessageService() {
STLDeleteContainerPairSecondPointers(channels_.begin(), channels_.end());
channels_.clear();
}
void ExtensionMessageService::DestroyingProfile() {
profile_ = NULL;
if (!registrar_.IsEmpty())
registrar_.RemoveAll();
}
void ExtensionMessageService::OpenChannelToExtension(
int source_process_id, int source_routing_id, int receiver_port_id,
const std::string& source_extension_id,
const std::string& target_extension_id,
const std::string& channel_name) {
RenderProcessHost* source = RenderProcessHost::FromID(source_process_id);
if (!source)
return;
Profile* profile = Profile::FromBrowserContext(source->browser_context());
// Note: we use the source's profile here. If the source is an incognito
// process, we will use the incognito EPM to find the right extension process,
// which depends on whether the extension uses spanning or split mode.
MessagePort receiver(
profile->GetExtensionProcessManager()->GetExtensionProcess(
target_extension_id),
MSG_ROUTING_CONTROL);
TabContents* source_contents = tab_util::GetTabContentsByID(
source_process_id, source_routing_id);
// Include info about the opener's tab (if it was a tab).
std::string tab_json = "null";
if (source_contents) {
scoped_ptr<DictionaryValue> tab_value(
ExtensionTabUtil::CreateTabValue(source_contents));
base::JSONWriter::Write(tab_value.get(), false, &tab_json);
}
OpenChannelImpl(source, tab_json, receiver, receiver_port_id,
source_extension_id, target_extension_id, channel_name);
}
void ExtensionMessageService::OpenChannelToTab(
int source_process_id, int source_routing_id, int receiver_port_id,
int tab_id, const std::string& extension_id,
const std::string& channel_name) {
RenderProcessHost* source = RenderProcessHost::FromID(source_process_id);
if (!source)
return;
Profile* profile = Profile::FromBrowserContext(source->browser_context());
TabContentsWrapper* contents = NULL;
MessagePort receiver;
if (ExtensionTabUtil::GetTabById(tab_id, profile, true,
NULL, NULL, &contents, NULL)) {
receiver.sender = contents->render_view_host();
receiver.routing_id = contents->render_view_host()->routing_id();
}
if (contents && contents->controller().needs_reload()) {
// The tab isn't loaded yet. Don't attempt to connect. Treat this as a
// disconnect.
DispatchOnDisconnect(MessagePort(source, MSG_ROUTING_CONTROL),
GET_OPPOSITE_PORT_ID(receiver_port_id), true);
return;
}
TabContents* source_contents = tab_util::GetTabContentsByID(
source_process_id, source_routing_id);
// Include info about the opener's tab (if it was a tab).
std::string tab_json = "null";
if (source_contents) {
scoped_ptr<DictionaryValue> tab_value(
ExtensionTabUtil::CreateTabValue(source_contents));
base::JSONWriter::Write(tab_value.get(), false, &tab_json);
}
OpenChannelImpl(source, tab_json, receiver, receiver_port_id,
extension_id, extension_id, channel_name);
}
bool ExtensionMessageService::OpenChannelImpl(
IPC::Message::Sender* source,
const std::string& tab_json,
const MessagePort& receiver, int receiver_port_id,
const std::string& source_extension_id,
const std::string& target_extension_id,
const std::string& channel_name) {
if (!source)
return false; // Closed while in flight.
if (!receiver.sender) {
// Treat it as a disconnect.
DispatchOnDisconnect(MessagePort(source, MSG_ROUTING_CONTROL),
GET_OPPOSITE_PORT_ID(receiver_port_id), true);
return false;
}
// Add extra paranoid CHECKs, since we have crash reports of this being NULL.
// http://code.google.com/p/chromium/issues/detail?id=19067
CHECK(receiver.sender);
MessageChannel* channel(new MessageChannel);
channel->opener = MessagePort(source, MSG_ROUTING_CONTROL);
channel->receiver = receiver;
CHECK(receiver.sender);
CHECK(channels_.find(GET_CHANNEL_ID(receiver_port_id)) == channels_.end());
channels_[GET_CHANNEL_ID(receiver_port_id)] = channel;
CHECK(receiver.sender);
// Send the connect event to the receiver. Give it the opener's port ID (the
// opener has the opposite port ID).
DispatchOnConnect(receiver, receiver_port_id, channel_name, tab_json,
source_extension_id, target_extension_id);
return true;
}
int ExtensionMessageService::OpenSpecialChannelToExtension(
const std::string& extension_id, const std::string& channel_name,
const std::string& tab_json, IPC::Message::Sender* source) {
DCHECK(profile_);
int port1_id = -1;
int port2_id = -1;
// Create a channel ID for both sides of the channel.
AllocatePortIdPair(&port1_id, &port2_id);
MessagePort receiver(
profile_->GetExtensionProcessManager()->GetExtensionProcess(extension_id),
MSG_ROUTING_CONTROL);
if (!OpenChannelImpl(source, tab_json, receiver, port2_id,
extension_id, extension_id, channel_name))
return -1;
return port1_id;
}
int ExtensionMessageService::OpenSpecialChannelToTab(
const std::string& extension_id, const std::string& channel_name,
TabContents* target_tab_contents, IPC::Message::Sender* source) {
DCHECK(target_tab_contents);
if (target_tab_contents->controller().needs_reload()) {
// The tab isn't loaded yet. Don't attempt to connect.
return -1;
}
int port1_id = -1;
int port2_id = -1;
// Create a channel ID for both sides of the channel.
AllocatePortIdPair(&port1_id, &port2_id);
MessagePort receiver(
target_tab_contents->render_view_host(),
target_tab_contents->render_view_host()->routing_id());
if (!OpenChannelImpl(source, "null", receiver, port2_id,
extension_id, extension_id, channel_name))
return -1;
return port1_id;
}
void ExtensionMessageService::CloseChannel(int port_id) {
// Note: The channel might be gone already, if the other side closed first.
MessageChannelMap::iterator it = channels_.find(GET_CHANNEL_ID(port_id));
if (it != channels_.end())
CloseChannelImpl(it, port_id, true);
}
void ExtensionMessageService::CloseChannelImpl(
MessageChannelMap::iterator channel_iter, int closing_port_id,
bool notify_other_port) {
// Notify the other side.
const MessagePort& port = IS_OPENER_PORT_ID(closing_port_id) ?
channel_iter->second->receiver : channel_iter->second->opener;
if (notify_other_port)
DispatchOnDisconnect(port, GET_OPPOSITE_PORT_ID(closing_port_id), false);
delete channel_iter->second;
channels_.erase(channel_iter);
}
void ExtensionMessageService::PostMessageFromRenderer(
int source_port_id, const std::string& message) {
MessageChannelMap::iterator iter =
channels_.find(GET_CHANNEL_ID(source_port_id));
if (iter == channels_.end())
return;
// Figure out which port the ID corresponds to.
int dest_port_id = GET_OPPOSITE_PORT_ID(source_port_id);
const MessagePort& port = IS_OPENER_PORT_ID(dest_port_id) ?
iter->second->opener : iter->second->receiver;
DispatchOnMessage(port, message, dest_port_id);
}
void ExtensionMessageService::Observe(int type,
const NotificationSource& source,
const NotificationDetails& details) {
switch (type) {
case content::NOTIFICATION_RENDERER_PROCESS_TERMINATED:
case content::NOTIFICATION_RENDERER_PROCESS_CLOSED: {
RenderProcessHost* renderer = Source<RenderProcessHost>(source).ptr();
OnSenderClosed(renderer);
break;
}
case content::NOTIFICATION_RENDER_VIEW_HOST_DELETED:
OnSenderClosed(Source<RenderViewHost>(source).ptr());
break;
default:
NOTREACHED();
return;
}
}
void ExtensionMessageService::OnSenderClosed(IPC::Message::Sender* sender) {
// Close any channels that share this renderer. We notify the opposite
// port that his pair has closed.
for (MessageChannelMap::iterator it = channels_.begin();
it != channels_.end(); ) {
MessageChannelMap::iterator current = it++;
// If both sides are the same renderer, and it is closing, there is no
// "other" port, so there's no need to notify it.
bool notify_other_port =
current->second->opener.sender != current->second->receiver.sender;
if (current->second->opener.sender == sender) {
CloseChannelImpl(current, GET_CHANNEL_OPENER_ID(current->first),
notify_other_port);
} else if (current->second->receiver.sender == sender) {
CloseChannelImpl(current, GET_CHANNEL_RECEIVERS_ID(current->first),
notify_other_port);
}
}
}
<commit_msg>Mark ExtensionMessageService AllSources usage as ok.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/extension_message_service.h"
#include "base/atomic_sequence_num.h"
#include "base/json/json_writer.h"
#include "base/stl_util.h"
#include "base/values.h"
#include "chrome/browser/extensions/extension_process_manager.h"
#include "chrome/browser/extensions/extension_tab_util.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/tab_contents/tab_util.h"
#include "chrome/browser/ui/tab_contents/tab_contents_wrapper.h"
#include "chrome/common/extensions/extension.h"
#include "chrome/common/extensions/extension_messages.h"
#include "content/browser/child_process_security_policy.h"
#include "content/browser/renderer_host/render_process_host.h"
#include "content/browser/renderer_host/render_view_host.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "content/common/notification_service.h"
// Since we have 2 ports for every channel, we just index channels by half the
// port ID.
#define GET_CHANNEL_ID(port_id) ((port_id) / 2)
#define GET_CHANNEL_OPENER_ID(channel_id) ((channel_id) * 2)
#define GET_CHANNEL_RECEIVERS_ID(channel_id) ((channel_id) * 2 + 1)
// Port1 is always even, port2 is always odd.
#define IS_OPENER_PORT_ID(port_id) (((port_id) & 1) == 0)
// Change even to odd and vice versa, to get the other side of a given channel.
#define GET_OPPOSITE_PORT_ID(source_port_id) ((source_port_id) ^ 1)
struct ExtensionMessageService::MessagePort {
IPC::Message::Sender* sender;
int routing_id;
explicit MessagePort(IPC::Message::Sender* sender = NULL,
int routing_id = MSG_ROUTING_CONTROL)
: sender(sender), routing_id(routing_id) {}
};
struct ExtensionMessageService::MessageChannel {
ExtensionMessageService::MessagePort opener;
ExtensionMessageService::MessagePort receiver;
};
const char ExtensionMessageService::kDispatchOnConnect[] =
"Port.dispatchOnConnect";
const char ExtensionMessageService::kDispatchOnDisconnect[] =
"Port.dispatchOnDisconnect";
namespace {
static base::AtomicSequenceNumber g_next_channel_id(base::LINKER_INITIALIZED);
static void DispatchOnConnect(const ExtensionMessageService::MessagePort& port,
int dest_port_id,
const std::string& channel_name,
const std::string& tab_json,
const std::string& source_extension_id,
const std::string& target_extension_id) {
ListValue args;
args.Set(0, Value::CreateIntegerValue(dest_port_id));
args.Set(1, Value::CreateStringValue(channel_name));
args.Set(2, Value::CreateStringValue(tab_json));
args.Set(3, Value::CreateStringValue(source_extension_id));
args.Set(4, Value::CreateStringValue(target_extension_id));
CHECK(port.sender);
port.sender->Send(
new ExtensionMsg_MessageInvoke(
port.routing_id,
target_extension_id,
ExtensionMessageService::kDispatchOnConnect, args, GURL()));
}
static void DispatchOnDisconnect(
const ExtensionMessageService::MessagePort& port, int source_port_id,
bool connection_error) {
ListValue args;
args.Set(0, Value::CreateIntegerValue(source_port_id));
args.Set(1, Value::CreateBooleanValue(connection_error));
port.sender->Send(new ExtensionMsg_MessageInvoke(port.routing_id,
"", ExtensionMessageService::kDispatchOnDisconnect, args, GURL()));
}
static void DispatchOnMessage(const ExtensionMessageService::MessagePort& port,
const std::string& message, int target_port_id) {
port.sender->Send(
new ExtensionMsg_DeliverMessage(
port.routing_id, target_port_id, message));
}
} // namespace
// static
void ExtensionMessageService::AllocatePortIdPair(int* port1, int* port2) {
int channel_id = g_next_channel_id.GetNext();
int port1_id = channel_id * 2;
int port2_id = channel_id * 2 + 1;
// Sanity checks to make sure our channel<->port converters are correct.
DCHECK(IS_OPENER_PORT_ID(port1_id));
DCHECK(GET_OPPOSITE_PORT_ID(port1_id) == port2_id);
DCHECK(GET_OPPOSITE_PORT_ID(port2_id) == port1_id);
DCHECK(GET_CHANNEL_ID(port1_id) == GET_CHANNEL_ID(port2_id));
DCHECK(GET_CHANNEL_ID(port1_id) == channel_id);
DCHECK(GET_CHANNEL_OPENER_ID(channel_id) == port1_id);
DCHECK(GET_CHANNEL_RECEIVERS_ID(channel_id) == port2_id);
*port1 = port1_id;
*port2 = port2_id;
}
ExtensionMessageService::ExtensionMessageService(Profile* profile)
: profile_(profile) {
registrar_.Add(this, content::NOTIFICATION_RENDERER_PROCESS_TERMINATED,
NotificationService::AllBrowserContextsAndSources());
registrar_.Add(this, content::NOTIFICATION_RENDERER_PROCESS_CLOSED,
NotificationService::AllBrowserContextsAndSources());
registrar_.Add(this, content::NOTIFICATION_RENDER_VIEW_HOST_DELETED,
NotificationService::AllBrowserContextsAndSources());
}
ExtensionMessageService::~ExtensionMessageService() {
STLDeleteContainerPairSecondPointers(channels_.begin(), channels_.end());
channels_.clear();
}
void ExtensionMessageService::DestroyingProfile() {
profile_ = NULL;
if (!registrar_.IsEmpty())
registrar_.RemoveAll();
}
void ExtensionMessageService::OpenChannelToExtension(
int source_process_id, int source_routing_id, int receiver_port_id,
const std::string& source_extension_id,
const std::string& target_extension_id,
const std::string& channel_name) {
RenderProcessHost* source = RenderProcessHost::FromID(source_process_id);
if (!source)
return;
Profile* profile = Profile::FromBrowserContext(source->browser_context());
// Note: we use the source's profile here. If the source is an incognito
// process, we will use the incognito EPM to find the right extension process,
// which depends on whether the extension uses spanning or split mode.
MessagePort receiver(
profile->GetExtensionProcessManager()->GetExtensionProcess(
target_extension_id),
MSG_ROUTING_CONTROL);
TabContents* source_contents = tab_util::GetTabContentsByID(
source_process_id, source_routing_id);
// Include info about the opener's tab (if it was a tab).
std::string tab_json = "null";
if (source_contents) {
scoped_ptr<DictionaryValue> tab_value(
ExtensionTabUtil::CreateTabValue(source_contents));
base::JSONWriter::Write(tab_value.get(), false, &tab_json);
}
OpenChannelImpl(source, tab_json, receiver, receiver_port_id,
source_extension_id, target_extension_id, channel_name);
}
void ExtensionMessageService::OpenChannelToTab(
int source_process_id, int source_routing_id, int receiver_port_id,
int tab_id, const std::string& extension_id,
const std::string& channel_name) {
RenderProcessHost* source = RenderProcessHost::FromID(source_process_id);
if (!source)
return;
Profile* profile = Profile::FromBrowserContext(source->browser_context());
TabContentsWrapper* contents = NULL;
MessagePort receiver;
if (ExtensionTabUtil::GetTabById(tab_id, profile, true,
NULL, NULL, &contents, NULL)) {
receiver.sender = contents->render_view_host();
receiver.routing_id = contents->render_view_host()->routing_id();
}
if (contents && contents->controller().needs_reload()) {
// The tab isn't loaded yet. Don't attempt to connect. Treat this as a
// disconnect.
DispatchOnDisconnect(MessagePort(source, MSG_ROUTING_CONTROL),
GET_OPPOSITE_PORT_ID(receiver_port_id), true);
return;
}
TabContents* source_contents = tab_util::GetTabContentsByID(
source_process_id, source_routing_id);
// Include info about the opener's tab (if it was a tab).
std::string tab_json = "null";
if (source_contents) {
scoped_ptr<DictionaryValue> tab_value(
ExtensionTabUtil::CreateTabValue(source_contents));
base::JSONWriter::Write(tab_value.get(), false, &tab_json);
}
OpenChannelImpl(source, tab_json, receiver, receiver_port_id,
extension_id, extension_id, channel_name);
}
bool ExtensionMessageService::OpenChannelImpl(
IPC::Message::Sender* source,
const std::string& tab_json,
const MessagePort& receiver, int receiver_port_id,
const std::string& source_extension_id,
const std::string& target_extension_id,
const std::string& channel_name) {
if (!source)
return false; // Closed while in flight.
if (!receiver.sender) {
// Treat it as a disconnect.
DispatchOnDisconnect(MessagePort(source, MSG_ROUTING_CONTROL),
GET_OPPOSITE_PORT_ID(receiver_port_id), true);
return false;
}
// Add extra paranoid CHECKs, since we have crash reports of this being NULL.
// http://code.google.com/p/chromium/issues/detail?id=19067
CHECK(receiver.sender);
MessageChannel* channel(new MessageChannel);
channel->opener = MessagePort(source, MSG_ROUTING_CONTROL);
channel->receiver = receiver;
CHECK(receiver.sender);
CHECK(channels_.find(GET_CHANNEL_ID(receiver_port_id)) == channels_.end());
channels_[GET_CHANNEL_ID(receiver_port_id)] = channel;
CHECK(receiver.sender);
// Send the connect event to the receiver. Give it the opener's port ID (the
// opener has the opposite port ID).
DispatchOnConnect(receiver, receiver_port_id, channel_name, tab_json,
source_extension_id, target_extension_id);
return true;
}
int ExtensionMessageService::OpenSpecialChannelToExtension(
const std::string& extension_id, const std::string& channel_name,
const std::string& tab_json, IPC::Message::Sender* source) {
DCHECK(profile_);
int port1_id = -1;
int port2_id = -1;
// Create a channel ID for both sides of the channel.
AllocatePortIdPair(&port1_id, &port2_id);
MessagePort receiver(
profile_->GetExtensionProcessManager()->GetExtensionProcess(extension_id),
MSG_ROUTING_CONTROL);
if (!OpenChannelImpl(source, tab_json, receiver, port2_id,
extension_id, extension_id, channel_name))
return -1;
return port1_id;
}
int ExtensionMessageService::OpenSpecialChannelToTab(
const std::string& extension_id, const std::string& channel_name,
TabContents* target_tab_contents, IPC::Message::Sender* source) {
DCHECK(target_tab_contents);
if (target_tab_contents->controller().needs_reload()) {
// The tab isn't loaded yet. Don't attempt to connect.
return -1;
}
int port1_id = -1;
int port2_id = -1;
// Create a channel ID for both sides of the channel.
AllocatePortIdPair(&port1_id, &port2_id);
MessagePort receiver(
target_tab_contents->render_view_host(),
target_tab_contents->render_view_host()->routing_id());
if (!OpenChannelImpl(source, "null", receiver, port2_id,
extension_id, extension_id, channel_name))
return -1;
return port1_id;
}
void ExtensionMessageService::CloseChannel(int port_id) {
// Note: The channel might be gone already, if the other side closed first.
MessageChannelMap::iterator it = channels_.find(GET_CHANNEL_ID(port_id));
if (it != channels_.end())
CloseChannelImpl(it, port_id, true);
}
void ExtensionMessageService::CloseChannelImpl(
MessageChannelMap::iterator channel_iter, int closing_port_id,
bool notify_other_port) {
// Notify the other side.
const MessagePort& port = IS_OPENER_PORT_ID(closing_port_id) ?
channel_iter->second->receiver : channel_iter->second->opener;
if (notify_other_port)
DispatchOnDisconnect(port, GET_OPPOSITE_PORT_ID(closing_port_id), false);
delete channel_iter->second;
channels_.erase(channel_iter);
}
void ExtensionMessageService::PostMessageFromRenderer(
int source_port_id, const std::string& message) {
MessageChannelMap::iterator iter =
channels_.find(GET_CHANNEL_ID(source_port_id));
if (iter == channels_.end())
return;
// Figure out which port the ID corresponds to.
int dest_port_id = GET_OPPOSITE_PORT_ID(source_port_id);
const MessagePort& port = IS_OPENER_PORT_ID(dest_port_id) ?
iter->second->opener : iter->second->receiver;
DispatchOnMessage(port, message, dest_port_id);
}
void ExtensionMessageService::Observe(int type,
const NotificationSource& source,
const NotificationDetails& details) {
switch (type) {
case content::NOTIFICATION_RENDERER_PROCESS_TERMINATED:
case content::NOTIFICATION_RENDERER_PROCESS_CLOSED: {
RenderProcessHost* renderer = Source<RenderProcessHost>(source).ptr();
OnSenderClosed(renderer);
break;
}
case content::NOTIFICATION_RENDER_VIEW_HOST_DELETED:
OnSenderClosed(Source<RenderViewHost>(source).ptr());
break;
default:
NOTREACHED();
return;
}
}
void ExtensionMessageService::OnSenderClosed(IPC::Message::Sender* sender) {
// Close any channels that share this renderer. We notify the opposite
// port that his pair has closed.
for (MessageChannelMap::iterator it = channels_.begin();
it != channels_.end(); ) {
MessageChannelMap::iterator current = it++;
// If both sides are the same renderer, and it is closing, there is no
// "other" port, so there's no need to notify it.
bool notify_other_port =
current->second->opener.sender != current->second->receiver.sender;
if (current->second->opener.sender == sender) {
CloseChannelImpl(current, GET_CHANNEL_OPENER_ID(current->first),
notify_other_port);
} else if (current->second->receiver.sender == sender) {
CloseChannelImpl(current, GET_CHANNEL_RECEIVERS_ID(current->first),
notify_other_port);
}
}
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/format_macros.h"
#include "base/string_util.h"
#include "base/stringprintf.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/autocomplete/autocomplete.h"
#include "chrome/browser/autocomplete/autocomplete_edit.h"
#include "chrome/browser/autocomplete/autocomplete_match.h"
#include "chrome/browser/autocomplete/autocomplete_popup_model.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/search_engines/template_url.h"
#include "chrome/browser/search_engines/template_url_service.h"
#include "chrome/browser/search_engines/template_url_service_factory.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/omnibox/location_bar.h"
#include "chrome/browser/ui/omnibox/omnibox_view.h"
#include "chrome/common/chrome_notification_types.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/common/content_notification_types.h"
#if defined(TOOLKIT_GTK)
#include "chrome/browser/ui/gtk/browser_window_gtk.h"
#endif
// Basic test is flaky on ChromeOS.
// http://crbug.com/52929
#if defined(OS_CHROMEOS)
#define MAYBE_Basic FLAKY_Basic
#else
#define MAYBE_Basic Basic
#endif
namespace {
string16 AutocompleteResultAsString(const AutocompleteResult& result) {
std::string output(base::StringPrintf("{%" PRIuS "} ", result.size()));
for (size_t i = 0; i < result.size(); ++i) {
AutocompleteMatch match = result.match_at(i);
std::string provider_name = match.provider->name();
output.append(base::StringPrintf("[\"%s\" by \"%s\"] ",
UTF16ToUTF8(match.contents).c_str(),
provider_name.c_str()));
}
return UTF8ToUTF16(output);
}
} // namespace
class OmniboxApiTest : public ExtensionApiTest {
protected:
LocationBar* GetLocationBar() const {
return browser()->window()->GetLocationBar();
}
AutocompleteController* GetAutocompleteController() const {
return GetLocationBar()->location_entry()->model()->popup_model()->
autocomplete_controller();
}
void WaitForTemplateURLServiceToLoad() {
TemplateURLService* model =
TemplateURLServiceFactory::GetForProfile(browser()->profile());
model->Load();
if (!model->loaded()) {
ui_test_utils::WaitForNotification(
chrome::NOTIFICATION_TEMPLATE_URL_SERVICE_LOADED);
}
}
void WaitForAutocompleteDone(AutocompleteController* controller) {
while (!controller->done()) {
ui_test_utils::WaitForNotification(
chrome::NOTIFICATION_AUTOCOMPLETE_CONTROLLER_RESULT_READY);
}
}
};
IN_PROC_BROWSER_TEST_F(OmniboxApiTest, MAYBE_Basic) {
#if defined(TOOLKIT_GTK)
// Disable the timer because, on Lucid at least, it triggers resize/move
// behavior in the browser window, which dismisses the autocomplete popup
// before the results can be read.
static_cast<BrowserWindowGtk*>(
browser()->window())->DisableDebounceTimerForTests(true);
#endif
ASSERT_TRUE(test_server()->Start());
ASSERT_TRUE(RunExtensionTest("omnibox")) << message_;
// The results depend on the TemplateURLService being loaded. Make sure it is
// loaded so that the autocomplete results are consistent.
WaitForTemplateURLServiceToLoad();
LocationBar* location_bar = GetLocationBar();
AutocompleteController* autocomplete_controller = GetAutocompleteController();
// Test that our extension's keyword is suggested to us when we partially type
// it.
{
autocomplete_controller->Start(
ASCIIToUTF16("keywor"), string16(), true, false, true,
AutocompleteInput::ALL_MATCHES);
WaitForAutocompleteDone(autocomplete_controller);
EXPECT_TRUE(autocomplete_controller->done());
EXPECT_EQ(string16(), location_bar->GetInputString());
EXPECT_EQ(string16(), location_bar->location_entry()->GetText());
EXPECT_TRUE(location_bar->location_entry()->IsSelectAll());
// First result should be to search for what was typed, second should be to
// enter "extension keyword" mode.
const AutocompleteResult& result = autocomplete_controller->result();
ASSERT_EQ(2U, result.size()) << AutocompleteResultAsString(result);
AutocompleteMatch match = result.match_at(0);
EXPECT_EQ(AutocompleteMatch::SEARCH_WHAT_YOU_TYPED, match.type);
EXPECT_FALSE(match.deletable);
match = result.match_at(1);
ASSERT_TRUE(match.template_url);
EXPECT_TRUE(match.template_url->IsExtensionKeyword());
EXPECT_EQ(ASCIIToUTF16("keyword"), match.template_url->keyword());
}
// Test that our extension can send suggestions back to us.
{
autocomplete_controller->Start(
ASCIIToUTF16("keyword suggestio"), string16(), true, false, true,
AutocompleteInput::ALL_MATCHES);
WaitForAutocompleteDone(autocomplete_controller);
EXPECT_TRUE(autocomplete_controller->done());
// First result should be to invoke the keyword with what we typed, 2-4
// should be to invoke with suggestions from the extension, and the last
// should be to search for what we typed.
const AutocompleteResult& result = autocomplete_controller->result();
ASSERT_EQ(5U, result.size()) << AutocompleteResultAsString(result);
ASSERT_TRUE(result.match_at(0).template_url);
EXPECT_EQ(ASCIIToUTF16("keyword suggestio"),
result.match_at(0).fill_into_edit);
EXPECT_EQ(ASCIIToUTF16("keyword suggestion1"),
result.match_at(1).fill_into_edit);
EXPECT_EQ(ASCIIToUTF16("keyword suggestion2"),
result.match_at(2).fill_into_edit);
EXPECT_EQ(ASCIIToUTF16("keyword suggestion3"),
result.match_at(3).fill_into_edit);
string16 description =
ASCIIToUTF16("Description with style: <match>, [dim], (url till end)");
EXPECT_EQ(description, result.match_at(1).contents);
ASSERT_EQ(6u, result.match_at(1).contents_class.size());
EXPECT_EQ(0u,
result.match_at(1).contents_class[0].offset);
EXPECT_EQ(ACMatchClassification::NONE,
result.match_at(1).contents_class[0].style);
EXPECT_EQ(description.find('<'),
result.match_at(1).contents_class[1].offset);
EXPECT_EQ(ACMatchClassification::MATCH,
result.match_at(1).contents_class[1].style);
EXPECT_EQ(description.find('>') + 1u,
result.match_at(1).contents_class[2].offset);
EXPECT_EQ(ACMatchClassification::NONE,
result.match_at(1).contents_class[2].style);
EXPECT_EQ(description.find('['),
result.match_at(1).contents_class[3].offset);
EXPECT_EQ(ACMatchClassification::DIM,
result.match_at(1).contents_class[3].style);
EXPECT_EQ(description.find(']') + 1u,
result.match_at(1).contents_class[4].offset);
EXPECT_EQ(ACMatchClassification::NONE,
result.match_at(1).contents_class[4].style);
EXPECT_EQ(description.find('('),
result.match_at(1).contents_class[5].offset);
EXPECT_EQ(ACMatchClassification::URL,
result.match_at(1).contents_class[5].style);
AutocompleteMatch match = result.match_at(4);
EXPECT_EQ(AutocompleteMatch::SEARCH_WHAT_YOU_TYPED, match.type);
EXPECT_FALSE(match.deletable);
}
{
ResultCatcher catcher;
autocomplete_controller->Start(
ASCIIToUTF16("keyword command"), string16(), true, false, true,
AutocompleteInput::ALL_MATCHES);
location_bar->AcceptInput();
EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
}
}
// Tests that the autocomplete popup doesn't reopen after accepting input for
// a given query.
// http://crbug.com/88552
IN_PROC_BROWSER_TEST_F(OmniboxApiTest, PopupStaysClosed) {
#if defined(TOOLKIT_GTK)
// Disable the timer because, on Lucid at least, it triggers resize/move
// behavior in the browser window, which dismisses the autocomplete popup
// before the results can be read.
static_cast<BrowserWindowGtk*>(
browser()->window())->DisableDebounceTimerForTests(true);
#endif
ASSERT_TRUE(test_server()->Start());
ASSERT_TRUE(RunExtensionTest("omnibox")) << message_;
// The results depend on the TemplateURLService being loaded. Make sure it is
// loaded so that the autocomplete results are consistent.
WaitForTemplateURLServiceToLoad();
LocationBar* location_bar = GetLocationBar();
AutocompleteController* autocomplete_controller = GetAutocompleteController();
AutocompletePopupModel* popup_model =
GetLocationBar()->location_entry()->model()->popup_model();
// Input a keyword query and wait for suggestions from the extension.
autocomplete_controller->Start(
ASCIIToUTF16("keyword comman"), string16(), true, false, true,
AutocompleteInput::ALL_MATCHES);
WaitForAutocompleteDone(autocomplete_controller);
EXPECT_TRUE(autocomplete_controller->done());
EXPECT_TRUE(popup_model->IsOpen());
// Quickly type another query and accept it before getting suggestions back
// for the query. The popup will close after accepting input - ensure that it
// does not reopen when the extension returns its suggestions.
ResultCatcher catcher;
autocomplete_controller->Start(
ASCIIToUTF16("keyword command"), string16(), true, false, true,
AutocompleteInput::ALL_MATCHES);
location_bar->AcceptInput();
WaitForAutocompleteDone(autocomplete_controller);
EXPECT_TRUE(autocomplete_controller->done());
EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
EXPECT_FALSE(popup_model->IsOpen());
}
<commit_msg>Use current profile rather than AllSources for notification sources when registering for NOTIFICATION_AUTOCOMPLETE_CONTROLLER_RESULT_READY.<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 "base/format_macros.h"
#include "base/string_util.h"
#include "base/stringprintf.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/autocomplete/autocomplete.h"
#include "chrome/browser/autocomplete/autocomplete_edit.h"
#include "chrome/browser/autocomplete/autocomplete_match.h"
#include "chrome/browser/autocomplete/autocomplete_popup_model.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/search_engines/template_url.h"
#include "chrome/browser/search_engines/template_url_service.h"
#include "chrome/browser/search_engines/template_url_service_factory.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/omnibox/location_bar.h"
#include "chrome/browser/ui/omnibox/omnibox_view.h"
#include "chrome/common/chrome_notification_types.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/common/content_notification_types.h"
#if defined(TOOLKIT_GTK)
#include "chrome/browser/ui/gtk/browser_window_gtk.h"
#endif
// Basic test is flaky on ChromeOS.
// http://crbug.com/52929
#if defined(OS_CHROMEOS)
#define MAYBE_Basic FLAKY_Basic
#else
#define MAYBE_Basic Basic
#endif
namespace {
string16 AutocompleteResultAsString(const AutocompleteResult& result) {
std::string output(base::StringPrintf("{%" PRIuS "} ", result.size()));
for (size_t i = 0; i < result.size(); ++i) {
AutocompleteMatch match = result.match_at(i);
std::string provider_name = match.provider->name();
output.append(base::StringPrintf("[\"%s\" by \"%s\"] ",
UTF16ToUTF8(match.contents).c_str(),
provider_name.c_str()));
}
return UTF8ToUTF16(output);
}
} // namespace
class OmniboxApiTest : public ExtensionApiTest {
protected:
LocationBar* GetLocationBar() const {
return browser()->window()->GetLocationBar();
}
AutocompleteController* GetAutocompleteController() const {
return GetLocationBar()->location_entry()->model()->popup_model()->
autocomplete_controller();
}
void WaitForTemplateURLServiceToLoad() {
TemplateURLService* model =
TemplateURLServiceFactory::GetForProfile(browser()->profile());
model->Load();
if (!model->loaded()) {
ui_test_utils::WaitForNotification(
chrome::NOTIFICATION_TEMPLATE_URL_SERVICE_LOADED);
}
}
void WaitForAutocompleteDone(AutocompleteController* controller) {
while (!controller->done()) {
ui_test_utils::WaitForNotificationFrom(
chrome::NOTIFICATION_AUTOCOMPLETE_CONTROLLER_RESULT_READY,
Source<AutocompleteController>(controller));
}
}
};
IN_PROC_BROWSER_TEST_F(OmniboxApiTest, MAYBE_Basic) {
#if defined(TOOLKIT_GTK)
// Disable the timer because, on Lucid at least, it triggers resize/move
// behavior in the browser window, which dismisses the autocomplete popup
// before the results can be read.
static_cast<BrowserWindowGtk*>(
browser()->window())->DisableDebounceTimerForTests(true);
#endif
ASSERT_TRUE(test_server()->Start());
ASSERT_TRUE(RunExtensionTest("omnibox")) << message_;
// The results depend on the TemplateURLService being loaded. Make sure it is
// loaded so that the autocomplete results are consistent.
WaitForTemplateURLServiceToLoad();
LocationBar* location_bar = GetLocationBar();
AutocompleteController* autocomplete_controller = GetAutocompleteController();
// Test that our extension's keyword is suggested to us when we partially type
// it.
{
autocomplete_controller->Start(
ASCIIToUTF16("keywor"), string16(), true, false, true,
AutocompleteInput::ALL_MATCHES);
WaitForAutocompleteDone(autocomplete_controller);
EXPECT_TRUE(autocomplete_controller->done());
EXPECT_EQ(string16(), location_bar->GetInputString());
EXPECT_EQ(string16(), location_bar->location_entry()->GetText());
EXPECT_TRUE(location_bar->location_entry()->IsSelectAll());
// First result should be to search for what was typed, second should be to
// enter "extension keyword" mode.
const AutocompleteResult& result = autocomplete_controller->result();
ASSERT_EQ(2U, result.size()) << AutocompleteResultAsString(result);
AutocompleteMatch match = result.match_at(0);
EXPECT_EQ(AutocompleteMatch::SEARCH_WHAT_YOU_TYPED, match.type);
EXPECT_FALSE(match.deletable);
match = result.match_at(1);
ASSERT_TRUE(match.template_url);
EXPECT_TRUE(match.template_url->IsExtensionKeyword());
EXPECT_EQ(ASCIIToUTF16("keyword"), match.template_url->keyword());
}
// Test that our extension can send suggestions back to us.
{
autocomplete_controller->Start(
ASCIIToUTF16("keyword suggestio"), string16(), true, false, true,
AutocompleteInput::ALL_MATCHES);
WaitForAutocompleteDone(autocomplete_controller);
EXPECT_TRUE(autocomplete_controller->done());
// First result should be to invoke the keyword with what we typed, 2-4
// should be to invoke with suggestions from the extension, and the last
// should be to search for what we typed.
const AutocompleteResult& result = autocomplete_controller->result();
ASSERT_EQ(5U, result.size()) << AutocompleteResultAsString(result);
ASSERT_TRUE(result.match_at(0).template_url);
EXPECT_EQ(ASCIIToUTF16("keyword suggestio"),
result.match_at(0).fill_into_edit);
EXPECT_EQ(ASCIIToUTF16("keyword suggestion1"),
result.match_at(1).fill_into_edit);
EXPECT_EQ(ASCIIToUTF16("keyword suggestion2"),
result.match_at(2).fill_into_edit);
EXPECT_EQ(ASCIIToUTF16("keyword suggestion3"),
result.match_at(3).fill_into_edit);
string16 description =
ASCIIToUTF16("Description with style: <match>, [dim], (url till end)");
EXPECT_EQ(description, result.match_at(1).contents);
ASSERT_EQ(6u, result.match_at(1).contents_class.size());
EXPECT_EQ(0u,
result.match_at(1).contents_class[0].offset);
EXPECT_EQ(ACMatchClassification::NONE,
result.match_at(1).contents_class[0].style);
EXPECT_EQ(description.find('<'),
result.match_at(1).contents_class[1].offset);
EXPECT_EQ(ACMatchClassification::MATCH,
result.match_at(1).contents_class[1].style);
EXPECT_EQ(description.find('>') + 1u,
result.match_at(1).contents_class[2].offset);
EXPECT_EQ(ACMatchClassification::NONE,
result.match_at(1).contents_class[2].style);
EXPECT_EQ(description.find('['),
result.match_at(1).contents_class[3].offset);
EXPECT_EQ(ACMatchClassification::DIM,
result.match_at(1).contents_class[3].style);
EXPECT_EQ(description.find(']') + 1u,
result.match_at(1).contents_class[4].offset);
EXPECT_EQ(ACMatchClassification::NONE,
result.match_at(1).contents_class[4].style);
EXPECT_EQ(description.find('('),
result.match_at(1).contents_class[5].offset);
EXPECT_EQ(ACMatchClassification::URL,
result.match_at(1).contents_class[5].style);
AutocompleteMatch match = result.match_at(4);
EXPECT_EQ(AutocompleteMatch::SEARCH_WHAT_YOU_TYPED, match.type);
EXPECT_FALSE(match.deletable);
}
{
ResultCatcher catcher;
autocomplete_controller->Start(
ASCIIToUTF16("keyword command"), string16(), true, false, true,
AutocompleteInput::ALL_MATCHES);
location_bar->AcceptInput();
EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
}
}
// Tests that the autocomplete popup doesn't reopen after accepting input for
// a given query.
// http://crbug.com/88552
IN_PROC_BROWSER_TEST_F(OmniboxApiTest, PopupStaysClosed) {
#if defined(TOOLKIT_GTK)
// Disable the timer because, on Lucid at least, it triggers resize/move
// behavior in the browser window, which dismisses the autocomplete popup
// before the results can be read.
static_cast<BrowserWindowGtk*>(
browser()->window())->DisableDebounceTimerForTests(true);
#endif
ASSERT_TRUE(test_server()->Start());
ASSERT_TRUE(RunExtensionTest("omnibox")) << message_;
// The results depend on the TemplateURLService being loaded. Make sure it is
// loaded so that the autocomplete results are consistent.
WaitForTemplateURLServiceToLoad();
LocationBar* location_bar = GetLocationBar();
AutocompleteController* autocomplete_controller = GetAutocompleteController();
AutocompletePopupModel* popup_model =
GetLocationBar()->location_entry()->model()->popup_model();
// Input a keyword query and wait for suggestions from the extension.
autocomplete_controller->Start(
ASCIIToUTF16("keyword comman"), string16(), true, false, true,
AutocompleteInput::ALL_MATCHES);
WaitForAutocompleteDone(autocomplete_controller);
EXPECT_TRUE(autocomplete_controller->done());
EXPECT_TRUE(popup_model->IsOpen());
// Quickly type another query and accept it before getting suggestions back
// for the query. The popup will close after accepting input - ensure that it
// does not reopen when the extension returns its suggestions.
ResultCatcher catcher;
autocomplete_controller->Start(
ASCIIToUTF16("keyword command"), string16(), true, false, true,
AutocompleteInput::ALL_MATCHES);
location_bar->AcceptInput();
WaitForAutocompleteDone(autocomplete_controller);
EXPECT_TRUE(autocomplete_controller->done());
EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
EXPECT_FALSE(popup_model->IsOpen());
}
<|endoftext|>
|
<commit_before>#include "script_loader.h"
using namespace LuaScript;
ScriptLoader::File::File(std::string const& path) : path_(path) {
//TODO: find filename
//prob split on '/' and take latest, then split on '.' and take everything but the last one if there's more than one
}
ScriptLoader::ScriptLoader(std::shared_ptr<EntitySystem> entity_system, uint16_t map_id, std::string const& path):
entity_system_(entity_system),
logger_(Core::CLog::GetLogger(Core::log_type::SCRIPTLOADER).lock()),
path_(path), map_id_(map_id) {
state_.open_libraries(); //FIXME: check if we need all libs
state_.set_function("include", [this](std::string path) {
load_script(path);
});
}
void ScriptLoader::load_script() {
reload_scripts(path_);
}
void ScriptLoader::load_npcs() {
for (auto& [file, entities] : npc_files_) {
entity_system_->bulk_destroy(entities);
entities.clear();
load_script(file.path_);
}
}
void ScriptLoader::load_warpgates() {
for (auto& [file, entities] : warpgate_files_) {
entity_system_->bulk_destroy(entities);
entities.clear();
load_script(file.path_);
}
}
void ScriptLoader::load_spawners() {
for (auto& [file, entities] : spawner_files_) {
entity_system_->bulk_destroy(entities);
entities.clear();
load_script(file.path_);
}
}
void ScriptLoader::load_script(std::string const& path) {
try {
sol::environment env{state_, sol::create, state_.globals()};
auto [warpgate_file, ok] = warpgate_files_.insert(File{path}, {});
env.set_function("warp_gate", [warpgate_file](std::string alias, int dest_map_id, float dest_x, float dest_y, float dest_z, int map_id, float x, float y, float z, float angle, float x_scale, float y_scale, float z_scale) {
wargate_file->second.push_back(entity_system_->create_warpgate(alias, dest_map_id, dest_x, dest_y, dest_z, map_id, x, y, z, angle, x_scale, y_scale, z_scale));
});
auto [npc_file, ok] = npc_files_.insert(File{path}, {});
env.set_function("npc", [npc_file](std::string npc_lua, int npc_id, int map_id, float x, float y, float z, float angle) {
npc_file->second.push_back(entity_system_->create_npc(npc_lua, npc_id, map_id, x, y, z, angle));
});
auto [spawner_file, ok] = spawner_files_.insert(File{path}, {});
env.set_function("mob", [spawner_file](std::string alias, int mob_id, int mob_count, int limit, int interval, int range, int map_id, float x, float y, float z) {
spawner_file->second.push_back(entity_system->create_spawner(alias, mob_id, mob_count, limit, interval, range, map_id, x, y, z));
});
state_.script(path, env);
logger_->info("Finished (re)loading scripts from '{}'", path);
} catch (const sol::error& e) {
logger_->error("Error (re)loading lua scripts '{}' : {}", path, e.what());
}
}
<commit_msg>Update script_loader.cpp<commit_after>#include "script_loader.h"
using namespace LuaScript;
ScriptLoader::File::File(std::string const& path) : path_(path) {
//TODO: find filename
//prob split on '/' and take latest, then split on '.' and take everything but the last one if there's more than one
}
ScriptLoader::ScriptLoader(std::shared_ptr<EntitySystem> entity_system, uint16_t map_id, std::string const& path):
entity_system_(entity_system),
logger_(Core::CLog::GetLogger(Core::log_type::SCRIPTLOADER).lock()),
path_(path), map_id_(map_id) {
state_.open_libraries(); //FIXME: check if we need all libs
state_.set_function("include", [this](std::string path) {
load_script(path);
});
}
void ScriptLoader::load_script() {
reload_scripts(path_);
}
void ScriptLoader::load_npcs() {
for (auto& [file, entities] : npc_files_) {
entity_system_->bulk_destroy(entities);
entities.clear();
load_script(file.path_);
}
}
void ScriptLoader::load_warpgates() {
for (auto& [file, entities] : warpgate_files_) {
entity_system_->bulk_destroy(entities);
entities.clear();
load_script(file.path_);
}
}
void ScriptLoader::load_spawners() {
for (auto& [file, entities] : spawner_files_) {
entity_system_->bulk_destroy(entities);
entities.clear();
load_script(file.path_);
}
}
void ScriptLoader::load_script(std::string const& path) {
try {
File file = File{path};
sol::environment env{state_, sol::create, state_.globals()};
auto warpgate_file = warpgate_files_.find(files);
std::vector<Entity> warpgates;
if (warpgate_file != warpgate_files_.end()) {
warpgates = std::move(warpgate_file->second);
}
env.set_function("warp_gate", [warpgates](std::string alias, int dest_map_id, float dest_x, float dest_y, float dest_z, int map_id, float x, float y, float z, float angle, float x_scale, float y_scale, float z_scale) {
warpgates.push_back(entity_system_->create_warpgate(alias, dest_map_id, dest_x, dest_y, dest_z, map_id, x, y, z, angle, x_scale, y_scale, z_scale));
});
auto npc_file = npc_files_.find(file);
std::vector<Entity> npcs;
if (npc_file != npc_files_.end()) {
npcs = std::move(npc_file->second);
}
env.set_function("npc", [npc_file](std::string npc_lua, int npc_id, int map_id, float x, float y, float z, float angle) {
npc_file->second.push_back(entity_system_->create_npc(npc_lua, npc_id, map_id, x, y, z, angle));
});
auto spawner_file = spawner_files_.find(file);
std::vector<Entity> spawners;
if (spawner_file != spawner_files_.end()) {
spawners = std::move(spawners_file->second);
}
env.set_function("mob", [spawners](std::string alias, int mob_id, int mob_count, int limit, int interval, int range, int map_id, float x, float y, float z) {
spawners.push_back(entity_system->create_spawner(alias, mob_id, mob_count, limit, interval, range, map_id, x, y, z));
});
state_.script(path, env);
logger_->info("Finished (re)loading scripts from '{}'", path);
if (warpgates.size()) warpgate_files_.insert_or_assign(std::make_pair(file, std::move(warpgates)));
if (npcs.size()) npc_files_.insert_or_assign(std::make_pair(file, std::move(npcs)));
if (spawners.size()) spawner_files_.insert_or_assign(std::make_pair(file, std::move(spawners)));
} catch (const sol::error& e) {
logger_->error("Error (re)loading lua scripts '{}' : {}", path, e.what());
}
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/file_path.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/defaults.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
typedef InProcessBrowserTest SessionRestoreTest;
#if !defined(OS_WIN)
// http://crbug.com/39476
#define RestoreOnNewWindowWithNoTabbedBrowsers \
DISABLED_RestoreOnNewWindowWithNoTabbedBrowsers
#endif
// Makes sure when session restore is triggered in the same process we don't end
// up with an extra tab.
IN_PROC_BROWSER_TEST_F(SessionRestoreTest,
RestoreOnNewWindowWithNoTabbedBrowsers) {
if (browser_defaults::kRestorePopups)
return;
const FilePath::CharType* kTitle1File = FILE_PATH_LITERAL("title1.html");
GURL url(ui_test_utils::GetTestUrl(FilePath(FilePath::kCurrentDirectory),
FilePath(kTitle1File)));
ui_test_utils::NavigateToURL(browser(), url);
// Turn on session restore.
SessionStartupPref::SetStartupPref(
browser()->profile(),
SessionStartupPref(SessionStartupPref::LAST));
// Create a new popup.
Profile* profile = browser()->profile();
Browser* popup = Browser::CreateForPopup(profile);
popup->window()->Show();
// Close the browser.
browser()->window()->Close();
// Create a new window, which should trigger session restore.
popup->NewWindow();
Browser* new_browser = ui_test_utils::WaitForNewBrowser();
ASSERT_TRUE(new_browser != NULL);
// The browser should only have one tab.
ASSERT_EQ(1, new_browser->tab_count());
// And the first url should be url.
EXPECT_EQ(url, new_browser->GetTabContentsAt(0)->GetURL());
}
<commit_msg>TTF: Enable RestoreOnNewWindowWithNoTabbedBrowsers, as it seems to be working now.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/file_path.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/defaults.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
typedef InProcessBrowserTest SessionRestoreTest;
// Makes sure when session restore is triggered in the same process we don't end
// up with an extra tab.
IN_PROC_BROWSER_TEST_F(SessionRestoreTest,
RestoreOnNewWindowWithNoTabbedBrowsers) {
if (browser_defaults::kRestorePopups)
return;
const FilePath::CharType* kTitle1File = FILE_PATH_LITERAL("title1.html");
GURL url(ui_test_utils::GetTestUrl(FilePath(FilePath::kCurrentDirectory),
FilePath(kTitle1File)));
ui_test_utils::NavigateToURL(browser(), url);
// Turn on session restore.
SessionStartupPref::SetStartupPref(
browser()->profile(),
SessionStartupPref(SessionStartupPref::LAST));
// Create a new popup.
Profile* profile = browser()->profile();
Browser* popup = Browser::CreateForPopup(profile);
popup->window()->Show();
// Close the browser.
browser()->window()->Close();
// Create a new window, which should trigger session restore.
popup->NewWindow();
Browser* new_browser = ui_test_utils::WaitForNewBrowser();
ASSERT_TRUE(new_browser != NULL);
// The browser should only have one tab.
ASSERT_EQ(1, new_browser->tab_count());
// And the first url should be url.
EXPECT_EQ(url, new_browser->GetTabContentsAt(0)->GetURL());
}
<|endoftext|>
|
<commit_before>//===--- DeprecatedIosBaseAliasesCheck.cpp - clang-tidy--------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "DeprecatedIosBaseAliasesCheck.h"
#include "clang/AST/ASTContext.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
using namespace clang::ast_matchers;
namespace clang {
namespace tidy {
namespace modernize {
static const std::array<StringRef, 5> DeprecatedTypes = {
{"::std::ios_base::io_state"}, {"::std::ios_base::open_mode"},
{"::std::ios_base::seek_dir"}, {"::std::ios_base::streamoff"},
{"::std::ios_base::streampos"},
};
static const llvm::StringMap<StringRef> ReplacementTypes = {
{"io_state", "iostate"},
{"open_mode", "openmode"},
{"seek_dir", "seekdir"}};
void DeprecatedIosBaseAliasesCheck::registerMatchers(MatchFinder *Finder) {
// Only register the matchers for C++; the functionality currently does not
// provide any benefit to other languages, despite being benign.
if (!getLangOpts().CPlusPlus)
return;
auto IoStateDecl = typedefDecl(hasAnyName(DeprecatedTypes)).bind("TypeDecl");
auto IoStateType =
qualType(hasDeclaration(IoStateDecl), unless(elaboratedType()));
Finder->addMatcher(typeLoc(loc(IoStateType)).bind("TypeLoc"), this);
}
void DeprecatedIosBaseAliasesCheck::check(
const MatchFinder::MatchResult &Result) {
SourceManager &SM = *Result.SourceManager;
const auto *Typedef = Result.Nodes.getNodeAs<TypedefDecl>("TypeDecl");
StringRef TypeName = Typedef->getName();
bool HasReplacement = ReplacementTypes.count(TypeName);
const auto *TL = Result.Nodes.getNodeAs<TypeLoc>("TypeLoc");
SourceLocation IoStateLoc = TL->getBeginLoc();
// Do not generate fixits for matches depending on template arguments and
// macro expansions.
bool Fix = HasReplacement && !TL->getType()->isDependentType();
if (IoStateLoc.isMacroID()) {
IoStateLoc = SM.getSpellingLoc(IoStateLoc);
Fix = false;
}
SourceLocation EndLoc = IoStateLoc.getLocWithOffset(TypeName.size() - 1);
if (HasReplacement) {
auto FixName = ReplacementTypes.lookup(TypeName);
auto Builder = diag(IoStateLoc, "'std::ios_base::%0' is deprecated; use "
"'std::ios_base::%1' instead")
<< TypeName << FixName;
if (Fix)
Builder << FixItHint::CreateReplacement(SourceRange(IoStateLoc, EndLoc),
FixName);
} else
diag(IoStateLoc, "'std::ios_base::%0' is deprecated") << TypeName;
}
} // namespace modernize
} // namespace tidy
} // namespace clang
<commit_msg>Revert rL343916: Fix -Wmissing-braces warning. NFCI.<commit_after>//===--- DeprecatedIosBaseAliasesCheck.cpp - clang-tidy--------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "DeprecatedIosBaseAliasesCheck.h"
#include "clang/AST/ASTContext.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
using namespace clang::ast_matchers;
namespace clang {
namespace tidy {
namespace modernize {
static const std::array<StringRef, 5> DeprecatedTypes = {
"::std::ios_base::io_state", "::std::ios_base::open_mode",
"::std::ios_base::seek_dir", "::std::ios_base::streamoff",
"::std::ios_base::streampos",
};
static const llvm::StringMap<StringRef> ReplacementTypes = {
{"io_state", "iostate"},
{"open_mode", "openmode"},
{"seek_dir", "seekdir"}};
void DeprecatedIosBaseAliasesCheck::registerMatchers(MatchFinder *Finder) {
// Only register the matchers for C++; the functionality currently does not
// provide any benefit to other languages, despite being benign.
if (!getLangOpts().CPlusPlus)
return;
auto IoStateDecl = typedefDecl(hasAnyName(DeprecatedTypes)).bind("TypeDecl");
auto IoStateType =
qualType(hasDeclaration(IoStateDecl), unless(elaboratedType()));
Finder->addMatcher(typeLoc(loc(IoStateType)).bind("TypeLoc"), this);
}
void DeprecatedIosBaseAliasesCheck::check(
const MatchFinder::MatchResult &Result) {
SourceManager &SM = *Result.SourceManager;
const auto *Typedef = Result.Nodes.getNodeAs<TypedefDecl>("TypeDecl");
StringRef TypeName = Typedef->getName();
bool HasReplacement = ReplacementTypes.count(TypeName);
const auto *TL = Result.Nodes.getNodeAs<TypeLoc>("TypeLoc");
SourceLocation IoStateLoc = TL->getBeginLoc();
// Do not generate fixits for matches depending on template arguments and
// macro expansions.
bool Fix = HasReplacement && !TL->getType()->isDependentType();
if (IoStateLoc.isMacroID()) {
IoStateLoc = SM.getSpellingLoc(IoStateLoc);
Fix = false;
}
SourceLocation EndLoc = IoStateLoc.getLocWithOffset(TypeName.size() - 1);
if (HasReplacement) {
auto FixName = ReplacementTypes.lookup(TypeName);
auto Builder = diag(IoStateLoc, "'std::ios_base::%0' is deprecated; use "
"'std::ios_base::%1' instead")
<< TypeName << FixName;
if (Fix)
Builder << FixItHint::CreateReplacement(SourceRange(IoStateLoc, EndLoc),
FixName);
} else
diag(IoStateLoc, "'std::ios_base::%0' is deprecated") << TypeName;
}
} // namespace modernize
} // namespace tidy
} // namespace clang
<|endoftext|>
|
<commit_before>#include <pcl/kdtree/kdtree_flann.h>
#include "CompetitionController.h"
using namespace IGVC::Sensors;
using namespace std;
namespace IGVC
{
namespace Control
{
CompetitionController::CompetitionController(IGVC::Sensors::GPS* gps,
Event<pcl::PointCloud<pcl::PointXYZ> >* mapSource,
WaypointReader* waypointReader,
MotorDriver* driver)
: _hasAllData(false),
GPS_BUFFER_SIZE(5),
LOnNewGPSData(this),
LOnNewIMUData(this),
LOnNewMapFrame(this),
_viewer("Map and Path")
{
_gps = gps;
_gps->onNewData += &LOnNewGPSData;
_waypointReader = waypointReader;
_waypointReader->Next();
_currentHeading = 0;
_driver = driver;
(*mapSource) += &LOnNewMapFrame;
MaxW = 0.8;
DeltaT = 0.1;
}
bool CompetitionController::isRunning()
{
return true;
}
void CompetitionController::OnNewGPSData(GPSData data)
{
std::cout << "Compcon gps" << std::endl;
if(_gpsBuffer.size() >= GPS_BUFFER_SIZE)
{
_gpsBuffer.push_back(data);
GPSData last = _gpsBuffer.back();
_currentAvgGPS.Lat(_currentAvgGPS.Lat() - ( last.Lat() / GPS_BUFFER_SIZE ));
_currentAvgGPS.Long(_currentAvgGPS.Long() - ( last.Long() / GPS_BUFFER_SIZE ));
_currentAvgGPS.Heading(_currentAvgGPS.Heading() - ( last.Heading() / GPS_BUFFER_SIZE ));
_currentAvgGPS.Speed(_currentAvgGPS.Speed() - ( last.Speed() / GPS_BUFFER_SIZE ));
_gpsBuffer.erase(_gpsBuffer.begin());
}
else
{
_gpsBuffer.push_back(data);
}
_currentAvgGPS.Lat(_currentAvgGPS.Lat() + ( data.Lat() / GPS_BUFFER_SIZE ));
_currentAvgGPS.Long(_currentAvgGPS.Long() + ( data.Long() / GPS_BUFFER_SIZE ));
_currentAvgGPS.Heading(_currentAvgGPS.Heading() + ( data.Heading() / GPS_BUFFER_SIZE ));
_currentAvgGPS.Speed(_currentAvgGPS.Speed() + ( data.Speed() / GPS_BUFFER_SIZE ));
_hasAllData = true;
}
void CompetitionController::OnNewIMUData(IMURawData data)
{
std::cout << "Compcon imu" << std::endl;
_currentHeading = data.heading;
}
/*
void CompetitionController::OnNewMapFrame(pcl::PointCloud<pcl::PointXYZ> mapFrame)
{
cout << mapFrame.points.size() << " points recieved." << endl;
if(!_hasAllData)
return;
_viewer.removeAllPointClouds(0);
_viewer.removeAllShapes();
_viewer.addPointCloud(mapFrame.makeShared(), "map");
_viewer.setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 5, "map");
_viewer.spin();
std::cout << "Compcon newMap" << std::endl;
vector< pair<double, double> > available_actions;
using namespace std;
cout << "Loading possible actions" << endl;
double v = 0.4;
for(double w = -MaxW; w <= MaxW; w += 0.5)
{
pcl::KdTreeFLANN<pcl::PointXYZ> kdtree;
kdtree.setInputCloud(mapFrame.makeShared());
pair<double, double> end = result(w,v);
pcl::PointXYZ searchPoint(end.first, end.second, 0);
std::vector<int> pointIdxRadiusSearch;
std::vector<float> pointRadiusSquaredDistance;
if(kdtree.radiusSearch(searchPoint, 0.01, pointIdxRadiusSearch, pointRadiusSquaredDistance) == 0)
{
available_actions.push_back(pair<double,double>(v, w));
}
}
cout << "Checking possible actions..." << endl;
pair<double, double> minPair;
double minDist = -1;
for(vector< pair<double, double> >::iterator iter = available_actions.begin(); iter != available_actions.end(); iter++)
{
pair<double, double> action = (*iter);
cout << "Action done" << endl;
pair<double, double> waypointCoords;
cout << _waypointReader->Current().Lat() << endl;
waypointCoords.first = GPSdX(_currentAvgGPS, _waypointReader->Current());
waypointCoords.second = GPSdY(_currentAvgGPS, _waypointReader->Current());
cout << "loaded" << endl;
pair<double, double> endLoc = result(action.second, action.first);
cout << "resulted" << endl;
double dist = distBetween(waypointCoords, endLoc);
cout << "dist" << endl;
if(minDist == -1 || dist < minDist)
{
minPair = action;
minDist = dist;
}
}
cout << "Computing velocities..." << endl;
double Baseline = Robot::CurrentRobot().Baseline();
double Vr = minPair.first + (Baseline/2.0)*minPair.second;
double Vl = minPair.first - (Baseline/2.0)*minPair.second;
cout << "Decided on Vl=" << Vl << " and Vr=" << Vr << endl;
_driver->setVelocities(Vl, Vr);
}
*/
double CompetitionController::weighting(double delta)
{
if (delta !=0 )
{
//return 1/pow(delta,2);
return 1/delta;
}
else
{
std::cout << "input to weighting function was 0. This should not have happened" << std::endl;
return 0;
}
}
void CompetitionController::OnNewMapFrame(pcl::PointCloud<pcl::PointXYZ> mapFrame)
{
//cout << mapFrame.points.size() << " points recieved." << endl;
//Bunch of Visualization stuff
if(!_hasAllData)
return;
_viewer.removeAllPointClouds(0);
_viewer.removeAllShapes();
_viewer.addPointCloud(mapFrame.makeShared(), "map");
_viewer.setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 5, "map");
_viewer.spin();
std::cout << "Compcon newMap" << std::endl;
vector< pair<double, double> > available_actions;
//cout << "Loading possible actions" << endl;
//Find Potential Routes
double v = 0.4; //meters per second
double wInc = 0.05; //step size between possible omegas
int i=0; //servers as an iterator for scores so the desired index doesnt have to be rederied from w
double deltaDeltaT=0.1;
const int nPaths = floor((2*MaxW)/wInc);
std::vector<double> scores;
scores.assign(nPaths,0);
double minDeltaT = Robot::CurrentRobot().Dist2Front()/v;
for(double w = -MaxW; w <= MaxW; w += wInc)
{
for(double T = deltaDeltaT;T<=DeltaT;T+=deltaDeltaT)
{
pcl::KdTreeFLANN<pcl::PointXYZ> kdtree;
kdtree.setInputCloud(mapFrame.makeShared());
pair<double, double> end = result(w,v,T);
pcl::PointXYZ searchPoint(end.first, end.second, 0);
std::vector<int> pointIdxRadiusSearch;
std::vector<float> pointRadiusSquaredDistance;
if(kdtree.radiusSearch(searchPoint, 0.1, pointIdxRadiusSearch, pointRadiusSquaredDistance) == 0)
{
}
else
{
scores[i]+=weighting(T);
}
}
i++;
}
int minArg = 0;
int secondMinArg = 0;
int min = 50000;
int currentScore;
for(int j=0;j<nPaths;j++)
{
currentScore = scores[j];
if (currentScore<min)
{
secondMinArg = minArg;
minArg = secondMinArg;
min = currentScore;
}
}
cout << "minArg is" << endl;
//available_actions.push_back(pair<double,double>(v, w));
pair<double, double> minPair;
minPair.first = v;
minPair.second = -MaxW+wInc*minArg;
/*
double minDist = -1;
for(vector< pair<double, double> >::iterator iter = available_actions.begin(); iter != available_actions.end(); iter++)
{
pair<double, double> action = (*iter);
cout << "Action done" << endl;
pair<double, double> waypointCoords;
cout << _waypointReader->Current().Lat() << endl;
waypointCoords.first = GPSdX(_currentAvgGPS, _waypointReader->Current());
waypointCoords.second = GPSdY(_currentAvgGPS, _waypointReader->Current());
cout << "loaded" << endl;
pair<double, double> endLoc = result(action.second, action.first);
cout << "resulted" << endl;
double dist = distBetween(waypointCoords, endLoc);
cout << "dist" << endl;
if(minDist == -1 || dist < minDist)
{
minPair = action;
minDist = dist;
}
}
cout << "Computing velocities..." << endl;
double Baseline = Robot::CurrentRobot().Baseline();
double Vr = minPair.first + (Baseline/2.0)*minPair.second;
double Vl = minPair.first - (Baseline/2.0)*minPair.second;
cout << "Decided on Vl=" << Vl << " and Vr=" << Vr << endl;
_driver->setVelocities(Vl, Vr);
*/
}
double CompetitionController::headingFromAToB(GPSData A, GPSData B)
{
double dy = B.Lat() - A.Lat();
double dx = cos(M_PI/180.0*A.Lat())*(B.Long() - A.Long());
return atan2(dy, dx);
}
double CompetitionController::distBetween(GPSData A, GPSData B)
{
double dy = B.Lat() - A.Lat();
double dx = cos(M_PI/180.0*A.Lat())*(B.Long() - A.Long());
return sqrt(dx*dx + dy*dy);
}
double CompetitionController::distBetween(pair<double, double> A, pair<double, double> B)
{
double dy = B.second - A.second;
double dx = B.first - A.first;
return sqrt(dx*dx + dy*dy);
}
double CompetitionController::GPSdX(GPSData A, GPSData B)
{
return cos(M_PI/180.0*A.Lat())*(B.Long() - A.Long());
}
double CompetitionController::GPSdY(GPSData A, GPSData B)
{
return B.Lat() - A.Lat();
}
pair<double, double> CompetitionController::result(double W, double V)
{
Eigen::Vector3d endLocation;
if(W != 0)
{
double R = V / W;
double ICCx = cos(- M_PI/2.0) * R;
double ICCy = sin(- M_PI/2.0) * R;
using namespace Eigen;
Matrix3d T;
double wdt = W*DeltaT;
T << cos(wdt), -sin(wdt), 0, sin(wdt), cos(wdt), 0, 0, 0, 1;
Vector3d a(-ICCx, -ICCy, 0);
Vector3d b(ICCx, ICCy, wdt);
endLocation = T * a + b;
}
else
{
endLocation[0] = 0;
endLocation[1] = V * DeltaT;
}
return pair<double, double> (endLocation[0], endLocation[1]);
}
pair<double, double> CompetitionController::result(double W, double V, double dt)
{
Eigen::Vector3d endLocation;
if(W != 0)
{
double R = V / W;
double ICCx = cos(- M_PI/2.0) * R;
double ICCy = sin(- M_PI/2.0) * R;
using namespace Eigen;
Matrix3d T;
double wdt = W*dt;
T << cos(wdt), -sin(wdt), 0, sin(wdt), cos(wdt), 0, 0, 0, 1;
Vector3d a(-ICCx, -ICCy, 0);
Vector3d b(ICCx, ICCy, wdt);
endLocation = T * a + b;
}
else
{
endLocation[0] = 0;
endLocation[1] = V * dt;
}
return pair<double, double> (endLocation[0], endLocation[1]);
}
CompetitionController::~CompetitionController()
{
if(_gps)
_gps->onNewData -= &LOnNewGPSData;
}
}
}
<commit_msg>changed DeltaT<commit_after>#include <pcl/kdtree/kdtree_flann.h>
#include "CompetitionController.h"
using namespace IGVC::Sensors;
using namespace std;
namespace IGVC
{
namespace Control
{
CompetitionController::CompetitionController(IGVC::Sensors::GPS* gps,
Event<pcl::PointCloud<pcl::PointXYZ> >* mapSource,
WaypointReader* waypointReader,
MotorDriver* driver)
: _hasAllData(false),
GPS_BUFFER_SIZE(5),
LOnNewGPSData(this),
LOnNewIMUData(this),
LOnNewMapFrame(this),
_viewer("Map and Path")
{
_gps = gps;
_gps->onNewData += &LOnNewGPSData;
_waypointReader = waypointReader;
_waypointReader->Next();
_currentHeading = 0;
_driver = driver;
(*mapSource) += &LOnNewMapFrame;
MaxW = 0.8;
DeltaT = 1.5
}
bool CompetitionController::isRunning()
{
return true;
}
void CompetitionController::OnNewGPSData(GPSData data)
{
std::cout << "Compcon gps" << std::endl;
if(_gpsBuffer.size() >= GPS_BUFFER_SIZE)
{
_gpsBuffer.push_back(data);
GPSData last = _gpsBuffer.back();
_currentAvgGPS.Lat(_currentAvgGPS.Lat() - ( last.Lat() / GPS_BUFFER_SIZE ));
_currentAvgGPS.Long(_currentAvgGPS.Long() - ( last.Long() / GPS_BUFFER_SIZE ));
_currentAvgGPS.Heading(_currentAvgGPS.Heading() - ( last.Heading() / GPS_BUFFER_SIZE ));
_currentAvgGPS.Speed(_currentAvgGPS.Speed() - ( last.Speed() / GPS_BUFFER_SIZE ));
_gpsBuffer.erase(_gpsBuffer.begin());
}
else
{
_gpsBuffer.push_back(data);
}
_currentAvgGPS.Lat(_currentAvgGPS.Lat() + ( data.Lat() / GPS_BUFFER_SIZE ));
_currentAvgGPS.Long(_currentAvgGPS.Long() + ( data.Long() / GPS_BUFFER_SIZE ));
_currentAvgGPS.Heading(_currentAvgGPS.Heading() + ( data.Heading() / GPS_BUFFER_SIZE ));
_currentAvgGPS.Speed(_currentAvgGPS.Speed() + ( data.Speed() / GPS_BUFFER_SIZE ));
_hasAllData = true;
}
void CompetitionController::OnNewIMUData(IMURawData data)
{
std::cout << "Compcon imu" << std::endl;
_currentHeading = data.heading;
}
/*
void CompetitionController::OnNewMapFrame(pcl::PointCloud<pcl::PointXYZ> mapFrame)
{
cout << mapFrame.points.size() << " points recieved." << endl;
if(!_hasAllData)
return;
_viewer.removeAllPointClouds(0);
_viewer.removeAllShapes();
_viewer.addPointCloud(mapFrame.makeShared(), "map");
_viewer.setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 5, "map");
_viewer.spin();
std::cout << "Compcon newMap" << std::endl;
vector< pair<double, double> > available_actions;
using namespace std;
cout << "Loading possible actions" << endl;
double v = 0.4;
for(double w = -MaxW; w <= MaxW; w += 0.5)
{
pcl::KdTreeFLANN<pcl::PointXYZ> kdtree;
kdtree.setInputCloud(mapFrame.makeShared());
pair<double, double> end = result(w,v);
pcl::PointXYZ searchPoint(end.first, end.second, 0);
std::vector<int> pointIdxRadiusSearch;
std::vector<float> pointRadiusSquaredDistance;
if(kdtree.radiusSearch(searchPoint, 0.01, pointIdxRadiusSearch, pointRadiusSquaredDistance) == 0)
{
available_actions.push_back(pair<double,double>(v, w));
}
}
cout << "Checking possible actions..." << endl;
pair<double, double> minPair;
double minDist = -1;
for(vector< pair<double, double> >::iterator iter = available_actions.begin(); iter != available_actions.end(); iter++)
{
pair<double, double> action = (*iter);
cout << "Action done" << endl;
pair<double, double> waypointCoords;
cout << _waypointReader->Current().Lat() << endl;
waypointCoords.first = GPSdX(_currentAvgGPS, _waypointReader->Current());
waypointCoords.second = GPSdY(_currentAvgGPS, _waypointReader->Current());
cout << "loaded" << endl;
pair<double, double> endLoc = result(action.second, action.first);
cout << "resulted" << endl;
double dist = distBetween(waypointCoords, endLoc);
cout << "dist" << endl;
if(minDist == -1 || dist < minDist)
{
minPair = action;
minDist = dist;
}
}
cout << "Computing velocities..." << endl;
double Baseline = Robot::CurrentRobot().Baseline();
double Vr = minPair.first + (Baseline/2.0)*minPair.second;
double Vl = minPair.first - (Baseline/2.0)*minPair.second;
cout << "Decided on Vl=" << Vl << " and Vr=" << Vr << endl;
_driver->setVelocities(Vl, Vr);
}
*/
double CompetitionController::weighting(double delta)
{
if (delta !=0 )
{
//return 1/pow(delta,2);
return 1/delta;
}
else
{
std::cout << "input to weighting function was 0. This should not have happened" << std::endl;
return 0;
}
}
void CompetitionController::OnNewMapFrame(pcl::PointCloud<pcl::PointXYZ> mapFrame)
{
//cout << mapFrame.points.size() << " points recieved." << endl;
//Bunch of Visualization stuff
if(!_hasAllData)
return;
_viewer.removeAllPointClouds(0);
_viewer.removeAllShapes();
_viewer.addPointCloud(mapFrame.makeShared(), "map");
_viewer.setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 5, "map");
_viewer.spin();
std::cout << "Compcon newMap" << std::endl;
vector< pair<double, double> > available_actions;
//cout << "Loading possible actions" << endl;
//Find Potential Routes
double v = 0.4; //meters per second
double wInc = 0.05; //step size between possible omegas
int i=0; //servers as an iterator for scores so the desired index doesnt have to be rederied from w
double deltaDeltaT=0.1;
const int nPaths = floor((2*MaxW)/wInc);
std::vector<double> scores;
scores.assign(nPaths,0);
double minDeltaT = Robot::CurrentRobot().Dist2Front()/v;
for(double w = -MaxW; w <= MaxW; w += wInc)
{
for(double T = deltaDeltaT;T<=DeltaT;T+=deltaDeltaT)
{
pcl::KdTreeFLANN<pcl::PointXYZ> kdtree;
kdtree.setInputCloud(mapFrame.makeShared());
pair<double, double> end = result(w,v,T);
pcl::PointXYZ searchPoint(end.first, end.second, 0);
std::vector<int> pointIdxRadiusSearch;
std::vector<float> pointRadiusSquaredDistance;
if(kdtree.radiusSearch(searchPoint, 0.1, pointIdxRadiusSearch, pointRadiusSquaredDistance) == 0)
{
}
else
{
scores[i]+=weighting(T);
}
}
i++;
}
int minArg = 0;
int secondMinArg = 0;
int min = 50000;
int currentScore;
for(int j=0;j<nPaths;j++)
{
currentScore = scores[j];
if (currentScore<min)
{
secondMinArg = minArg;
minArg = secondMinArg;
min = currentScore;
}
}
cout << "minArg is" << endl;
//available_actions.push_back(pair<double,double>(v, w));
pair<double, double> minPair;
minPair.first = v;
minPair.second = -MaxW+wInc*minArg;
/*
double minDist = -1;
for(vector< pair<double, double> >::iterator iter = available_actions.begin(); iter != available_actions.end(); iter++)
{
pair<double, double> action = (*iter);
cout << "Action done" << endl;
pair<double, double> waypointCoords;
cout << _waypointReader->Current().Lat() << endl;
waypointCoords.first = GPSdX(_currentAvgGPS, _waypointReader->Current());
waypointCoords.second = GPSdY(_currentAvgGPS, _waypointReader->Current());
cout << "loaded" << endl;
pair<double, double> endLoc = result(action.second, action.first);
cout << "resulted" << endl;
double dist = distBetween(waypointCoords, endLoc);
cout << "dist" << endl;
if(minDist == -1 || dist < minDist)
{
minPair = action;
minDist = dist;
}
}
cout << "Computing velocities..." << endl;
double Baseline = Robot::CurrentRobot().Baseline();
double Vr = minPair.first + (Baseline/2.0)*minPair.second;
double Vl = minPair.first - (Baseline/2.0)*minPair.second;
cout << "Decided on Vl=" << Vl << " and Vr=" << Vr << endl;
_driver->setVelocities(Vl, Vr);
*/
}
double CompetitionController::headingFromAToB(GPSData A, GPSData B)
{
double dy = B.Lat() - A.Lat();
double dx = cos(M_PI/180.0*A.Lat())*(B.Long() - A.Long());
return atan2(dy, dx);
}
double CompetitionController::distBetween(GPSData A, GPSData B)
{
double dy = B.Lat() - A.Lat();
double dx = cos(M_PI/180.0*A.Lat())*(B.Long() - A.Long());
return sqrt(dx*dx + dy*dy);
}
double CompetitionController::distBetween(pair<double, double> A, pair<double, double> B)
{
double dy = B.second - A.second;
double dx = B.first - A.first;
return sqrt(dx*dx + dy*dy);
}
double CompetitionController::GPSdX(GPSData A, GPSData B)
{
return cos(M_PI/180.0*A.Lat())*(B.Long() - A.Long());
}
double CompetitionController::GPSdY(GPSData A, GPSData B)
{
return B.Lat() - A.Lat();
}
pair<double, double> CompetitionController::result(double W, double V)
{
Eigen::Vector3d endLocation;
if(W != 0)
{
double R = V / W;
double ICCx = cos(- M_PI/2.0) * R;
double ICCy = sin(- M_PI/2.0) * R;
using namespace Eigen;
Matrix3d T;
double wdt = W*DeltaT;
T << cos(wdt), -sin(wdt), 0, sin(wdt), cos(wdt), 0, 0, 0, 1;
Vector3d a(-ICCx, -ICCy, 0);
Vector3d b(ICCx, ICCy, wdt);
endLocation = T * a + b;
}
else
{
endLocation[0] = 0;
endLocation[1] = V * DeltaT;
}
return pair<double, double> (endLocation[0], endLocation[1]);
}
pair<double, double> CompetitionController::result(double W, double V, double dt)
{
Eigen::Vector3d endLocation;
if(W != 0)
{
double R = V / W;
double ICCx = cos(- M_PI/2.0) * R;
double ICCy = sin(- M_PI/2.0) * R;
using namespace Eigen;
Matrix3d T;
double wdt = W*dt;
T << cos(wdt), -sin(wdt), 0, sin(wdt), cos(wdt), 0, 0, 0, 1;
Vector3d a(-ICCx, -ICCy, 0);
Vector3d b(ICCx, ICCy, wdt);
endLocation = T * a + b;
}
else
{
endLocation[0] = 0;
endLocation[1] = V * dt;
}
return pair<double, double> (endLocation[0], endLocation[1]);
}
CompetitionController::~CompetitionController()
{
if(_gps)
_gps->onNewData -= &LOnNewGPSData;
}
}
}
<|endoftext|>
|
<commit_before>#include "mjolnir/graphoptimizer.h"
#include "config.h"
#include <ostream>
#include <set>
using namespace valhalla::midgard;
using namespace valhalla::baldr;
namespace valhalla {
namespace mjolnir {
GraphOptimizer::GraphOptimizer(const boost::property_tree::ptree& pt)
: tile_hierarchy_(pt),
graphreader_(tile_hierarchy_) {
// Make sure there are at least 2 levels!
if (tile_hierarchy_.levels().size() < 2)
throw std::runtime_error("Bad tile hierarchy - need 2 levels");
}
bool GraphOptimizer::Optimize() {
// Iterate through all levels and all tiles.
// TODO - concurrency
for (auto tile_level : tile_hierarchy_.levels()) {
uint32_t level = (uint32_t)tile_level.second.level;
uint32_t ntiles = tile_level.second.tiles.TileCount();
for (uint32_t tileid = 0; tileid < ntiles; tileid++) {
// Get the graph tile. Skip if no tile exists (common case)
GraphTileBuilder tilebuilder(tile_hierarchy_, GraphId(tileid, level, 0));
if (tilebuilder.size() == 0) {
continue;
}
// Update nodes and directed edges as needed
const GraphTileHeader* existinghdr = tilebuilder.header();
GraphTileHeaderBuilder hdrbuilder;
hdrbuilder.set_nodecount(existinghdr->nodecount());
hdrbuilder.set_directededgecount(existinghdr->directededgecount());
hdrbuilder.set_edgeinfo_offset(existinghdr->edgeinfo_offset());
hdrbuilder.set_textlist_offset(existinghdr->textlist_offset());
std::vector<NodeInfoBuilder> nodes;
std::vector<DirectedEdgeBuilder> directededges;
// Iterate through the nodes and the directed edges
uint32_t nodecount = tilebuilder.header()->nodecount();
GraphId node(tileid, level, 0);
for (uint32_t i = 0; i < nodecount; i++, node++) {
NodeInfoBuilder nodeinfo = tilebuilder.node(i);
// Go through directed edges and update data
for (uint32_t j = 0, n = nodeinfo.edge_count(); j < n; j++) {
DirectedEdgeBuilder& directededge = tilebuilder.directededge(
nodeinfo.edge_index() + j);
// Set the opposing edge index
/* if (directededge.shortcut()) {
// || directededge.trans_up() || directededge.trans_down()) {
directededge.set_opp_index(31);
} else {*/
directededge.set_opp_index(GetOpposingEdgeIndex(node, directededge));
directededges.emplace_back(std::move(directededge));
}
// Add the node to the list
nodes.emplace_back(std::move(nodeinfo));
}
// Write the new file
tilebuilder.Update(tile_hierarchy_, hdrbuilder, nodes, directededges);
}
}
}
// Get the GraphId of the opposing edge.
uint32_t GraphOptimizer::GetOpposingEdgeIndex(const GraphId& node,
DirectedEdge& edge) {
// Get the tile at the end node
GraphId endnode = edge.endnode();
GraphTile* tile = graphreader_.GetGraphTile(endnode);
// Get the node info
const NodeInfo* nodeinfo = tile->node(endnode.id());
uint32_t n = nodeinfo->edge_count();
// Get the directed edges and return when the end node matches
// the specified node and length matches
const DirectedEdge* directededge = tile->directededge(
nodeinfo->edge_index());
for (uint32_t i = 0; i < n; i++, directededge++) {
if (directededge->endnode() == node &&
fabs(directededge->length() - edge.length()) < 0.0001f) {
return i;
}
}
std::cout << "Opposing edge not found at LL= " <<
nodeinfo->latlng().lat() << "," << nodeinfo->latlng().lng() << " edges at end node= " << n << std::endl;
std::cout << " Length = " << edge.length() <<
" Basenode " << node << " EndNode " << edge.endnode() <<
" sc,td,tu " << edge.shortcut() << "," << edge.trans_down() <<
"," << edge.trans_up() << std::endl;
directededge = tile->directededge(nodeinfo->edge_index());
for (uint32_t i = 0; i < n; i++, directededge++) {
std::cout << " Length = " << directededge->length() << " Endnode: " <<
directededge->endnode() << std::endl;
}
return 0;
}
}
}
<commit_msg>Exclude shortcut edges from opp index for now.<commit_after>#include "mjolnir/graphoptimizer.h"
#include "config.h"
#include <ostream>
#include <set>
using namespace valhalla::midgard;
using namespace valhalla::baldr;
namespace valhalla {
namespace mjolnir {
GraphOptimizer::GraphOptimizer(const boost::property_tree::ptree& pt)
: tile_hierarchy_(pt),
graphreader_(tile_hierarchy_) {
// Make sure there are at least 2 levels!
if (tile_hierarchy_.levels().size() < 2)
throw std::runtime_error("Bad tile hierarchy - need 2 levels");
}
bool GraphOptimizer::Optimize() {
// Iterate through all levels and all tiles.
// TODO - concurrency
for (auto tile_level : tile_hierarchy_.levels()) {
uint32_t level = (uint32_t)tile_level.second.level;
uint32_t ntiles = tile_level.second.tiles.TileCount();
for (uint32_t tileid = 0; tileid < ntiles; tileid++) {
// Get the graph tile. Skip if no tile exists (common case)
GraphTileBuilder tilebuilder(tile_hierarchy_, GraphId(tileid, level, 0));
if (tilebuilder.size() == 0) {
continue;
}
// Update nodes and directed edges as needed
const GraphTileHeader* existinghdr = tilebuilder.header();
GraphTileHeaderBuilder hdrbuilder;
hdrbuilder.set_nodecount(existinghdr->nodecount());
hdrbuilder.set_directededgecount(existinghdr->directededgecount());
hdrbuilder.set_edgeinfo_offset(existinghdr->edgeinfo_offset());
hdrbuilder.set_textlist_offset(existinghdr->textlist_offset());
std::vector<NodeInfoBuilder> nodes;
std::vector<DirectedEdgeBuilder> directededges;
// Iterate through the nodes and the directed edges
uint32_t nodecount = tilebuilder.header()->nodecount();
GraphId node(tileid, level, 0);
for (uint32_t i = 0; i < nodecount; i++, node++) {
NodeInfoBuilder nodeinfo = tilebuilder.node(i);
// Go through directed edges and update data
for (uint32_t j = 0, n = nodeinfo.edge_count(); j < n; j++) {
DirectedEdgeBuilder& directededge = tilebuilder.directededge(
nodeinfo.edge_index() + j);
// Set the opposing edge index
// NOTE: shortcut edges do not always have opposing shortcuts
// may need to fix this!
if (directededge.shortcut()) {
directededge.set_opp_index(31);
} else {
directededge.set_opp_index(GetOpposingEdgeIndex(node, directededge));
}
directededges.emplace_back(std::move(directededge));
}
// Add the node to the list
nodes.emplace_back(std::move(nodeinfo));
}
// Write the new file
tilebuilder.Update(tile_hierarchy_, hdrbuilder, nodes, directededges);
}
}
}
// Get the GraphId of the opposing edge.
uint32_t GraphOptimizer::GetOpposingEdgeIndex(const GraphId& node,
DirectedEdge& edge) {
// Get the tile at the end node
GraphId endnode = edge.endnode();
GraphTile* tile = graphreader_.GetGraphTile(endnode);
// Get the node info
const NodeInfo* nodeinfo = tile->node(endnode.id());
uint32_t n = nodeinfo->edge_count();
// Get the directed edges and return when the end node matches
// the specified node and length matches
const DirectedEdge* directededge = tile->directededge(
nodeinfo->edge_index());
for (uint32_t i = 0; i < n; i++, directededge++) {
if (directededge->endnode() == node &&
fabs(directededge->length() - edge.length()) < 0.0001f) {
return i;
}
}
std::cout << "Opposing edge not found at LL= " <<
nodeinfo->latlng().lat() << "," << nodeinfo->latlng().lng() << " edges at end node= " << n << std::endl;
std::cout << " Length = " << edge.length() <<
" Basenode " << node << " EndNode " << edge.endnode() <<
" sc,td,tu " << edge.shortcut() << "," << edge.trans_down() <<
"," << edge.trans_up() << std::endl;
directededge = tile->directededge(nodeinfo->edge_index());
for (uint32_t i = 0; i < n; i++, directededge++) {
std::cout << " Length = " << directededge->length() << " Endnode: " <<
directededge->endnode() << std::endl;
}
return 0;
}
}
}
<|endoftext|>
|
<commit_before>#include "mjolnir/transitbuilder.h"
#include "mjolnir/idtable.h"
#include "mjolnir/graphtilebuilder.h"
#include <list>
#include <future>
#include <thread>
#include <mutex>
#include <sqlite3.h>
#include <spatialite.h>
#include <boost/filesystem/operations.hpp>
#include <valhalla/baldr/graphtile.h>
#include <valhalla/baldr/graphreader.h>
#include <valhalla/midgard/logging.h>
using namespace valhalla::midgard;
using namespace valhalla::baldr;
using namespace valhalla::mjolnir;
namespace {
// Struct to hold stats information during each threads work
struct builder_stats {
uint32_t stops; // TODO - placeholder until other stats are added
// Accumulate stats from all threads
void operator()(const builder_stats& other) {
stops += other.stops;
}
};
// We make sure to lock on reading and writing because we dont want to race
// since difference threads, use for the done map as well
void build(const boost::property_tree::ptree& pt, GraphReader& reader,
IdTable& done_set, std::mutex& lock,
std::promise<builder_stats>& result) {
// Construct the transit database
std::string dir = pt.get<std::string>("transit_dir");
std::string db_name = pt.get<std::string>("db_name");
std::string database = dir + "/" + db_name;
// Make sure it exists
sqlite3 *db_handle = nullptr;
if (boost::filesystem::exists(database)) {
spatialite_init(0);
sqlite3_stmt *stmt = 0;
uint32_t ret;
char *err_msg = NULL;
std::string sql;
ret = sqlite3_open_v2(database.c_str(), &db_handle,
SQLITE_OPEN_READONLY, NULL);
if (ret != SQLITE_OK) {
LOG_ERROR("cannot open " + database);
sqlite3_close(db_handle);
db_handle = NULL;
return;
}
// loading SpatiaLite as an extension
sqlite3_enable_load_extension(db_handle, 1);
sql = "SELECT load_extension('libspatialite.so')";
ret = sqlite3_exec(db_handle, sql.c_str(), NULL, NULL, &err_msg);
if (ret != SQLITE_OK) {
LOG_ERROR("load_extension() error: " + std::string(err_msg));
sqlite3_free(err_msg);
sqlite3_close(db_handle);
return;
}
LOG_INFO("SpatiaLite loaded as an extension");
}
else {
LOG_INFO("Transit db " + database + " not found. Transit will not be added.");
return;
}
// Get some things we need throughout
builder_stats stats{};
lock.lock();
auto tile_hierarchy = reader.GetTileHierarchy();
auto local_level = tile_hierarchy.levels().rbegin()->second.level;
auto tiles = tile_hierarchy.levels().rbegin()->second.tiles;
lock.unlock();
// Iterate through the tiles and perform enhancements
for (uint32_t id = 0; id < tiles.TileCount(); id++) {
GraphId tile_id(id, local_level, 0);
// If no tile exists skip it
if(!GraphReader::DoesTileExist(tile_hierarchy, tile_id))
continue;
// If someone else is working/worked on this tile we can skip it
lock.lock();
if (done_set.IsUsed(id)) {
lock.unlock();
continue;
}
done_set.set(id);
lock.unlock();
// Get writeable and readable tiles
lock.lock();
GraphTileBuilder tilebuilder(tile_hierarchy, tile_id);
const GraphTile* tile = reader.GetGraphTile(tile_id);
lock.unlock();
// Iterate through tiles?
// Query to find all stops within the tile's bounding box
// Add these stops to the tile
// Get all routes within this tile
// Get all trips with this tile
// Get all transfers from any stop within the tile.
// Write the new file
lock.lock();
// TODO
lock.unlock();
}
if (db_handle)
sqlite3_close(db_handle);
// Send back the statistics
result.set_value(stats);
}
}
namespace valhalla {
namespace mjolnir {
// Add transit to the graph
void TransitBuilder::Build(const boost::property_tree::ptree& pt) {
// Graphreader
GraphReader reader(pt.get_child("mjolnir.hierarchy"));
// A place to hold worker threads and their results
std::vector<std::shared_ptr<std::thread> > threads(
std::max(static_cast<uint32_t>(1),
pt.get<uint32_t>("concurrency", std::thread::hardware_concurrency())));
// A place to hold the results of those threads (exceptions, stats)
std::list<std::promise<builder_stats> > results;
// A place for the threads to synchronize who is working/worked on what
IdTable done_set(reader.GetTileHierarchy().levels().rbegin()->second.tiles.TileCount());
// An atomic object we can use to do the synchronization
std::mutex lock;
// Start the threads
LOG_INFO("Add transit to the local graph...");
for (auto& thread : threads) {
results.emplace_back();
thread.reset(new std::thread(build, std::ref(pt.get_child("mjolnir.transit")),
std::ref(reader), std::ref(done_set),
std::ref(lock), std::ref(results.back())));
}
// Wait for them to finish up their work
for (auto& thread : threads) {
thread->join();
}
// Check all of the outcomes, to see about maximum density (km/km2)
builder_stats stats{};
for (auto& result : results) {
// If something bad went down this will rethrow it
try {
auto thread_stats = result.get_future().get();
stats(thread_stats);
}
catch(std::exception& e) {
//TODO: throw further up the chain?
}
}
}
}
}
<commit_msg>testing new sqlite db.<commit_after>#include "mjolnir/transitbuilder.h"
#include "mjolnir/idtable.h"
#include "mjolnir/graphtilebuilder.h"
#include <list>
#include <future>
#include <thread>
#include <mutex>
#include <sqlite3.h>
#include <spatialite.h>
#include <boost/filesystem/operations.hpp>
#include <valhalla/baldr/graphtile.h>
#include <valhalla/baldr/graphreader.h>
#include <valhalla/midgard/logging.h>
using namespace valhalla::midgard;
using namespace valhalla::baldr;
using namespace valhalla::mjolnir;
namespace {
// Struct to hold stats information during each threads work
struct builder_stats {
uint32_t stops; // TODO - placeholder until other stats are added
// Accumulate stats from all threads
void operator()(const builder_stats& other) {
stops += other.stops;
}
};
void GetStops(sqlite3 *db_handle, const AABB2& aabb) {
if (!db_handle)
return;
sqlite3_stmt *stmt = 0;
uint32_t ret;
char *err_msg = nullptr;
uint32_t result = 0;
std::string geom;
std::string sql = "SELECT stop_key,stop_id,stop_code,stop_name,stop_desc,zone_id,";
sql += "stop_url,location_type, parent_station_key from stops where ";
sql += "ST_Intersects(geom, BuildMBR(" + std::to_string(aabb.minx()) + ",";
sql += std::to_string(aabb.miny()) + ", " + std::to_string(aabb.maxx()) + ",";
sql += std::to_string(aabb.maxy()) + ")) ";
sql += "and rowid IN (SELECT rowid FROM SpatialIndex WHERE f_table_name = ";
sql += "'stops' AND search_frame = BuildMBR(" + std::to_string(aabb.minx()) + ",";
sql += std::to_string(aabb.miny()) + ", " + std::to_string(aabb.maxx()) + ",";
sql += std::to_string(aabb.maxy()) + "));";
ret = sqlite3_prepare_v2(db_handle, sql.c_str(), sql.length(), &stmt, 0);
if (ret == SQLITE_OK) {
result = sqlite3_step(stmt);
while (result == SQLITE_ROW) {
int stop_key = sqlite3_column_int(stmt, 0);
result = sqlite3_step(stmt);
}
}
if (stmt) {
sqlite3_finalize(stmt);
stmt = 0;
}
}
// We make sure to lock on reading and writing because we dont want to race
// since difference threads, use for the done map as well
void build(const boost::property_tree::ptree& pt, GraphReader& reader,
IdTable& done_set, std::mutex& lock,
std::promise<builder_stats>& result) {
// Construct the transit database
std::string dir = pt.get<std::string>("transit_dir");
std::string db_name = pt.get<std::string>("db_name");
std::string database = dir + "/" + db_name;
// Make sure it exists
sqlite3 *db_handle = nullptr;
if (boost::filesystem::exists(database)) {
spatialite_init(0);
sqlite3_stmt *stmt = 0;
uint32_t ret;
char *err_msg = NULL;
std::string sql;
ret = sqlite3_open_v2(database.c_str(), &db_handle,
SQLITE_OPEN_READONLY, NULL);
if (ret != SQLITE_OK) {
LOG_ERROR("cannot open " + database);
sqlite3_close(db_handle);
db_handle = NULL;
return;
}
// loading SpatiaLite as an extension
sqlite3_enable_load_extension(db_handle, 1);
sql = "SELECT load_extension('libspatialite.so')";
ret = sqlite3_exec(db_handle, sql.c_str(), NULL, NULL, &err_msg);
if (ret != SQLITE_OK) {
LOG_ERROR("load_extension() error: " + std::string(err_msg));
sqlite3_free(err_msg);
sqlite3_close(db_handle);
return;
}
LOG_INFO("SpatiaLite loaded as an extension");
}
else {
LOG_INFO("Transit db " + database + " not found. Transit will not be added.");
return;
}
// Get some things we need throughout
builder_stats stats{};
lock.lock();
auto tile_hierarchy = reader.GetTileHierarchy();
auto local_level = tile_hierarchy.levels().rbegin()->second.level;
auto tiles = tile_hierarchy.levels().rbegin()->second.tiles;
lock.unlock();
// Iterate through the tiles and perform enhancements
for (uint32_t id = 0; id < tiles.TileCount(); id++) {
GraphId tile_id(id, local_level, 0);
// If no tile exists skip it
if(!GraphReader::DoesTileExist(tile_hierarchy, tile_id))
continue;
// If someone else is working/worked on this tile we can skip it
lock.lock();
if (done_set.IsUsed(id)) {
lock.unlock();
continue;
}
done_set.set(id);
lock.unlock();
// Get writeable and readable tiles
lock.lock();
GraphTileBuilder tilebuilder(tile_hierarchy, tile_id);
const GraphTile* tile = reader.GetGraphTile(tile_id);
lock.unlock();
// Iterate through tiles?
GetStops(db_handle,tiles.TileBounds(id));
// Add these stops to the tile
// Get all routes within this tile
// Get all trips with this tile
// Get all transfers from any stop within the tile.
// Write the new file
lock.lock();
// TODO
lock.unlock();
}
if (db_handle)
sqlite3_close(db_handle);
// Send back the statistics
result.set_value(stats);
}
}
namespace valhalla {
namespace mjolnir {
// Add transit to the graph
void TransitBuilder::Build(const boost::property_tree::ptree& pt) {
// Graphreader
GraphReader reader(pt.get_child("mjolnir.hierarchy"));
// A place to hold worker threads and their results
std::vector<std::shared_ptr<std::thread> > threads(
std::max(static_cast<uint32_t>(1),
pt.get<uint32_t>("concurrency", std::thread::hardware_concurrency())));
// A place to hold the results of those threads (exceptions, stats)
std::list<std::promise<builder_stats> > results;
// A place for the threads to synchronize who is working/worked on what
IdTable done_set(reader.GetTileHierarchy().levels().rbegin()->second.tiles.TileCount());
// An atomic object we can use to do the synchronization
std::mutex lock;
// Start the threads
LOG_INFO("Add transit to the local graph...");
for (auto& thread : threads) {
results.emplace_back();
thread.reset(new std::thread(build, std::ref(pt.get_child("mjolnir.transit")),
std::ref(reader), std::ref(done_set),
std::ref(lock), std::ref(results.back())));
}
// Wait for them to finish up their work
for (auto& thread : threads) {
thread->join();
}
// Check all of the outcomes, to see about maximum density (km/km2)
builder_stats stats{};
for (auto& result : results) {
// If something bad went down this will rethrow it
try {
auto thread_stats = result.get_future().get();
stats(thread_stats);
}
catch(std::exception& e) {
//TODO: throw further up the chain?
}
}
}
}
}
<|endoftext|>
|
<commit_before>#include "C3DFileAdapter.h"
#include "btkAcquisitionFileReader.h"
#include "btkAcquisition.h"
#include "btkForcePlatformsExtractor.h"
#include "btkGroundReactionWrenchFilter.h"
namespace OpenSim {
const std::string C3DFileAdapter::_markers{"markers"};
const std::string C3DFileAdapter::_forces{"forces"};
const std::unordered_map<std::string, size_t>
C3DFileAdapter::_unit_index{{"marker", 0},
{"angle" , 1},
{"force" , 2},
{"moment", 3},
{"power" , 4},
{"scalar", 5}};
C3DFileAdapter*
C3DFileAdapter::clone() const {
return new C3DFileAdapter{*this};
}
C3DFileAdapter::Tables
C3DFileAdapter::read(const std::string& fileName) const {
auto abstables = extendRead(fileName);
auto marker_table =
std::static_pointer_cast<TimeSeriesTableVec3>(abstables.at(_markers));
auto force_table =
std::static_pointer_cast<TimeSeriesTableVec3>(abstables.at(_forces));
Tables tables{};
tables.emplace(_markers, marker_table);
tables.emplace( _forces, force_table);
return tables;
}
void
C3DFileAdapter::write(const C3DFileAdapter::Tables& tables,
const std::string& fileName) const {
throw Exception{"Writing C3D not supported yet."};
}
C3DFileAdapter::OutputTables
C3DFileAdapter::extendRead(const std::string& fileName) const {
auto reader = btk::AcquisitionFileReader::New();
reader->SetFilename(fileName);
reader->Update();
auto acquisition = reader->GetOutput();
OutputTables tables{};
auto& marker_table = *(new TimeSeriesTableVec3{});
auto& force_table = *(new TimeSeriesTableVec3{});
tables.emplace(_markers,
std::shared_ptr<TimeSeriesTableVec3>(&marker_table));
tables.emplace(_forces,
std::shared_ptr<TimeSeriesTableVec3>(&force_table));
auto marker_pts = btk::PointCollection::New();
for(auto it = acquisition->BeginPoint();
it != acquisition->EndPoint();
++it) {
auto pt = *it;
if(pt->GetType() == btk::Point::Marker)
marker_pts->InsertItem(pt);
}
if(marker_pts->GetItemNumber() != 0) {
marker_table.
updTableMetaData().
setValueForKey("DataRate",
std::to_string(acquisition->GetPointFrequency()));
marker_table.
updTableMetaData().
setValueForKey("Units",
acquisition->GetPointUnit());
ValueArray<std::string> marker_labels{};
for(auto it = marker_pts->Begin();
it != marker_pts->End();
++it) {
marker_labels.
upd().
push_back(SimTK::Value<std::string>((*it)->GetLabel()));
}
TimeSeriesTableVec3::DependentsMetaData marker_dep_metadata{};
marker_dep_metadata.setValueArrayForKey("labels", marker_labels);
marker_table.setDependentsMetaData(marker_dep_metadata);
double time_step{1.0 / acquisition->GetPointFrequency()};
for(int f = 0;
f < marker_pts->GetFrontItem()->GetFrameNumber();
++f) {
SimTK::RowVector_<SimTK::Vec3> row{marker_pts->GetItemNumber()};
int m{0};
for(auto it = marker_pts->Begin();
it != marker_pts->End();
++it) {
auto pt = *it;
row[m++] = SimTK::Vec3{pt->GetValues().coeff(f, 0),
pt->GetValues().coeff(f, 1),
pt->GetValues().coeff(f, 2)};
}
marker_table.appendRow(0 + f * time_step, row);
}
}
// This is probably the right way to get the raw forces data from force
// platforms. Extract the collection of force platforms.
auto force_platforms_extractor = btk::ForcePlatformsExtractor::New();
force_platforms_extractor->SetInput(acquisition);
auto force_platform_collection = force_platforms_extractor->GetOutput();
force_platforms_extractor->Update();
std::vector<btk::ForcePlatform::CalMatrix> fp_cal_matrices{};
std::vector<btk::ForcePlatform::Corners> fp_corners{};
std::vector<btk::ForcePlatform::Origin> fp_origins{};
std::vector<unsigned> fp_types{};
auto fp_force_pts = btk::PointCollection::New();
auto fp_moment_pts = btk::PointCollection::New();
auto fp_position_pts = btk::PointCollection::New();
for(auto platform = force_platform_collection->Begin();
platform != force_platform_collection->End();
++platform) {
fp_cal_matrices.push_back((*platform)->GetCalMatrix());
fp_corners.push_back((*platform)->GetCorners());
fp_origins.push_back((*platform)->GetOrigin());
fp_types.push_back(static_cast<unsigned>((*platform)->GetType()));
// Get ground reaction wrenches for the force platform.
auto ground_reaction_wrench_filter =
btk::GroundReactionWrenchFilter::New();
ground_reaction_wrench_filter->SetInput(*platform);
auto wrench_collection = ground_reaction_wrench_filter->GetOutput();
ground_reaction_wrench_filter->Update();
for(auto wrench = wrench_collection->Begin();
wrench != wrench_collection->End();
++wrench) {
// Forces time series.
fp_force_pts->InsertItem((*wrench)->GetForce());
// Moment time series.
fp_moment_pts->InsertItem((*wrench)->GetMoment());
// Position time series.
fp_position_pts->InsertItem((*wrench)->GetPosition());
}
}
//shrik<btk::ForcePlatform::Origin> foo;
if(fp_force_pts->GetItemNumber() != 0) {
// Convert Eigen matrices into SimTK matrices before updating metadata
// of the force table.
std::vector<SimTK::Matrix_<double>> cal_matrices{};
for(const auto& eigen_mat : fp_cal_matrices) {
SimTK::Matrix_<double>
simtk_mat{static_cast<int>(eigen_mat.rows()),
static_cast<int>(eigen_mat.cols())};
for(int r = 0; r < eigen_mat.rows(); ++r)
for(int c = 0; c < eigen_mat.cols(); ++c)
simtk_mat(r, c) = eigen_mat(r, c);
cal_matrices.push_back(simtk_mat);
}
std::vector<SimTK::Matrix_<double>> corners{};
for(const auto& eigen_mat : fp_corners) {
SimTK::Matrix_<double>
simtk_mat{static_cast<int>(eigen_mat.rows()),
static_cast<int>(eigen_mat.cols())};
for(int r = 0; r < eigen_mat.rows(); ++r)
for(int c = 0; c < eigen_mat.cols(); ++c)
simtk_mat(r, c) = eigen_mat(r, c);
corners.push_back(simtk_mat);
}
std::vector<SimTK::Vector_<double>> origins{};
for(const auto& eigen_vec : fp_origins) {
SimTK::Vector_<double>
simtk_vec{static_cast<int>(eigen_vec.rows())};
for(int r = 0; r < eigen_vec.rows(); ++r)
simtk_vec(r) = eigen_vec(r, 0);
origins.push_back(simtk_vec);
}
force_table.
updTableMetaData().
setValueForKey("CalibrationMatrices", std::move(cal_matrices));
force_table.
updTableMetaData().
setValueForKey("Corners", std::move(corners));
force_table.
updTableMetaData().
setValueForKey("Origins", std::move(origins));
force_table.
updTableMetaData().
setValueForKey("Types", std::move(fp_types));
force_table.
updTableMetaData().
setValueForKey("DataRate",
std::to_string(acquisition->GetAnalogFrequency()));
ValueArray<std::string> labels{};
ValueArray<std::string> units{};
for(int fp = 1; fp <= fp_force_pts->GetItemNumber(); ++fp) {
auto fp_str = std::to_string(fp);
labels.upd().push_back(SimTK::Value<std::string>("f" + fp_str));
auto force_unit = acquisition->GetPointUnits().
at(_unit_index.at("force"));
units.upd().push_back(SimTK::Value<std::string>(force_unit));
labels.upd().push_back(SimTK::Value<std::string>("m" + fp_str));
auto moment_unit = acquisition->GetPointUnits().
at(_unit_index.at("moment"));
units.upd().push_back(SimTK::Value<std::string>(moment_unit));
labels.upd().push_back(SimTK::Value<std::string>("p" + fp_str));
auto position_unit = acquisition->GetPointUnits().
at(_unit_index.at("marker"));
units.upd().push_back(SimTK::Value<std::string>(position_unit));
}
TimeSeriesTableVec3::DependentsMetaData force_dep_metadata{};
force_dep_metadata.setValueArrayForKey("labels", labels);
force_dep_metadata.setValueArrayForKey("units", units);
force_table.setDependentsMetaData(force_dep_metadata);
double time_step{1.0 / acquisition->GetAnalogFrequency()};
for(int f = 0;
f < fp_force_pts->GetFrontItem()->GetFrameNumber();
++f) {
SimTK::RowVector_<SimTK::Vec3>
row{fp_force_pts->GetItemNumber() * 3};
size_t col{0};
for(auto fit = fp_force_pts->Begin(),
mit = fp_moment_pts->Begin(),
pit = fp_position_pts->Begin();
fit != fp_force_pts->End();
++fit,
++mit,
++pit) {
row[col] = SimTK::Vec3{(*fit)->GetValues().coeff(f, 0),
(*fit)->GetValues().coeff(f, 1),
(*fit)->GetValues().coeff(f, 2)};
++col;
row[col] = SimTK::Vec3{(*mit)->GetValues().coeff(f, 0),
(*mit)->GetValues().coeff(f, 1),
(*mit)->GetValues().coeff(f, 2)};
++col;
row[col] = SimTK::Vec3{(*pit)->GetValues().coeff(f, 0),
(*pit)->GetValues().coeff(f, 1),
(*pit)->GetValues().coeff(f, 2)};
++col;
}
force_table.appendRow(0 + f * time_step, row);
}
}
EventTable event_table{};
auto events = acquisition->GetEvents();
for(auto it = events->Begin();
it != events->End();
++it) {
auto et = *it;
event_table.push_back({et->GetLabel(),
et->GetTime(),
et->GetFrame(),
et->GetDescription()});
}
marker_table.updTableMetaData().setValueForKey("events", event_table);
force_table.updTableMetaData().setValueForKey("events", event_table);
return tables;
}
void
C3DFileAdapter::extendWrite(const InputTables& absTables,
const std::string& fileName) const {
throw Exception{"Writing to C3D not supported yet."};
}
} // namespace OpenSim
<commit_msg>Conversion from size_t to int.<commit_after>#include "C3DFileAdapter.h"
#include "btkAcquisitionFileReader.h"
#include "btkAcquisition.h"
#include "btkForcePlatformsExtractor.h"
#include "btkGroundReactionWrenchFilter.h"
namespace OpenSim {
const std::string C3DFileAdapter::_markers{"markers"};
const std::string C3DFileAdapter::_forces{"forces"};
const std::unordered_map<std::string, size_t>
C3DFileAdapter::_unit_index{{"marker", 0},
{"angle" , 1},
{"force" , 2},
{"moment", 3},
{"power" , 4},
{"scalar", 5}};
C3DFileAdapter*
C3DFileAdapter::clone() const {
return new C3DFileAdapter{*this};
}
C3DFileAdapter::Tables
C3DFileAdapter::read(const std::string& fileName) const {
auto abstables = extendRead(fileName);
auto marker_table =
std::static_pointer_cast<TimeSeriesTableVec3>(abstables.at(_markers));
auto force_table =
std::static_pointer_cast<TimeSeriesTableVec3>(abstables.at(_forces));
Tables tables{};
tables.emplace(_markers, marker_table);
tables.emplace( _forces, force_table);
return tables;
}
void
C3DFileAdapter::write(const C3DFileAdapter::Tables& tables,
const std::string& fileName) const {
throw Exception{"Writing C3D not supported yet."};
}
C3DFileAdapter::OutputTables
C3DFileAdapter::extendRead(const std::string& fileName) const {
auto reader = btk::AcquisitionFileReader::New();
reader->SetFilename(fileName);
reader->Update();
auto acquisition = reader->GetOutput();
OutputTables tables{};
auto& marker_table = *(new TimeSeriesTableVec3{});
auto& force_table = *(new TimeSeriesTableVec3{});
tables.emplace(_markers,
std::shared_ptr<TimeSeriesTableVec3>(&marker_table));
tables.emplace(_forces,
std::shared_ptr<TimeSeriesTableVec3>(&force_table));
auto marker_pts = btk::PointCollection::New();
for(auto it = acquisition->BeginPoint();
it != acquisition->EndPoint();
++it) {
auto pt = *it;
if(pt->GetType() == btk::Point::Marker)
marker_pts->InsertItem(pt);
}
if(marker_pts->GetItemNumber() != 0) {
marker_table.
updTableMetaData().
setValueForKey("DataRate",
std::to_string(acquisition->GetPointFrequency()));
marker_table.
updTableMetaData().
setValueForKey("Units",
acquisition->GetPointUnit());
ValueArray<std::string> marker_labels{};
for(auto it = marker_pts->Begin();
it != marker_pts->End();
++it) {
marker_labels.
upd().
push_back(SimTK::Value<std::string>((*it)->GetLabel()));
}
TimeSeriesTableVec3::DependentsMetaData marker_dep_metadata{};
marker_dep_metadata.setValueArrayForKey("labels", marker_labels);
marker_table.setDependentsMetaData(marker_dep_metadata);
double time_step{1.0 / acquisition->GetPointFrequency()};
for(int f = 0;
f < marker_pts->GetFrontItem()->GetFrameNumber();
++f) {
SimTK::RowVector_<SimTK::Vec3> row{marker_pts->GetItemNumber()};
int m{0};
for(auto it = marker_pts->Begin();
it != marker_pts->End();
++it) {
auto pt = *it;
row[m++] = SimTK::Vec3{pt->GetValues().coeff(f, 0),
pt->GetValues().coeff(f, 1),
pt->GetValues().coeff(f, 2)};
}
marker_table.appendRow(0 + f * time_step, row);
}
}
// This is probably the right way to get the raw forces data from force
// platforms. Extract the collection of force platforms.
auto force_platforms_extractor = btk::ForcePlatformsExtractor::New();
force_platforms_extractor->SetInput(acquisition);
auto force_platform_collection = force_platforms_extractor->GetOutput();
force_platforms_extractor->Update();
std::vector<btk::ForcePlatform::CalMatrix> fp_cal_matrices{};
std::vector<btk::ForcePlatform::Corners> fp_corners{};
std::vector<btk::ForcePlatform::Origin> fp_origins{};
std::vector<unsigned> fp_types{};
auto fp_force_pts = btk::PointCollection::New();
auto fp_moment_pts = btk::PointCollection::New();
auto fp_position_pts = btk::PointCollection::New();
for(auto platform = force_platform_collection->Begin();
platform != force_platform_collection->End();
++platform) {
fp_cal_matrices.push_back((*platform)->GetCalMatrix());
fp_corners.push_back((*platform)->GetCorners());
fp_origins.push_back((*platform)->GetOrigin());
fp_types.push_back(static_cast<unsigned>((*platform)->GetType()));
// Get ground reaction wrenches for the force platform.
auto ground_reaction_wrench_filter =
btk::GroundReactionWrenchFilter::New();
ground_reaction_wrench_filter->SetInput(*platform);
auto wrench_collection = ground_reaction_wrench_filter->GetOutput();
ground_reaction_wrench_filter->Update();
for(auto wrench = wrench_collection->Begin();
wrench != wrench_collection->End();
++wrench) {
// Forces time series.
fp_force_pts->InsertItem((*wrench)->GetForce());
// Moment time series.
fp_moment_pts->InsertItem((*wrench)->GetMoment());
// Position time series.
fp_position_pts->InsertItem((*wrench)->GetPosition());
}
}
//shrik<btk::ForcePlatform::Origin> foo;
if(fp_force_pts->GetItemNumber() != 0) {
// Convert Eigen matrices into SimTK matrices before updating metadata
// of the force table.
std::vector<SimTK::Matrix_<double>> cal_matrices{};
for(const auto& eigen_mat : fp_cal_matrices) {
SimTK::Matrix_<double>
simtk_mat{static_cast<int>(eigen_mat.rows()),
static_cast<int>(eigen_mat.cols())};
for(int r = 0; r < eigen_mat.rows(); ++r)
for(int c = 0; c < eigen_mat.cols(); ++c)
simtk_mat(r, c) = eigen_mat(r, c);
cal_matrices.push_back(simtk_mat);
}
std::vector<SimTK::Matrix_<double>> corners{};
for(const auto& eigen_mat : fp_corners) {
SimTK::Matrix_<double>
simtk_mat{static_cast<int>(eigen_mat.rows()),
static_cast<int>(eigen_mat.cols())};
for(int r = 0; r < eigen_mat.rows(); ++r)
for(int c = 0; c < eigen_mat.cols(); ++c)
simtk_mat(r, c) = eigen_mat(r, c);
corners.push_back(simtk_mat);
}
std::vector<SimTK::Vector_<double>> origins{};
for(const auto& eigen_vec : fp_origins) {
SimTK::Vector_<double>
simtk_vec{static_cast<int>(eigen_vec.rows())};
for(int r = 0; r < eigen_vec.rows(); ++r)
simtk_vec(r) = eigen_vec(r, 0);
origins.push_back(simtk_vec);
}
force_table.
updTableMetaData().
setValueForKey("CalibrationMatrices", std::move(cal_matrices));
force_table.
updTableMetaData().
setValueForKey("Corners", std::move(corners));
force_table.
updTableMetaData().
setValueForKey("Origins", std::move(origins));
force_table.
updTableMetaData().
setValueForKey("Types", std::move(fp_types));
force_table.
updTableMetaData().
setValueForKey("DataRate",
std::to_string(acquisition->GetAnalogFrequency()));
ValueArray<std::string> labels{};
ValueArray<std::string> units{};
for(int fp = 1; fp <= fp_force_pts->GetItemNumber(); ++fp) {
auto fp_str = std::to_string(fp);
labels.upd().push_back(SimTK::Value<std::string>("f" + fp_str));
auto force_unit = acquisition->GetPointUnits().
at(_unit_index.at("force"));
units.upd().push_back(SimTK::Value<std::string>(force_unit));
labels.upd().push_back(SimTK::Value<std::string>("m" + fp_str));
auto moment_unit = acquisition->GetPointUnits().
at(_unit_index.at("moment"));
units.upd().push_back(SimTK::Value<std::string>(moment_unit));
labels.upd().push_back(SimTK::Value<std::string>("p" + fp_str));
auto position_unit = acquisition->GetPointUnits().
at(_unit_index.at("marker"));
units.upd().push_back(SimTK::Value<std::string>(position_unit));
}
TimeSeriesTableVec3::DependentsMetaData force_dep_metadata{};
force_dep_metadata.setValueArrayForKey("labels", labels);
force_dep_metadata.setValueArrayForKey("units", units);
force_table.setDependentsMetaData(force_dep_metadata);
double time_step{1.0 / acquisition->GetAnalogFrequency()};
for(int f = 0;
f < fp_force_pts->GetFrontItem()->GetFrameNumber();
++f) {
SimTK::RowVector_<SimTK::Vec3>
row{fp_force_pts->GetItemNumber() * 3};
int col{0};
for(auto fit = fp_force_pts->Begin(),
mit = fp_moment_pts->Begin(),
pit = fp_position_pts->Begin();
fit != fp_force_pts->End();
++fit,
++mit,
++pit) {
row[col] = SimTK::Vec3{(*fit)->GetValues().coeff(f, 0),
(*fit)->GetValues().coeff(f, 1),
(*fit)->GetValues().coeff(f, 2)};
++col;
row[col] = SimTK::Vec3{(*mit)->GetValues().coeff(f, 0),
(*mit)->GetValues().coeff(f, 1),
(*mit)->GetValues().coeff(f, 2)};
++col;
row[col] = SimTK::Vec3{(*pit)->GetValues().coeff(f, 0),
(*pit)->GetValues().coeff(f, 1),
(*pit)->GetValues().coeff(f, 2)};
++col;
}
force_table.appendRow(0 + f * time_step, row);
}
}
EventTable event_table{};
auto events = acquisition->GetEvents();
for(auto it = events->Begin();
it != events->End();
++it) {
auto et = *it;
event_table.push_back({et->GetLabel(),
et->GetTime(),
et->GetFrame(),
et->GetDescription()});
}
marker_table.updTableMetaData().setValueForKey("events", event_table);
force_table.updTableMetaData().setValueForKey("events", event_table);
return tables;
}
void
C3DFileAdapter::extendWrite(const InputTables& absTables,
const std::string& fileName) const {
throw Exception{"Writing to C3D not supported yet."};
}
} // namespace OpenSim
<|endoftext|>
|
<commit_before>#include "TRCFileAdapter.h"
#include <fstream>
#include <iomanip>
namespace OpenSim {
const std::string TRCFileAdapter::_markers{"markers"};
const std::string TRCFileAdapter::_delimiterWrite{"\t"};
// Get rid of the extra \r if parsing a file with CRLF line endings.
const std::string TRCFileAdapter::_delimitersRead{"\t\r"};
const std::string TRCFileAdapter::_frameNumColumnLabel{"Frame#"};
const std::string TRCFileAdapter::_timeColumnLabel{"Time"};
const std::string TRCFileAdapter::_xLabel{"X"};
const std::string TRCFileAdapter::_yLabel{"Y"};
const std::string TRCFileAdapter::_zLabel{"Z"};
const std::string TRCFileAdapter::_numMarkersLabel{"NumMarkers"};
const std::string TRCFileAdapter::_numFramesLabel{"NumFrames"};
const unsigned TRCFileAdapter::_dataStartsAtLine{6};
const std::vector<std::string> TRCFileAdapter::_metadataKeys{"DataRate",
"CameraRate", "NumFrames", "NumMarkers", "Units", "OrigDataRate",
"OrigDataStartFrame", "OrigNumFrames"};
TRCFileAdapter*
TRCFileAdapter::clone() const {
return new TRCFileAdapter{*this};
}
TimeSeriesTableVec3
TRCFileAdapter::read(const std::string& fileName) {
auto abs_table = TRCFileAdapter{}.extendRead(fileName).at(_markers);
return static_cast<TimeSeriesTableVec3&>(*abs_table);
}
void
TRCFileAdapter::write(const TimeSeriesTableVec3& table,
const std::string& fileName) {
InputTables tables{};
tables.emplace(_markers, &table);
TRCFileAdapter{}.extendWrite(tables, fileName);
}
TRCFileAdapter::OutputTables
TRCFileAdapter::extendRead(const std::string& fileName) const {
// Helper lambda to remove empty elements from token lists
auto eraseEmptyElements = [](std::vector<std::string>& list) {
std::vector<std::string>::iterator it = list.begin();
while (it != list.end()) {
if (it->empty())
it = list.erase(it);
else
++it;
}
};
OPENSIM_THROW_IF(fileName.empty(),
EmptyFileName);
std::ifstream in_stream{fileName};
OPENSIM_THROW_IF(!in_stream.good(),
FileDoesNotExist,
fileName);
auto table = std::make_shared<TimeSeriesTableVec3>();
// Callable to get the next line in form of vector of tokens.
auto nextLine = [&] {
return getNextLine(in_stream, _delimitersRead);
};
// First line of the stream is considered the header.
std::string header{};
std::getline(in_stream, header);
auto header_tokens = tokenize(header, _delimitersRead);
OPENSIM_THROW_IF(header_tokens.empty(),
FileIsEmpty,
fileName);
OPENSIM_THROW_IF(header_tokens.at(0) != "PathFileType",
MissingHeader);
table->updTableMetaData().setValueForKey("header", header);
// Read the line containing metadata keys.
auto keys = nextLine();
// Keys cannot be empty strings, so delete empty keys due to
// excessive use of delimiters
eraseEmptyElements(keys);
OPENSIM_THROW_IF(keys.size() != _metadataKeys.size(),
IncorrectNumMetaDataKeys,
fileName,
_metadataKeys.size(),
keys.size());
for(size_t i = 0; i < keys.size(); ++i)
OPENSIM_THROW_IF(keys[i] != _metadataKeys[i],
UnexpectedMetaDataKey,
fileName,
_metadataKeys[i],
keys[i]);
// Read the line containing metadata values.
auto values = nextLine();
eraseEmptyElements(values);
OPENSIM_THROW_IF(keys.size() != values.size(),
MetaDataLengthMismatch,
fileName,
keys.size(),
values.size());
// Fill up the metadata container.
for(std::size_t i = 0; i < keys.size(); ++i)
table->updTableMetaData().setValueForKey(keys[i], values[i]);
auto num_markers_expected =
std::stoul(table->
getTableMetaData().
getValueForKey(_numMarkersLabel).
template getValue<std::string>());
// Read the line containing column labels and fill up the column labels
// container.
auto column_labels = nextLine();
// for marker labels we do not need three columns per marker.
// remove the blank ones used in TRC due to tabbing
eraseEmptyElements(column_labels);
OPENSIM_THROW_IF(column_labels.size() != num_markers_expected + 2,
IncorrectNumColumnLabels,
fileName,
num_markers_expected + 2,
column_labels.size());
// Column 0 should be the frame number. Check and get rid of it as it is
// not used. The whole column is discarded as the data is read in.
OPENSIM_THROW_IF(column_labels[0] != _frameNumColumnLabel,
UnexpectedColumnLabel,
fileName,
_frameNumColumnLabel,
column_labels[0]);
column_labels.erase(column_labels.begin());
// Column 0 (originally column 1 before removing frame number) should
// now be the time column. Check and get rid of it. The data in this
// column is maintained separately from rest of the data.
OPENSIM_THROW_IF(column_labels[0] != _timeColumnLabel,
UnexpectedColumnLabel,
fileName,
_timeColumnLabel,
column_labels[0]);
column_labels.erase(column_labels.begin());
// Read in the next line of column labels containing (Xdd, Ydd, Zdd)
// tuples where dd is a 1 or 2 digit subscript. For example --
// X1, Y1, Z1, X2, Y2, Z2, ... so on.
// Check and ignore these labels.
auto xyz_labels_found = nextLine();
// erase blank labels, e.g. due to Frame# and Time columns
eraseEmptyElements(xyz_labels_found);
for(unsigned i = 1; i <= num_markers_expected; ++i) {
unsigned j = 0;
for(auto& letter : {_xLabel, _yLabel, _zLabel}) {
const unsigned ind = ((i - 1) * 3) + j++;
const std::string expected{letter + std::to_string(i)};
OPENSIM_THROW_IF(xyz_labels_found.at(ind) != expected,
UnexpectedColumnLabel,
fileName,
expected,
xyz_labels_found.at(ind));
}
}
// Read the rows one at a time and fill up the time column container and
// the data container.
std::size_t line_num{_dataStartsAtLine - 1};
auto row = nextLine();
while(!row.empty()) {
if (row.at(0).empty()) { //if no Frame# then ignore as empty elements
row = nextLine();
continue;
}
++line_num;
size_t expected{column_labels.size() * 3 + 2};
OPENSIM_THROW_IF(row.size() != expected,
RowLengthMismatch,
fileName,
line_num,
expected,
row.size());
// Columns 2 till the end are data.
TimeSeriesTableVec3::RowVector
row_vector{static_cast<int>(num_markers_expected),
SimTK::Vec3(SimTK::NaN)};
int ind{0};
for (std::size_t c = 2; c < column_labels.size() * 3 + 2; c += 3) {
if (!row.at(c).empty())
row_vector[ind] = SimTK::Vec3{ std::stod(row.at(c)),
std::stod(row.at(c + 1)),
std::stod(row.at(c + 2)) };
++ind;
}
// Column 1 is time.
table->appendRow(std::stod(row.at(1)), std::move(row_vector));
row = nextLine();
}
// Set the column labels of the table.
ValueArray<std::string> value_array{};
for(const auto& cl : column_labels)
value_array.upd().push_back(SimTK::Value<std::string>{cl});
TimeSeriesTableVec3::DependentsMetaData dep_metadata{};
dep_metadata.setValueArrayForKey("labels", value_array);
table->setDependentsMetaData(dep_metadata);
OutputTables output_tables{};
output_tables.emplace(_markers, table);
return output_tables;
}
void
TRCFileAdapter::extendWrite(const InputTables& absTables,
const std::string& fileName) const {
OPENSIM_THROW_IF(absTables.empty(),
NoTableFound);
const TimeSeriesTableVec3* table{};
try {
auto abs_table = absTables.at(_markers);
table = dynamic_cast<const TimeSeriesTableVec3*>(abs_table);
} catch(std::out_of_range) {
OPENSIM_THROW(KeyMissing,
_markers);
} catch(std::bad_cast&) {
OPENSIM_THROW(IncorrectTableType);
}
OPENSIM_THROW_IF(fileName.empty(),
EmptyFileName);
std::ofstream out_stream{fileName};
// First line of the stream is the header.
try {
out_stream << table->
getTableMetaData().
getValueForKey("header").
getValue<std::string>() << "\n";
} catch(KeyNotFound&) {
out_stream << "PathFileType\t4\t(X/Y/Z)\t" << fileName << "\n";
}
// Line containing metadata keys.
out_stream << _metadataKeys[0];
for(unsigned i = 1; i < _metadataKeys.size(); ++i)
out_stream << _delimiterWrite << _metadataKeys[i];
out_stream << "\n";
// Line containing metadata values.
std::string datarate;
try {
datarate = table->
getTableMetaData().
getValueForKey(_metadataKeys[0]).
getValue<std::string>();
} catch(KeyNotFound&) {
OPENSIM_THROW(MissingMetaData,
"DataRate");
}
out_stream << datarate << _delimiterWrite;
try {
out_stream << table->
getTableMetaData().
getValueForKey(_metadataKeys[1]).
getValue<std::string>()
<< _delimiterWrite;
} catch(KeyNotFound&) {
out_stream << datarate << _delimiterWrite;
}
try {
out_stream << table->
getTableMetaData().
getValueForKey(_metadataKeys[2]).
getValue<std::string>()
<< _delimiterWrite;
} catch(KeyNotFound&) {
out_stream << table->getNumRows() << _delimiterWrite;
}
try {
out_stream << table->
getTableMetaData().
getValueForKey(_metadataKeys[3]).
getValue<std::string>()
<< _delimiterWrite;
} catch(KeyNotFound&) {
out_stream << table->getNumColumns() << _delimiterWrite;
}
try {
out_stream << table->
getTableMetaData().
getValueForKey(_metadataKeys[4]).
getValue<std::string>()
<< _delimiterWrite;
} catch(KeyNotFound&) {
OPENSIM_THROW(MissingMetaData,
"Units");
}
try {
out_stream << table->
getTableMetaData().
getValueForKey(_metadataKeys[5]).
getValue<std::string>()
<< _delimiterWrite;
} catch(KeyNotFound&) {
out_stream << datarate << _delimiterWrite;
}
try {
out_stream << table->
getTableMetaData().
getValueForKey(_metadataKeys[6]).
getValue<std::string>()
<< _delimiterWrite;
} catch(KeyNotFound&) {
out_stream << 0 << _delimiterWrite;
}
try {
out_stream << table->
getTableMetaData().
getValueForKey(_metadataKeys[7]).
getValue<std::string>();
} catch(KeyNotFound&) {
out_stream << table->getNumRows();
}
out_stream << "\n";
// Line containing column labels.
out_stream << _frameNumColumnLabel << _delimiterWrite
<< _timeColumnLabel << _delimiterWrite;
for(unsigned col = 0; col < table->getNumColumns(); ++col)
out_stream << table->
getDependentsMetaData().
getValueArrayForKey("labels")[col].
getValue<std::string>()
<< _delimiterWrite << _delimiterWrite << _delimiterWrite;
out_stream << "\n";
// Line containing xyz component labels for each marker.
out_stream << _delimiterWrite << _delimiterWrite;
for(unsigned col = 1; col <= table->getNumColumns(); ++col)
for(auto& letter : {_xLabel, _yLabel, _zLabel})
out_stream << (letter + std::to_string(col)) << _delimiterWrite;
out_stream << "\n";
// Empty line.
out_stream << "\n";
// Data rows.
for(unsigned row = 0; row < table->getNumRows(); ++row) {
constexpr auto prec = std::numeric_limits<double>::digits10 + 1;
out_stream << row + 1 << _delimiterWrite
<< std::setprecision(prec)
<< table->getIndependentColumn()[row] << _delimiterWrite;
const auto& row_r = table->getRowAtIndex(row);
for(unsigned col = 0; col < table->getNumColumns(); ++col) {
const auto& elt = row_r[col];
out_stream << std::setprecision(prec)
<< elt[0] << _delimiterWrite
<< elt[1] << _delimiterWrite
<< elt[2] << _delimiterWrite;
}
out_stream << "\n";
}
}
}
<commit_msg>We have test files with spaces in the header, which are likely incorrect, but to maintain the status quo, enable parsing of the header with space as a delimiter.<commit_after>#include "TRCFileAdapter.h"
#include <fstream>
#include <iomanip>
namespace OpenSim {
const std::string _headerDelimiters{ " \t\r" };
const std::string TRCFileAdapter::_markers{"markers"};
const std::string TRCFileAdapter::_delimiterWrite{"\t"};
// Get rid of the extra \r if parsing a file with CRLF line endings.
const std::string TRCFileAdapter::_delimitersRead{"\t\r"};
const std::string TRCFileAdapter::_frameNumColumnLabel{"Frame#"};
const std::string TRCFileAdapter::_timeColumnLabel{"Time"};
const std::string TRCFileAdapter::_xLabel{"X"};
const std::string TRCFileAdapter::_yLabel{"Y"};
const std::string TRCFileAdapter::_zLabel{"Z"};
const std::string TRCFileAdapter::_numMarkersLabel{"NumMarkers"};
const std::string TRCFileAdapter::_numFramesLabel{"NumFrames"};
const unsigned TRCFileAdapter::_dataStartsAtLine{6};
const std::vector<std::string> TRCFileAdapter::_metadataKeys{"DataRate",
"CameraRate", "NumFrames", "NumMarkers", "Units", "OrigDataRate",
"OrigDataStartFrame", "OrigNumFrames"};
TRCFileAdapter*
TRCFileAdapter::clone() const {
return new TRCFileAdapter{*this};
}
TimeSeriesTableVec3
TRCFileAdapter::read(const std::string& fileName) {
auto abs_table = TRCFileAdapter{}.extendRead(fileName).at(_markers);
return static_cast<TimeSeriesTableVec3&>(*abs_table);
}
void
TRCFileAdapter::write(const TimeSeriesTableVec3& table,
const std::string& fileName) {
InputTables tables{};
tables.emplace(_markers, &table);
TRCFileAdapter{}.extendWrite(tables, fileName);
}
TRCFileAdapter::OutputTables
TRCFileAdapter::extendRead(const std::string& fileName) const {
// Helper lambda to remove empty elements from token lists
auto eraseEmptyElements = [](std::vector<std::string>& list) {
std::vector<std::string>::iterator it = list.begin();
while (it != list.end()) {
if (it->empty())
it = list.erase(it);
else
++it;
}
};
OPENSIM_THROW_IF(fileName.empty(),
EmptyFileName);
std::ifstream in_stream{fileName};
OPENSIM_THROW_IF(!in_stream.good(),
FileDoesNotExist,
fileName);
auto table = std::make_shared<TimeSeriesTableVec3>();
// Callable to get the next line in form of vector of tokens.
auto nextLine = [&] {
return getNextLine(in_stream, _delimitersRead);
};
// First line of the stream is considered the header.
std::string header{};
std::getline(in_stream, header);
auto header_tokens = tokenize(header, _headerDelimiters);
OPENSIM_THROW_IF(header_tokens.empty(),
FileIsEmpty,
fileName);
OPENSIM_THROW_IF(header_tokens.at(0) != "PathFileType",
MissingHeader);
table->updTableMetaData().setValueForKey("header", header);
// Read the line containing metadata keys.
auto keys = nextLine();
// Keys cannot be empty strings, so delete empty keys due to
// excessive use of delimiters
eraseEmptyElements(keys);
OPENSIM_THROW_IF(keys.size() != _metadataKeys.size(),
IncorrectNumMetaDataKeys,
fileName,
_metadataKeys.size(),
keys.size());
for(size_t i = 0; i < keys.size(); ++i)
OPENSIM_THROW_IF(keys[i] != _metadataKeys[i],
UnexpectedMetaDataKey,
fileName,
_metadataKeys[i],
keys[i]);
// Read the line containing metadata values.
auto values = nextLine();
eraseEmptyElements(values);
OPENSIM_THROW_IF(keys.size() != values.size(),
MetaDataLengthMismatch,
fileName,
keys.size(),
values.size());
// Fill up the metadata container.
for(std::size_t i = 0; i < keys.size(); ++i)
table->updTableMetaData().setValueForKey(keys[i], values[i]);
auto num_markers_expected =
std::stoul(table->
getTableMetaData().
getValueForKey(_numMarkersLabel).
template getValue<std::string>());
// Read the line containing column labels and fill up the column labels
// container.
auto column_labels = nextLine();
// for marker labels we do not need three columns per marker.
// remove the blank ones used in TRC due to tabbing
eraseEmptyElements(column_labels);
OPENSIM_THROW_IF(column_labels.size() != num_markers_expected + 2,
IncorrectNumColumnLabels,
fileName,
num_markers_expected + 2,
column_labels.size());
// Column 0 should be the frame number. Check and get rid of it as it is
// not used. The whole column is discarded as the data is read in.
OPENSIM_THROW_IF(column_labels[0] != _frameNumColumnLabel,
UnexpectedColumnLabel,
fileName,
_frameNumColumnLabel,
column_labels[0]);
column_labels.erase(column_labels.begin());
// Column 0 (originally column 1 before removing frame number) should
// now be the time column. Check and get rid of it. The data in this
// column is maintained separately from rest of the data.
OPENSIM_THROW_IF(column_labels[0] != _timeColumnLabel,
UnexpectedColumnLabel,
fileName,
_timeColumnLabel,
column_labels[0]);
column_labels.erase(column_labels.begin());
// Read in the next line of column labels containing (Xdd, Ydd, Zdd)
// tuples where dd is a 1 or 2 digit subscript. For example --
// X1, Y1, Z1, X2, Y2, Z2, ... so on.
// Check and ignore these labels.
auto xyz_labels_found = nextLine();
// erase blank labels, e.g. due to Frame# and Time columns
eraseEmptyElements(xyz_labels_found);
for(unsigned i = 1; i <= num_markers_expected; ++i) {
unsigned j = 0;
for(auto& letter : {_xLabel, _yLabel, _zLabel}) {
const unsigned ind = ((i - 1) * 3) + j++;
const std::string expected{letter + std::to_string(i)};
OPENSIM_THROW_IF(xyz_labels_found.at(ind) != expected,
UnexpectedColumnLabel,
fileName,
expected,
xyz_labels_found.at(ind));
}
}
// Read the rows one at a time and fill up the time column container and
// the data container.
std::size_t line_num{_dataStartsAtLine - 1};
std::vector<std::string> row = nextLine();
// skip immediate blank lines between header and data.
while(row.empty() || row.at(0).empty()) {
row = nextLine();
++line_num;
}
const size_t expected{ column_labels.size() * 3 + 2 };
// An empty line during data parsing denotes end of data
while(!row.empty()) {
OPENSIM_THROW_IF(row.size() != expected,
RowLengthMismatch,
fileName,
line_num,
expected,
row.size());
// Columns 2 till the end are data.
TimeSeriesTableVec3::RowVector
row_vector{static_cast<int>(num_markers_expected),
SimTK::Vec3(SimTK::NaN)};
int ind{0};
for (std::size_t c = 2; c < column_labels.size() * 3 + 2; c += 3) {
if (!row.at(c).empty())
row_vector[ind] = SimTK::Vec3{ std::stod(row.at(c)),
std::stod(row.at(c + 1)),
std::stod(row.at(c + 2)) };
++ind;
}
// Column 1 is time.
table->appendRow(std::stod(row.at(1)), std::move(row_vector));
row = nextLine();
++line_num;
}
// Set the column labels of the table.
ValueArray<std::string> value_array{};
for(const auto& cl : column_labels)
value_array.upd().push_back(SimTK::Value<std::string>{cl});
TimeSeriesTableVec3::DependentsMetaData dep_metadata{};
dep_metadata.setValueArrayForKey("labels", value_array);
table->setDependentsMetaData(dep_metadata);
OutputTables output_tables{};
output_tables.emplace(_markers, table);
return output_tables;
}
void
TRCFileAdapter::extendWrite(const InputTables& absTables,
const std::string& fileName) const {
OPENSIM_THROW_IF(absTables.empty(),
NoTableFound);
const TimeSeriesTableVec3* table{};
try {
auto abs_table = absTables.at(_markers);
table = dynamic_cast<const TimeSeriesTableVec3*>(abs_table);
} catch(std::out_of_range) {
OPENSIM_THROW(KeyMissing,
_markers);
} catch(std::bad_cast&) {
OPENSIM_THROW(IncorrectTableType);
}
OPENSIM_THROW_IF(fileName.empty(),
EmptyFileName);
std::ofstream out_stream{fileName};
// First line of the stream is the header.
try {
out_stream << table->
getTableMetaData().
getValueForKey("header").
getValue<std::string>() << "\n";
} catch(KeyNotFound&) {
out_stream << "PathFileType\t4\t(X/Y/Z)\t" << fileName << "\n";
}
// Line containing metadata keys.
out_stream << _metadataKeys[0];
for(unsigned i = 1; i < _metadataKeys.size(); ++i)
out_stream << _delimiterWrite << _metadataKeys[i];
out_stream << "\n";
// Line containing metadata values.
std::string datarate;
try {
datarate = table->
getTableMetaData().
getValueForKey(_metadataKeys[0]).
getValue<std::string>();
} catch(KeyNotFound&) {
OPENSIM_THROW(MissingMetaData,
"DataRate");
}
out_stream << datarate << _delimiterWrite;
try {
out_stream << table->
getTableMetaData().
getValueForKey(_metadataKeys[1]).
getValue<std::string>()
<< _delimiterWrite;
} catch(KeyNotFound&) {
out_stream << datarate << _delimiterWrite;
}
try {
out_stream << table->
getTableMetaData().
getValueForKey(_metadataKeys[2]).
getValue<std::string>()
<< _delimiterWrite;
} catch(KeyNotFound&) {
out_stream << table->getNumRows() << _delimiterWrite;
}
try {
out_stream << table->
getTableMetaData().
getValueForKey(_metadataKeys[3]).
getValue<std::string>()
<< _delimiterWrite;
} catch(KeyNotFound&) {
out_stream << table->getNumColumns() << _delimiterWrite;
}
try {
out_stream << table->
getTableMetaData().
getValueForKey(_metadataKeys[4]).
getValue<std::string>()
<< _delimiterWrite;
} catch(KeyNotFound&) {
OPENSIM_THROW(MissingMetaData,
"Units");
}
try {
out_stream << table->
getTableMetaData().
getValueForKey(_metadataKeys[5]).
getValue<std::string>()
<< _delimiterWrite;
} catch(KeyNotFound&) {
out_stream << datarate << _delimiterWrite;
}
try {
out_stream << table->
getTableMetaData().
getValueForKey(_metadataKeys[6]).
getValue<std::string>()
<< _delimiterWrite;
} catch(KeyNotFound&) {
out_stream << 0 << _delimiterWrite;
}
try {
out_stream << table->
getTableMetaData().
getValueForKey(_metadataKeys[7]).
getValue<std::string>();
} catch(KeyNotFound&) {
out_stream << table->getNumRows();
}
out_stream << "\n";
// Line containing column labels.
out_stream << _frameNumColumnLabel << _delimiterWrite
<< _timeColumnLabel << _delimiterWrite;
for(unsigned col = 0; col < table->getNumColumns(); ++col)
out_stream << table->
getDependentsMetaData().
getValueArrayForKey("labels")[col].
getValue<std::string>()
<< _delimiterWrite << _delimiterWrite << _delimiterWrite;
out_stream << "\n";
// Line containing xyz component labels for each marker.
out_stream << _delimiterWrite << _delimiterWrite;
for(unsigned col = 1; col <= table->getNumColumns(); ++col)
for(auto& letter : {_xLabel, _yLabel, _zLabel})
out_stream << (letter + std::to_string(col)) << _delimiterWrite;
out_stream << "\n";
// Empty line.
out_stream << "\n";
// Data rows.
for(unsigned row = 0; row < table->getNumRows(); ++row) {
constexpr auto prec = std::numeric_limits<double>::digits10 + 1;
out_stream << row + 1 << _delimiterWrite
<< std::setprecision(prec)
<< table->getIndependentColumn()[row] << _delimiterWrite;
const auto& row_r = table->getRowAtIndex(row);
for(unsigned col = 0; col < table->getNumColumns(); ++col) {
const auto& elt = row_r[col];
out_stream << std::setprecision(prec)
<< elt[0] << _delimiterWrite
<< elt[1] << _delimiterWrite
<< elt[2] << _delimiterWrite;
}
out_stream << "\n";
}
}
}
<|endoftext|>
|
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#include "doc.hxx"
#include "frmtool.hxx"
#include "hints.hxx"
#include <fmtornt.hxx>
#include "txtfrm.hxx"
#include "flyfrms.hxx"
// OD 2004-01-19 #110582#
#include <dflyobj.hxx>
//from FlyCnt.cxx
void DeepCalc( const SwFrm *pFrm );
SwFlyInCntFrm::SwFlyInCntFrm( SwFlyFrmFmt *pFmt, SwFrm* pSib, SwFrm *pAnch ) :
SwFlyFrm( pFmt, pSib, pAnch )
{
bInCnt = bInvalidLayout = bInvalidCntnt = sal_True;
SwTwips nRel = pFmt->GetVertOrient().GetPos();
// OD 2004-05-27 #i26791# - member <aRelPos> moved to <SwAnchoredObject>
Point aRelPos;
if( pAnch && pAnch->IsVertical() )
aRelPos.setX(pAnch->IsReverse() ? nRel : -nRel);
else
aRelPos.setY(nRel);
SetCurrRelPos( aRelPos );
}
SwFlyInCntFrm::~SwFlyInCntFrm()
{
if ( !GetFmt()->GetDoc()->IsInDtor() && GetAnchorFrm() )
{
SwRect aTmp( GetObjRectWithSpaces() );
SwFlyInCntFrm::NotifyBackground( FindPageFrm(), aTmp, PREP_FLY_LEAVE );
}
}
// #i28701#
TYPEINIT1(SwFlyInCntFrm,SwFlyFrm);
void SwFlyInCntFrm::SetRefPoint( const Point& rPoint,
const Point& rRelAttr,
const Point& rRelPos )
{
// OD 2004-05-27 #i26791# - member <aRelPos> moved to <SwAnchoredObject>
OSL_ENSURE( rPoint != aRef || rRelAttr != GetCurrRelPos(), "SetRefPoint: no change" );
SwFlyNotify *pNotify = NULL;
// No notify at a locked fly frame, if a fly frame is locked, there's
// already a SwFlyNotify object on the stack (MakeAll).
if( !IsLocked() )
pNotify = new SwFlyNotify( this );
aRef = rPoint;
SetCurrRelPos( rRelAttr );
SWRECTFN( GetAnchorFrm() )
(Frm().*fnRect->fnSetPos)( rPoint + rRelPos );
// #i68520#
InvalidateObjRectWithSpaces();
if( pNotify )
{
InvalidatePage();
mbValidPos = sal_False;
bInvalid = sal_True;
Calc();
delete pNotify;
}
}
void SwFlyInCntFrm::Modify( const SfxPoolItem* pOld, const SfxPoolItem *pNew )
{
bool bCallPrepare = false;
sal_uInt16 nWhich = pOld ? pOld->Which() : pNew ? pNew->Which() : 0;
if( RES_ATTRSET_CHG == nWhich )
{
if( SFX_ITEM_SET == ((SwAttrSetChg*)pNew)->GetChgSet()->
GetItemState( RES_SURROUND, false ) ||
SFX_ITEM_SET == ((SwAttrSetChg*)pNew)->GetChgSet()->
GetItemState( RES_FRMMACRO, false ) )
{
SwAttrSetChg aOld( *(SwAttrSetChg*)pOld );
SwAttrSetChg aNew( *(SwAttrSetChg*)pNew );
aOld.ClearItem( RES_SURROUND );
aNew.ClearItem( RES_SURROUND );
aOld.ClearItem( RES_FRMMACRO );
aNew.ClearItem( RES_FRMMACRO );
if( aNew.Count() )
{
SwFlyFrm::Modify( &aOld, &aNew );
bCallPrepare = true;
}
}
else if( ((SwAttrSetChg*)pNew)->GetChgSet()->Count())
{
SwFlyFrm::Modify( pOld, pNew );
bCallPrepare = true;
}
}
else if( nWhich != RES_SURROUND && RES_FRMMACRO != nWhich )
{
SwFlyFrm::Modify( pOld, pNew );
bCallPrepare = true;
}
if ( bCallPrepare && GetAnchorFrm() )
AnchorFrm()->Prepare( PREP_FLY_ATTR_CHG, GetFmt() );
}
/// Here the content gets formatted initially.
void SwFlyInCntFrm::Format( const SwBorderAttrs *pAttrs )
{
if ( !Frm().Height() )
{
Lock(); //don't format the anchor on the crook.
SwCntntFrm *pCntnt = ContainsCntnt();
while ( pCntnt )
{ pCntnt->Calc();
pCntnt = pCntnt->GetNextCntntFrm();
}
Unlock();
}
SwFlyFrm::Format( pAttrs );
}
/** Calculate object position
*
* @note: In contrast to other Frames, we only calculate the relative position
* here. The absolute position is only calculated using SetAbsPos.
**/
void SwFlyInCntFrm::MakeObjPos()
{
if ( !mbValidPos )
{
mbValidPos = sal_True;
SwFlyFrmFmt *pFmt = (SwFlyFrmFmt*)GetFmt();
const SwFmtVertOrient &rVert = pFmt->GetVertOrient();
//Update the current values in the format if needed, during this we of
//course must not send any Modify.
const bool bVert = GetAnchorFrm()->IsVertical();
const bool bRev = GetAnchorFrm()->IsReverse();
SwTwips nOld = rVert.GetPos();
SwTwips nAct = bVert ? -GetCurrRelPos().X() : GetCurrRelPos().Y();
if( bRev )
nAct = -nAct;
if( nAct != nOld )
{
SwFmtVertOrient aVert( rVert );
aVert.SetPos( nAct );
pFmt->LockModify();
pFmt->SetFmtAttr( aVert );
pFmt->UnlockModify();
}
}
}
// #115759#
void SwFlyInCntFrm::_ActionOnInvalidation( const InvalidationType _nInvalid )
{
if ( INVALID_POS == _nInvalid || INVALID_ALL == _nInvalid )
AnchorFrm()->Prepare( PREP_FLY_ATTR_CHG, &GetFrmFmt() );
}
void SwFlyInCntFrm::NotifyBackground( SwPageFrm *, const SwRect& rRect,
PrepareHint eHint)
{
if ( eHint == PREP_FLY_ATTR_CHG )
AnchorFrm()->Prepare( PREP_FLY_ATTR_CHG );
else
AnchorFrm()->Prepare( eHint, (void*)&rRect );
}
const Point SwFlyInCntFrm::GetRelPos() const
{
Calc();
return GetCurrRelPos();
}
/// @see SwRowFrm::RegistFlys()
void SwFlyInCntFrm::RegistFlys()
{
SwPageFrm *pPage = FindPageFrm();
OSL_ENSURE( pPage, "Register Flys without pages?" );
::RegistFlys( pPage, this );
}
void SwFlyInCntFrm::MakeAll()
{
// OD 2004-01-19 #110582#
if ( !GetFmt()->GetDoc()->IsVisibleLayerId( GetVirtDrawObj()->GetLayer() ) )
{
return;
}
if ( !GetAnchorFrm() || IsLocked() || IsColLocked() || !FindPageFrm() )
return;
Lock(); // The curtain falls
//does the notification in the DTor
const SwFlyNotify aNotify( this );
SwBorderAttrAccess aAccess( SwFrm::GetCache(), this );
const SwBorderAttrs &rAttrs = *aAccess.Get();
if ( IsClipped() )
mbValidSize = bHeightClipped = bWidthClipped = sal_False;
while ( !mbValidPos || !mbValidSize || !mbValidPrtArea )
{
//Only stop, if the flag is set!!
if ( !mbValidSize )
{
mbValidPrtArea = sal_False;
}
if ( !mbValidPrtArea )
MakePrtArea( rAttrs );
if ( !mbValidSize )
Format( &rAttrs );
if ( !mbValidPos )
{
MakeObjPos();
}
// re-activate clipping of as-character anchored Writer fly frames
// depending on compatibility option <ClipAsCharacterAnchoredWriterFlyFrames>
if ( mbValidPos && mbValidSize &&
GetFmt()->getIDocumentSettingAccess()->get( IDocumentSettingAccess::CLIP_AS_CHARACTER_ANCHORED_WRITER_FLY_FRAME ) )
{
SwFrm* pFrm = AnchorFrm();
if ( Frm().Left() == (pFrm->Frm().Left()+pFrm->Prt().Left()) &&
Frm().Width() > pFrm->Prt().Width() )
{
Frm().Width( pFrm->Prt().Width() );
mbValidPrtArea = sal_False;
bWidthClipped = sal_True;
}
}
}
Unlock();
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Vertical content alignment of frames anchored as character<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#include "doc.hxx"
#include "frmtool.hxx"
#include "hints.hxx"
#include <fmtornt.hxx>
#include "txtfrm.hxx"
#include "flyfrms.hxx"
// OD 2004-01-19 #110582#
#include <dflyobj.hxx>
//from FlyCnt.cxx
void DeepCalc( const SwFrm *pFrm );
SwFlyInCntFrm::SwFlyInCntFrm( SwFlyFrmFmt *pFmt, SwFrm* pSib, SwFrm *pAnch ) :
SwFlyFrm( pFmt, pSib, pAnch )
{
bInCnt = bInvalidLayout = bInvalidCntnt = sal_True;
SwTwips nRel = pFmt->GetVertOrient().GetPos();
// OD 2004-05-27 #i26791# - member <aRelPos> moved to <SwAnchoredObject>
Point aRelPos;
if( pAnch && pAnch->IsVertical() )
aRelPos.setX(pAnch->IsReverse() ? nRel : -nRel);
else
aRelPos.setY(nRel);
SetCurrRelPos( aRelPos );
}
SwFlyInCntFrm::~SwFlyInCntFrm()
{
if ( !GetFmt()->GetDoc()->IsInDtor() && GetAnchorFrm() )
{
SwRect aTmp( GetObjRectWithSpaces() );
SwFlyInCntFrm::NotifyBackground( FindPageFrm(), aTmp, PREP_FLY_LEAVE );
}
}
// #i28701#
TYPEINIT1(SwFlyInCntFrm,SwFlyFrm);
void SwFlyInCntFrm::SetRefPoint( const Point& rPoint,
const Point& rRelAttr,
const Point& rRelPos )
{
// OD 2004-05-27 #i26791# - member <aRelPos> moved to <SwAnchoredObject>
OSL_ENSURE( rPoint != aRef || rRelAttr != GetCurrRelPos(), "SetRefPoint: no change" );
SwFlyNotify *pNotify = NULL;
// No notify at a locked fly frame, if a fly frame is locked, there's
// already a SwFlyNotify object on the stack (MakeAll).
if( !IsLocked() )
pNotify = new SwFlyNotify( this );
aRef = rPoint;
SetCurrRelPos( rRelAttr );
SWRECTFN( GetAnchorFrm() )
(Frm().*fnRect->fnSetPos)( rPoint + rRelPos );
// #i68520#
InvalidateObjRectWithSpaces();
if( pNotify )
{
InvalidatePage();
mbValidPos = sal_False;
bInvalid = sal_True;
Calc();
delete pNotify;
}
}
void SwFlyInCntFrm::Modify( const SfxPoolItem* pOld, const SfxPoolItem *pNew )
{
bool bCallPrepare = false;
sal_uInt16 nWhich = pOld ? pOld->Which() : pNew ? pNew->Which() : 0;
if( RES_ATTRSET_CHG == nWhich )
{
if( SFX_ITEM_SET == ((SwAttrSetChg*)pNew)->GetChgSet()->
GetItemState( RES_SURROUND, false ) ||
SFX_ITEM_SET == ((SwAttrSetChg*)pNew)->GetChgSet()->
GetItemState( RES_FRMMACRO, false ) )
{
SwAttrSetChg aOld( *(SwAttrSetChg*)pOld );
SwAttrSetChg aNew( *(SwAttrSetChg*)pNew );
aOld.ClearItem( RES_SURROUND );
aNew.ClearItem( RES_SURROUND );
aOld.ClearItem( RES_FRMMACRO );
aNew.ClearItem( RES_FRMMACRO );
if( aNew.Count() )
{
SwFlyFrm::Modify( &aOld, &aNew );
bCallPrepare = true;
}
}
else if( ((SwAttrSetChg*)pNew)->GetChgSet()->Count())
{
SwFlyFrm::Modify( pOld, pNew );
bCallPrepare = true;
}
}
else if( nWhich != RES_SURROUND && RES_FRMMACRO != nWhich )
{
SwFlyFrm::Modify( pOld, pNew );
bCallPrepare = true;
}
if ( bCallPrepare && GetAnchorFrm() )
AnchorFrm()->Prepare( PREP_FLY_ATTR_CHG, GetFmt() );
}
/// Here the content gets formatted initially.
void SwFlyInCntFrm::Format( const SwBorderAttrs *pAttrs )
{
if ( !Frm().Height() )
{
Lock(); //don't format the anchor on the crook.
SwCntntFrm *pCntnt = ContainsCntnt();
while ( pCntnt )
{ pCntnt->Calc();
pCntnt = pCntnt->GetNextCntntFrm();
}
Unlock();
}
SwFlyFrm::Format( pAttrs );
}
/** Calculate object position
*
* @note: In contrast to other Frames, we only calculate the relative position
* here. The absolute position is only calculated using SetAbsPos.
**/
void SwFlyInCntFrm::MakeObjPos()
{
if ( !mbValidPos )
{
mbValidPos = sal_True;
SwFlyFrmFmt *pFmt = (SwFlyFrmFmt*)GetFmt();
const SwFmtVertOrient &rVert = pFmt->GetVertOrient();
//Update the current values in the format if needed, during this we of
//course must not send any Modify.
const bool bVert = GetAnchorFrm()->IsVertical();
const bool bRev = GetAnchorFrm()->IsReverse();
SwTwips nOld = rVert.GetPos();
SwTwips nAct = bVert ? -GetCurrRelPos().X() : GetCurrRelPos().Y();
if( bRev )
nAct = -nAct;
if( nAct != nOld )
{
SwFmtVertOrient aVert( rVert );
aVert.SetPos( nAct );
pFmt->LockModify();
pFmt->SetFmtAttr( aVert );
pFmt->UnlockModify();
}
}
}
// #115759#
void SwFlyInCntFrm::_ActionOnInvalidation( const InvalidationType _nInvalid )
{
if ( INVALID_POS == _nInvalid || INVALID_ALL == _nInvalid )
AnchorFrm()->Prepare( PREP_FLY_ATTR_CHG, &GetFrmFmt() );
}
void SwFlyInCntFrm::NotifyBackground( SwPageFrm *, const SwRect& rRect,
PrepareHint eHint)
{
if ( eHint == PREP_FLY_ATTR_CHG )
AnchorFrm()->Prepare( PREP_FLY_ATTR_CHG );
else
AnchorFrm()->Prepare( eHint, (void*)&rRect );
}
const Point SwFlyInCntFrm::GetRelPos() const
{
Calc();
return GetCurrRelPos();
}
/// @see SwRowFrm::RegistFlys()
void SwFlyInCntFrm::RegistFlys()
{
SwPageFrm *pPage = FindPageFrm();
OSL_ENSURE( pPage, "Register Flys without pages?" );
::RegistFlys( pPage, this );
}
void SwFlyInCntFrm::MakeAll()
{
// OD 2004-01-19 #110582#
if ( !GetFmt()->GetDoc()->IsVisibleLayerId( GetVirtDrawObj()->GetLayer() ) )
{
return;
}
if ( !GetAnchorFrm() || IsLocked() || IsColLocked() || !FindPageFrm() )
return;
Lock(); // The curtain falls
//does the notification in the DTor
const SwFlyNotify aNotify( this );
SwBorderAttrAccess aAccess( SwFrm::GetCache(), this );
const SwBorderAttrs &rAttrs = *aAccess.Get();
if ( IsClipped() )
mbValidSize = bHeightClipped = bWidthClipped = sal_False;
while ( !mbValidPos || !mbValidSize || !mbValidPrtArea || !m_bValidContentPos )
{
//Only stop, if the flag is set!!
if ( !mbValidSize )
{
mbValidPrtArea = sal_False;
}
if ( !mbValidPrtArea )
{
MakePrtArea( rAttrs );
m_bValidContentPos = false;
}
if ( !mbValidSize )
Format( &rAttrs );
if ( !mbValidPos )
{
MakeObjPos();
}
if ( !m_bValidContentPos )
MakeContentPos( rAttrs );
// re-activate clipping of as-character anchored Writer fly frames
// depending on compatibility option <ClipAsCharacterAnchoredWriterFlyFrames>
if ( mbValidPos && mbValidSize &&
GetFmt()->getIDocumentSettingAccess()->get( IDocumentSettingAccess::CLIP_AS_CHARACTER_ANCHORED_WRITER_FLY_FRAME ) )
{
SwFrm* pFrm = AnchorFrm();
if ( Frm().Left() == (pFrm->Frm().Left()+pFrm->Prt().Left()) &&
Frm().Width() > pFrm->Prt().Width() )
{
Frm().Width( pFrm->Prt().Width() );
mbValidPrtArea = sal_False;
bWidthClipped = sal_True;
}
}
}
Unlock();
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>
|
<commit_before>/**
* @file pca_test.cpp
* @author Ajinkya Kale
*
* Test file for PCA class.
*/
#include <mlpack/core.hpp>
#include <mlpack/methods/pca/pca.hpp>
#include <boost/test/unit_test.hpp>
BOOST_AUTO_TEST_SUITE(PCATest);
using namespace std;
using namespace arma;
using namespace mlpack;
using namespace mlpack::pca;
BOOST_AUTO_TEST_CASE(ArmaComparisonPCATest)
{
int n_rows;
int n_cols;
mat coeff, coeff1;
vec eigVal, eigVal1;
mat score, score1;
mat data = randu<mat>(100,100);
PCA p;
p.Apply(data, score1, eigVal1, coeff1);
princomp(coeff, score, eigVal, trans(data));
score = trans(score);
coeff = trans(coeff);
n_rows = eigVal.n_rows;
n_cols = eigVal.n_cols;
// Verify the PCA results based on the eigenvalues.
for(int i = 0; i < n_rows; i++)
{
for(int j = 0; j < n_cols; j++)
{
BOOST_REQUIRE_CLOSE(eigVal(i, j), eigVal1(i, j), 1e-5);
}
}
}
BOOST_AUTO_TEST_SUITE_END();
<commit_msg>I thought I was helping, but it turns out I just made things worse. BOOST_REQUIRE_SMALL is necessary because the eigenvalues could be zero. The fabs() isn't, though.<commit_after>/**
* @file pca_test.cpp
* @author Ajinkya Kale
*
* Test file for PCA class.
*/
#include <mlpack/core.hpp>
#include <mlpack/methods/pca/pca.hpp>
#include <boost/test/unit_test.hpp>
BOOST_AUTO_TEST_SUITE(PCATest);
using namespace std;
using namespace arma;
using namespace mlpack;
using namespace mlpack::pca;
BOOST_AUTO_TEST_CASE(ArmaComparisonPCATest)
{
int n_rows;
int n_cols;
mat coeff, coeff1;
vec eigVal, eigVal1;
mat score, score1;
mat data = randu<mat>(100,100);
PCA p;
p.Apply(data, score1, eigVal1, coeff1);
princomp(coeff, score, eigVal, trans(data));
score = trans(score);
coeff = trans(coeff);
n_rows = eigVal.n_rows;
n_cols = eigVal.n_cols;
// Verify the PCA results based on the eigenvalues.
for(int i = 0; i < n_rows; i++)
{
for(int j = 0; j < n_cols; j++)
{
BOOST_REQUIRE_SMALL(eigVal(i, j) - eigVal1(i, j), 0.0001);
}
}
}
BOOST_AUTO_TEST_SUITE_END();
<|endoftext|>
|
<commit_before>/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* 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 <folly/Singleton.h>
#include <folly/portability/Config.h>
#ifndef _WIN32
#include <dlfcn.h>
#endif
#include <atomic>
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <string>
#include <folly/Demangle.h>
#include <folly/Format.h>
#include <folly/ScopeGuard.h>
#include <folly/detail/SingletonStackTrace.h>
#if !defined(_WIN32) && !defined(__APPLE__) && !defined(__ANDROID__)
#define FOLLY_SINGLETON_HAVE_DLSYM 1
#endif
namespace folly {
#if FOLLY_SINGLETON_HAVE_DLSYM
namespace detail {
static void singleton_hs_init_weak(int* argc, char** argv[])
__attribute__((__weakref__("hs_init")));
} // namespace detail
#endif
SingletonVault::Type SingletonVault::defaultVaultType() {
#if FOLLY_SINGLETON_HAVE_DLSYM
bool isPython = dlsym(RTLD_DEFAULT, "Py_Main");
bool isHaskel =
detail::singleton_hs_init_weak || dlsym(RTLD_DEFAULT, "hs_init");
bool isJVM = dlsym(RTLD_DEFAULT, "JNI_GetCreatedJavaVMs");
bool isD = dlsym(RTLD_DEFAULT, "_d_run_main");
return isPython || isHaskel || isJVM || isD ? Type::Relaxed : Type::Strict;
#else
return Type::Relaxed;
#endif
}
namespace detail {
std::string TypeDescriptor::name() const {
auto ret = demangle(ti_.name());
if (tag_ti_ != std::type_index(typeid(DefaultTag))) {
ret += "/";
ret += demangle(tag_ti_.name());
}
return ret.toStdString();
}
// clang-format off
[[noreturn]] void singletonWarnDoubleRegistrationAndAbort(
const TypeDescriptor& type) {
// Ensure the availability of std::cerr
std::ios_base::Init ioInit;
std::cerr << "Double registration of singletons of the same "
"underlying type; check for multiple definitions "
"of type folly::Singleton<"
<< type.name() << ">\n";
std::abort();
}
[[noreturn]] void singletonWarnLeakyDoubleRegistrationAndAbort(
const TypeDescriptor& type) {
// Ensure the availability of std::cerr
std::ios_base::Init ioInit;
std::cerr << "Double registration of singletons of the same "
"underlying type; check for multiple definitions "
"of type folly::LeakySingleton<"
<< type.name() << ">\n";
std::abort();
}
[[noreturn]] void singletonWarnLeakyInstantiatingNotRegisteredAndAbort(
const TypeDescriptor& type) {
auto trace = detail::getSingletonStackTrace();
LOG(FATAL) << "Creating instance for unregistered singleton: " << type.name()
<< "\n"
<< "Stacktrace:\n" << (!trace.empty() ? trace : "(not available)");
}
[[noreturn]] void singletonWarnRegisterMockEarlyAndAbort(
const TypeDescriptor& type) {
LOG(FATAL) << "Registering mock before singleton was registered: "
<< type.name();
}
void singletonWarnDestroyInstanceLeak(
const TypeDescriptor& type,
const void* ptr) {
LOG(ERROR) << "Singleton of type " << type.name() << " has a "
<< "living reference at destroyInstances time; beware! Raw "
<< "pointer is " << ptr << ". It is very likely "
<< "that some other singleton is holding a shared_ptr to it. "
<< "This singleton will be leaked (even if a shared_ptr to it "
<< "is eventually released)."
<< "Make sure dependencies between these singletons are "
<< "properly defined.";
}
[[noreturn]] void singletonWarnCreateCircularDependencyAndAbort(
const TypeDescriptor& type) {
LOG(FATAL) << "circular singleton dependency: " << type.name();
}
[[noreturn]] void singletonWarnCreateUnregisteredAndAbort(
const TypeDescriptor& type) {
auto trace = detail::getSingletonStackTrace();
LOG(FATAL) << "Creating instance for unregistered singleton: " << type.name()
<< "\n"
<< "Stacktrace:\n" << (!trace.empty() ? trace : "(not available)");
}
[[noreturn]] void singletonWarnCreateBeforeRegistrationCompleteAndAbort(
const TypeDescriptor& type) {
auto trace = detail::getSingletonStackTrace();
LOG(FATAL) << "Singleton " << type.name() << " requested before "
<< "registrationComplete() call.\n"
<< "This usually means that either main() never called "
<< "folly::init, or singleton was requested before main() "
<< "(which is not allowed).\n"
<< "Stacktrace:\n" << (!trace.empty() ? trace : "(not available)");
}
void singletonPrintDestructionStackTrace(const TypeDescriptor& type) {
auto trace = detail::getSingletonStackTrace();
LOG(ERROR) << "Singleton " << type.name() << " was released.\n"
<< "Stacktrace:\n" << (!trace.empty() ? trace : "(not available)");
}
[[noreturn]] void singletonThrowNullCreator(const std::type_info& type) {
auto const msg = sformat(
"nullptr_t should be passed if you want {} to be default constructed",
demangle(type));
throw std::logic_error(msg);
}
[[noreturn]] void singletonThrowGetInvokedAfterDestruction(
const TypeDescriptor& type) {
throw std::runtime_error(
"Raw pointer to a singleton requested after its destruction."
" Singleton type is: " +
type.name());
}
// clang-format on
} // namespace detail
namespace {
struct FatalHelper {
~FatalHelper() {
if (!leakedSingletons_.empty()) {
std::string leakedTypes;
for (const auto& singleton : leakedSingletons_) {
leakedTypes += "\t" + singleton.name() + "\n";
}
LOG(DFATAL) << "Singletons of the following types had living references "
<< "after destroyInstances was finished:\n"
<< leakedTypes
<< "beware! It is very likely that those singleton instances "
<< "are leaked.";
}
}
std::vector<detail::TypeDescriptor> leakedSingletons_;
};
#if defined(__APPLE__) || defined(_MSC_VER)
// OS X doesn't support constructor priorities.
FatalHelper fatalHelper;
#else
FatalHelper __attribute__((__init_priority__(101))) fatalHelper;
#endif
} // namespace
SingletonVault::~SingletonVault() {
destroyInstances();
}
void SingletonVault::registerSingleton(detail::SingletonHolderBase* entry) {
auto state = state_.rlock();
state->check(detail::SingletonVaultState::Type::Running);
if (UNLIKELY(state->registrationComplete)) {
LOG(ERROR) << "Registering singleton after registrationComplete().";
}
auto singletons = singletons_.wlock();
CHECK_THROW(
singletons->emplace(entry->type(), entry).second, std::logic_error);
}
void SingletonVault::addEagerInitSingleton(detail::SingletonHolderBase* entry) {
auto state = state_.rlock();
state->check(detail::SingletonVaultState::Type::Running);
if (UNLIKELY(state->registrationComplete)) {
LOG(ERROR) << "Registering for eager-load after registrationComplete().";
}
CHECK_THROW(singletons_.rlock()->count(entry->type()), std::logic_error);
auto eagerInitSingletons = eagerInitSingletons_.wlock();
eagerInitSingletons->insert(entry);
}
void SingletonVault::registrationComplete() {
std::atexit([]() { SingletonVault::singleton()->destroyInstances(); });
auto state = state_.wlock();
state->check(detail::SingletonVaultState::Type::Running);
if (state->registrationComplete) {
return;
}
auto singletons = singletons_.rlock();
if (type_ == Type::Strict) {
for (const auto& p : *singletons) {
if (p.second->hasLiveInstance()) {
throw std::runtime_error(
"Singleton " + p.first.name() +
" created before registration was complete.");
}
}
}
state->registrationComplete = true;
}
void SingletonVault::doEagerInit() {
{
auto state = state_.rlock();
state->check(detail::SingletonVaultState::Type::Running);
if (UNLIKELY(!state->registrationComplete)) {
throw std::logic_error("registrationComplete() not yet called");
}
}
auto eagerInitSingletons = eagerInitSingletons_.rlock();
for (auto* single : *eagerInitSingletons) {
single->createInstance();
}
}
void SingletonVault::doEagerInitVia(Executor& exe, folly::Baton<>* done) {
{
auto state = state_.rlock();
state->check(detail::SingletonVaultState::Type::Running);
if (UNLIKELY(!state->registrationComplete)) {
throw std::logic_error("registrationComplete() not yet called");
}
}
auto eagerInitSingletons = eagerInitSingletons_.rlock();
auto countdown =
std::make_shared<std::atomic<size_t>>(eagerInitSingletons->size());
for (auto* single : *eagerInitSingletons) {
// countdown is retained by shared_ptr, and will be alive until last lambda
// is done. notifyBaton is provided by the caller, and expected to remain
// present (if it's non-nullptr). singletonSet can go out of scope but
// its values, which are SingletonHolderBase pointers, are alive as long as
// SingletonVault is not being destroyed.
exe.add([=] {
// decrement counter and notify if requested, whether initialization
// was successful, was skipped (already initialized), or exception thrown.
SCOPE_EXIT {
if (--(*countdown) == 0) {
if (done != nullptr) {
done->post();
}
}
};
// if initialization is in progress in another thread, don't try to init
// here. Otherwise the current thread will block on 'createInstance'.
if (!single->creationStarted()) {
single->createInstance();
}
});
}
}
void SingletonVault::destroyInstances() {
auto stateW = state_.wlock();
if (stateW->state == detail::SingletonVaultState::Type::Quiescing) {
return;
}
stateW->state = detail::SingletonVaultState::Type::Quiescing;
auto stateR = stateW.moveFromWriteToRead();
{
auto singletons = singletons_.rlock();
auto creationOrder = creationOrder_.rlock();
CHECK_GE(singletons->size(), creationOrder->size());
// Release all ReadMostlyMainPtrs at once
{
ReadMostlyMainPtrDeleter<> deleter;
for (auto& singleton_type : *creationOrder) {
singletons->at(singleton_type)->preDestroyInstance(deleter);
}
}
for (auto type_iter = creationOrder->rbegin();
type_iter != creationOrder->rend();
++type_iter) {
singletons->at(*type_iter)->destroyInstance();
}
for (auto& singleton_type : *creationOrder) {
auto instance = singletons->at(singleton_type);
if (!instance->hasLiveInstance()) {
continue;
}
fatalHelper.leakedSingletons_.push_back(instance->type());
}
}
{
auto creationOrder = creationOrder_.wlock();
creationOrder->clear();
}
}
void SingletonVault::reenableInstances() {
auto state = state_.wlock();
state->check(detail::SingletonVaultState::Type::Quiescing);
state->state = detail::SingletonVaultState::Type::Running;
}
void SingletonVault::scheduleDestroyInstances() {
// Add a dependency on folly::ThreadLocal to make sure all its static
// singletons are initalized first.
threadlocal_detail::StaticMeta<void, void>::instance();
std::atexit([] { SingletonVault::singleton()->destroyInstances(); });
}
} // namespace folly
<commit_msg>Fix -Winvalid-return warnings in Singleton<commit_after>/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* 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 <folly/Singleton.h>
#include <folly/portability/Config.h>
#ifndef _WIN32
#include <dlfcn.h>
#endif
#include <atomic>
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <string>
#include <folly/Demangle.h>
#include <folly/Format.h>
#include <folly/ScopeGuard.h>
#include <folly/detail/SingletonStackTrace.h>
#if !defined(_WIN32) && !defined(__APPLE__) && !defined(__ANDROID__)
#define FOLLY_SINGLETON_HAVE_DLSYM 1
#endif
namespace folly {
#if FOLLY_SINGLETON_HAVE_DLSYM
namespace detail {
static void singleton_hs_init_weak(int* argc, char** argv[])
__attribute__((__weakref__("hs_init")));
} // namespace detail
#endif
SingletonVault::Type SingletonVault::defaultVaultType() {
#if FOLLY_SINGLETON_HAVE_DLSYM
bool isPython = dlsym(RTLD_DEFAULT, "Py_Main");
bool isHaskel =
detail::singleton_hs_init_weak || dlsym(RTLD_DEFAULT, "hs_init");
bool isJVM = dlsym(RTLD_DEFAULT, "JNI_GetCreatedJavaVMs");
bool isD = dlsym(RTLD_DEFAULT, "_d_run_main");
return isPython || isHaskel || isJVM || isD ? Type::Relaxed : Type::Strict;
#else
return Type::Relaxed;
#endif
}
namespace detail {
std::string TypeDescriptor::name() const {
auto ret = demangle(ti_.name());
if (tag_ti_ != std::type_index(typeid(DefaultTag))) {
ret += "/";
ret += demangle(tag_ti_.name());
}
return ret.toStdString();
}
// clang-format off
[[noreturn]] void singletonWarnDoubleRegistrationAndAbort(
const TypeDescriptor& type) {
// Ensure the availability of std::cerr
std::ios_base::Init ioInit;
std::cerr << "Double registration of singletons of the same "
"underlying type; check for multiple definitions "
"of type folly::Singleton<"
<< type.name() << ">\n";
std::abort();
}
[[noreturn]] void singletonWarnLeakyDoubleRegistrationAndAbort(
const TypeDescriptor& type) {
// Ensure the availability of std::cerr
std::ios_base::Init ioInit;
std::cerr << "Double registration of singletons of the same "
"underlying type; check for multiple definitions "
"of type folly::LeakySingleton<"
<< type.name() << ">\n";
std::abort();
}
[[noreturn]] void singletonWarnLeakyInstantiatingNotRegisteredAndAbort(
const TypeDescriptor& type) {
auto trace = detail::getSingletonStackTrace();
LOG(FATAL) << "Creating instance for unregistered singleton: " << type.name()
<< "\n"
<< "Stacktrace:\n" << (!trace.empty() ? trace : "(not available)");
folly::assume_unreachable();
}
[[noreturn]] void singletonWarnRegisterMockEarlyAndAbort(
const TypeDescriptor& type) {
LOG(FATAL) << "Registering mock before singleton was registered: "
<< type.name();
folly::assume_unreachable();
}
void singletonWarnDestroyInstanceLeak(
const TypeDescriptor& type,
const void* ptr) {
LOG(ERROR) << "Singleton of type " << type.name() << " has a "
<< "living reference at destroyInstances time; beware! Raw "
<< "pointer is " << ptr << ". It is very likely "
<< "that some other singleton is holding a shared_ptr to it. "
<< "This singleton will be leaked (even if a shared_ptr to it "
<< "is eventually released)."
<< "Make sure dependencies between these singletons are "
<< "properly defined.";
}
[[noreturn]] void singletonWarnCreateCircularDependencyAndAbort(
const TypeDescriptor& type) {
LOG(FATAL) << "circular singleton dependency: " << type.name();
folly::assume_unreachable();
}
[[noreturn]] void singletonWarnCreateUnregisteredAndAbort(
const TypeDescriptor& type) {
auto trace = detail::getSingletonStackTrace();
LOG(FATAL) << "Creating instance for unregistered singleton: " << type.name()
<< "\n"
<< "Stacktrace:\n" << (!trace.empty() ? trace : "(not available)");
folly::assume_unreachable();
}
[[noreturn]] void singletonWarnCreateBeforeRegistrationCompleteAndAbort(
const TypeDescriptor& type) {
auto trace = detail::getSingletonStackTrace();
LOG(FATAL) << "Singleton " << type.name() << " requested before "
<< "registrationComplete() call.\n"
<< "This usually means that either main() never called "
<< "folly::init, or singleton was requested before main() "
<< "(which is not allowed).\n"
<< "Stacktrace:\n" << (!trace.empty() ? trace : "(not available)");
folly::assume_unreachable();
}
void singletonPrintDestructionStackTrace(const TypeDescriptor& type) {
auto trace = detail::getSingletonStackTrace();
LOG(ERROR) << "Singleton " << type.name() << " was released.\n"
<< "Stacktrace:\n" << (!trace.empty() ? trace : "(not available)");
}
[[noreturn]] void singletonThrowNullCreator(const std::type_info& type) {
auto const msg = sformat(
"nullptr_t should be passed if you want {} to be default constructed",
demangle(type));
throw std::logic_error(msg);
}
[[noreturn]] void singletonThrowGetInvokedAfterDestruction(
const TypeDescriptor& type) {
throw std::runtime_error(
"Raw pointer to a singleton requested after its destruction."
" Singleton type is: " +
type.name());
}
// clang-format on
} // namespace detail
namespace {
struct FatalHelper {
~FatalHelper() {
if (!leakedSingletons_.empty()) {
std::string leakedTypes;
for (const auto& singleton : leakedSingletons_) {
leakedTypes += "\t" + singleton.name() + "\n";
}
LOG(DFATAL) << "Singletons of the following types had living references "
<< "after destroyInstances was finished:\n"
<< leakedTypes
<< "beware! It is very likely that those singleton instances "
<< "are leaked.";
}
}
std::vector<detail::TypeDescriptor> leakedSingletons_;
};
#if defined(__APPLE__) || defined(_MSC_VER)
// OS X doesn't support constructor priorities.
FatalHelper fatalHelper;
#else
FatalHelper __attribute__((__init_priority__(101))) fatalHelper;
#endif
} // namespace
SingletonVault::~SingletonVault() {
destroyInstances();
}
void SingletonVault::registerSingleton(detail::SingletonHolderBase* entry) {
auto state = state_.rlock();
state->check(detail::SingletonVaultState::Type::Running);
if (UNLIKELY(state->registrationComplete)) {
LOG(ERROR) << "Registering singleton after registrationComplete().";
}
auto singletons = singletons_.wlock();
CHECK_THROW(
singletons->emplace(entry->type(), entry).second, std::logic_error);
}
void SingletonVault::addEagerInitSingleton(detail::SingletonHolderBase* entry) {
auto state = state_.rlock();
state->check(detail::SingletonVaultState::Type::Running);
if (UNLIKELY(state->registrationComplete)) {
LOG(ERROR) << "Registering for eager-load after registrationComplete().";
}
CHECK_THROW(singletons_.rlock()->count(entry->type()), std::logic_error);
auto eagerInitSingletons = eagerInitSingletons_.wlock();
eagerInitSingletons->insert(entry);
}
void SingletonVault::registrationComplete() {
std::atexit([]() { SingletonVault::singleton()->destroyInstances(); });
auto state = state_.wlock();
state->check(detail::SingletonVaultState::Type::Running);
if (state->registrationComplete) {
return;
}
auto singletons = singletons_.rlock();
if (type_ == Type::Strict) {
for (const auto& p : *singletons) {
if (p.second->hasLiveInstance()) {
throw std::runtime_error(
"Singleton " + p.first.name() +
" created before registration was complete.");
}
}
}
state->registrationComplete = true;
}
void SingletonVault::doEagerInit() {
{
auto state = state_.rlock();
state->check(detail::SingletonVaultState::Type::Running);
if (UNLIKELY(!state->registrationComplete)) {
throw std::logic_error("registrationComplete() not yet called");
}
}
auto eagerInitSingletons = eagerInitSingletons_.rlock();
for (auto* single : *eagerInitSingletons) {
single->createInstance();
}
}
void SingletonVault::doEagerInitVia(Executor& exe, folly::Baton<>* done) {
{
auto state = state_.rlock();
state->check(detail::SingletonVaultState::Type::Running);
if (UNLIKELY(!state->registrationComplete)) {
throw std::logic_error("registrationComplete() not yet called");
}
}
auto eagerInitSingletons = eagerInitSingletons_.rlock();
auto countdown =
std::make_shared<std::atomic<size_t>>(eagerInitSingletons->size());
for (auto* single : *eagerInitSingletons) {
// countdown is retained by shared_ptr, and will be alive until last lambda
// is done. notifyBaton is provided by the caller, and expected to remain
// present (if it's non-nullptr). singletonSet can go out of scope but
// its values, which are SingletonHolderBase pointers, are alive as long as
// SingletonVault is not being destroyed.
exe.add([=] {
// decrement counter and notify if requested, whether initialization
// was successful, was skipped (already initialized), or exception thrown.
SCOPE_EXIT {
if (--(*countdown) == 0) {
if (done != nullptr) {
done->post();
}
}
};
// if initialization is in progress in another thread, don't try to init
// here. Otherwise the current thread will block on 'createInstance'.
if (!single->creationStarted()) {
single->createInstance();
}
});
}
}
void SingletonVault::destroyInstances() {
auto stateW = state_.wlock();
if (stateW->state == detail::SingletonVaultState::Type::Quiescing) {
return;
}
stateW->state = detail::SingletonVaultState::Type::Quiescing;
auto stateR = stateW.moveFromWriteToRead();
{
auto singletons = singletons_.rlock();
auto creationOrder = creationOrder_.rlock();
CHECK_GE(singletons->size(), creationOrder->size());
// Release all ReadMostlyMainPtrs at once
{
ReadMostlyMainPtrDeleter<> deleter;
for (auto& singleton_type : *creationOrder) {
singletons->at(singleton_type)->preDestroyInstance(deleter);
}
}
for (auto type_iter = creationOrder->rbegin();
type_iter != creationOrder->rend();
++type_iter) {
singletons->at(*type_iter)->destroyInstance();
}
for (auto& singleton_type : *creationOrder) {
auto instance = singletons->at(singleton_type);
if (!instance->hasLiveInstance()) {
continue;
}
fatalHelper.leakedSingletons_.push_back(instance->type());
}
}
{
auto creationOrder = creationOrder_.wlock();
creationOrder->clear();
}
}
void SingletonVault::reenableInstances() {
auto state = state_.wlock();
state->check(detail::SingletonVaultState::Type::Quiescing);
state->state = detail::SingletonVaultState::Type::Running;
}
void SingletonVault::scheduleDestroyInstances() {
// Add a dependency on folly::ThreadLocal to make sure all its static
// singletons are initalized first.
threadlocal_detail::StaticMeta<void, void>::instance();
std::atexit([] { SingletonVault::singleton()->destroyInstances(); });
}
} // namespace folly
<|endoftext|>
|
<commit_before>#include <vector>
#include <boost/math/constants/constants.hpp>
#include <boost/python.hpp>
#include <boost/python/suite/indexing/vector_indexing_suite.hpp>
#include <cal3d/buffersource.h>
#include <cal3d/coreanimation.h>
#include <cal3d/coremorphanimation.h>
#include <cal3d/corebone.h>
#include <cal3d/corematerial.h>
#include <cal3d/coremesh.h>
#include <cal3d/coreskeleton.h>
#include <cal3d/coresubmesh.h>
#include <cal3d/loader.h>
#include <cal3d/saver.h>
#include <cal3d/error.h>
using namespace boost::python;
CalCoreAnimationPtr loadCoreAnimationFromBuffer(const cal3d::Buffer& buffer) {
CalBufferSource cbs(buffer.data(), buffer.size());
return CalLoader::loadCoreAnimation(cbs);
}
bool saveCoreAnimation(const boost::shared_ptr<CalCoreAnimation>& animation, const std::string& path) {
return CalSaver::saveCoreAnimation(path, animation.get());
}
CalCoreSkeletonPtr loadCoreSkeletonFromBuffer(const cal3d::Buffer& buffer) {
CalBufferSource cbs(buffer.data(), buffer.size());
return CalLoader::loadCoreSkeleton(cbs);
}
bool saveCoreSkeleton(const boost::shared_ptr<CalCoreSkeleton>& skeleton, const std::string& path) {
return CalSaver::saveCoreSkeleton(path, skeleton.get());
}
CalCoreMaterialPtr loadCoreMaterialFromBuffer(const cal3d::Buffer& buffer) {
CalBufferSource cbs(buffer.data(), buffer.size());
return CalLoader::loadCoreMaterial(cbs);
}
bool saveCoreMaterial(const boost::shared_ptr<CalCoreMaterial>& material, const std::string& path) {
return CalSaver::saveCoreMaterial(path, material.get());
}
CalCoreMeshPtr loadCoreMeshFromBuffer(const cal3d::Buffer& buffer) {
CalBufferSource cbs(buffer.data(), buffer.size());
return CalLoader::loadCoreMesh(cbs);
}
bool saveCoreMesh(const boost::shared_ptr<CalCoreMesh>& mesh, const std::string& path) {
return CalSaver::saveCoreMesh(path, mesh.get());
}
CalCoreMorphAnimationPtr loadCoreMorphAnimationFromBuffer(const cal3d::Buffer& buffer) {
CalBufferSource cbs(buffer.data(), buffer.size());
return CalLoader::loadCoreMorphAnimation(cbs);
}
bool saveCoreMorphAnimation(const boost::shared_ptr<CalCoreMorphAnimation>& animatedMorph, const std::string& path) {
return CalSaver::saveCoreMorphAnimation(path, animatedMorph.get());
}
tuple getCoreSkeletonSceneAmbientColor(const CalCoreSkeletonPtr& skel) {
CalVector sceneAmbient = skel->sceneAmbientColor;
return make_tuple(
sceneAmbient.x,
sceneAmbient.y,
sceneAmbient.z
);
}
void setCoreSkeletonSceneAmbientColor(const CalCoreSkeletonPtr& skel, tuple c) {
if (len(c) != 3) {
PyErr_SetString(PyExc_ValueError, "sceneAmbientColor must be a triple");
throw_error_already_set();
}
skel->sceneAmbientColor.x = extract<float>(c[0]);
skel->sceneAmbientColor.y = extract<float>(c[1]);
skel->sceneAmbientColor.z = extract<float>(c[2]);
}
list getKeyframes(const CalCoreMorphTrack* t) {
list rv;
const std::vector<CalCoreMorphKeyframe>& keyframes = t->keyframes;
for (
std::vector<CalCoreMorphKeyframe>::const_iterator i = keyframes.begin();
i != keyframes.end();
++i
) {
rv.append(*i);
}
return rv;
}
list getTracks(const CalCoreMorphAnimation* m) {
list rv;
const std::vector<CalCoreMorphTrack>& tracks = m->tracks;
for (
std::vector<CalCoreMorphTrack>::const_iterator i = tracks.begin();
i != tracks.end();
++i
) {
rv.append(*i);
}
return rv;
}
namespace cal3d {
struct PythonBuffer : public Buffer {
public:
PythonBuffer(PyObject* p) {
_ = p;
incref(get());
}
~PythonBuffer() {
boost::python::PyGILState_AssertIsCurrent();
decref(get());
}
size_t size() const {
void* data;
return get()->ob_type->tp_as_buffer->bf_getreadbuffer(get(), 0, &data);
}
const void* data() const {
void* data;
get()->ob_type->tp_as_buffer->bf_getreadbuffer(get(), 0, &data);
return data;
}
boost::shared_ptr<Buffer> clone() const {
return boost::shared_ptr<Buffer>(new PythonBuffer(get()));
}
private:
PyObject* get() const {
return static_cast<PyObject*>(_);
}
};
struct BufferFromPythonObject {
BufferFromPythonObject() {
converter::registry::push_back(
&convertible,
&construct,
boost::python::type_id<Buffer>()
);
}
static void* convertible(PyObject* obj_ptr) {
return (obj_ptr->ob_type->tp_as_buffer &&
obj_ptr->ob_type->tp_as_buffer->bf_getreadbuffer)
? obj_ptr
: 0;
}
static void construct(
PyObject* obj_ptr,
boost::python::converter::rvalue_from_python_stage1_data* data
) {
// Note that we're registered as a converter to the Buffer interface,
// so Boost has already allocated sizeof(Buffer) for us. Since we're
// constructing PythonStringBuffer into that memory, assert that
// PythonStringBuffer and Buffer have the same size.
BOOST_STATIC_ASSERT(sizeof(Buffer) == sizeof(PythonBuffer));
void* storage = ((boost::python::converter::rvalue_from_python_storage<PythonBuffer>*)data)->storage.bytes;
new(storage) PythonBuffer(obj_ptr);
data->convertible = storage;
}
};
}
template<unsigned i>
CalIndex getFaceIndex(const CalCoreSubmesh::Face& f) {
return f.vertexId[i];
}
struct PythonVertex {
PythonVertex() {}
PythonVertex(const CalCoreSubmesh::Vertex& v) {
position.x = v.position.x;
position.y = v.position.y;
position.z = v.position.z;
normal.x = v.normal.x;
normal.y = v.normal.y;
normal.z = v.normal.z;
}
CalVector position;
CalVector normal;
bool operator==(const PythonVertex& rhs) const {
return position == rhs.position && normal == rhs.normal;
}
};
std::vector<PythonVertex> getVertices(const CalCoreSubmesh& submesh) {
return std::vector<PythonVertex>(
submesh.getVectorVertex().begin(),
submesh.getVectorVertex().end());
}
template<typename T>
void exportVector(const char* name) {
class_<std::vector<T> >(name)
.def(vector_indexing_suite< std::vector<T>, true>())
;
}
std::string VectorRepr(const CalVector& v) {
std::ostringstream os;
os << "cal3d.Vector(" << v.x << ", " << v.y << ", " << v.z << ")";
return os.str();
}
std::string QuaternionRepr(const CalQuaternion& q) {
float h2 = acos(-q.w);
float angle = h2 * 360 / boost::math::constants::pi<float>();
float s = sin(h2);
std::ostringstream os;
os << "cal3d.Quaternion(angle=" << angle << ", axis=(" << (q.x / s) << ", " << (q.y / s) << ", " << (q.z / s) << "))";
return os.str();
}
std::string RotateTranslateRepr(const cal3d::RotateTranslate& t) {
return "cal3d.RotateTranslate(" + QuaternionRepr(t.rotation) + ", " + VectorRepr(t.translation) + ")";
}
#ifndef NDEBUG
BOOST_PYTHON_MODULE(_cal3d_debug)
#else
BOOST_PYTHON_MODULE(_cal3d)
#endif
{
cal3d::BufferFromPythonObject();
class_<CalVector>("Vector")
.def("__repr__", &VectorRepr)
.def_readwrite("x", &CalVector::x)
.def_readwrite("y", &CalVector::y)
.def_readwrite("z", &CalVector::z)
;
class_<CalQuaternion>("Quaternion")
.def("__repr__", &QuaternionRepr)
.def_readwrite("x", &CalQuaternion::x)
.def_readwrite("y", &CalQuaternion::y)
.def_readwrite("z", &CalQuaternion::z)
.def_readwrite("w", &CalQuaternion::w)
;
class_<cal3d::RotateTranslate>("Transform")
.def("__repr__", &RotateTranslateRepr)
.def_readwrite("translation", &cal3d::RotateTranslate::translation)
.def_readwrite("rotation", &cal3d::RotateTranslate::rotation)
;
class_<CalCoreBone, boost::shared_ptr<CalCoreBone> >("CoreBone", no_init)
.def(init<std::string>())
.def_readwrite("parentIndex", &CalCoreBone::parentId)
.def_readonly("name", &CalCoreBone::name)
.def_readwrite("relativeTransform", &CalCoreBone::relativeTransform)
.def_readwrite("inverseBindPoseTransform", &CalCoreBone::inverseBindPoseTransform)
;
exportVector<CalCoreBonePtr>("BoneVector");
class_<CalCoreSkeleton, boost::shared_ptr<CalCoreSkeleton>, boost::noncopyable>("CoreSkeleton")
.def("addCoreBone", &CalCoreSkeleton::addCoreBone)
.def("scale", &CalCoreSkeleton::scale)
.add_property("sceneAmbientColor", &getCoreSkeletonSceneAmbientColor, &setCoreSkeletonSceneAmbientColor)
.add_property("bones", make_function(&CalCoreSkeleton::getCoreBones, return_value_policy<return_by_value>()))
;
{
scope CalCoreMaterial_class(
class_<CalCoreMaterial, boost::shared_ptr<CalCoreMaterial> >("CoreMaterial")
.def_readwrite("maps", &CalCoreMaterial::maps)
);
exportVector<CalCoreMaterial::Map>("MapVector");
class_<CalCoreMaterial::Map>("Map")
.def_readwrite("filename", &CalCoreMaterial::Map::filename)
.def_readwrite("type", &CalCoreMaterial::Map::type)
;
}
class_<CalCoreSubmesh::Face>("Triangle")
.add_property("v1", &getFaceIndex<0>)
.add_property("v2", &getFaceIndex<1>)
.add_property("v3", &getFaceIndex<2>)
;
exportVector<CalCoreSubmesh::Face>("TriangleVector");
class_<PythonVertex>("Vertex")
.def_readwrite("position", &PythonVertex::position)
.def_readwrite("normal", &PythonVertex::normal)
;
exportVector<PythonVertex>("VertexVector");
class_<CalCoreSubmesh::TextureCoordinate>("TextureCoordinate")
.def_readwrite("u", &CalCoreSubmesh::TextureCoordinate::u)
.def_readwrite("v", &CalCoreSubmesh::TextureCoordinate::v)
;
exportVector<CalCoreSubmesh::TextureCoordinate>("TextureCoordinateVector");
exportVector<std::vector<CalCoreSubmesh::TextureCoordinate> >("TextureCoordinateVectorVector");
class_<CalCoreSubmesh::Influence>("Influence")
.def_readwrite("boneId", &CalCoreSubmesh::Influence::boneId)
.def_readwrite("weight", &CalCoreSubmesh::Influence::weight)
.def_readwrite("isLast", &CalCoreSubmesh::Influence::lastInfluenceForThisVertex)
;
exportVector<CalCoreSubmesh::Influence>("InfluenceVector");
class_<CalCoreSubmesh, boost::shared_ptr<CalCoreSubmesh>, boost::noncopyable>("CoreSubmesh", no_init)
.def_readwrite("coreMaterialThreadId", &CalCoreSubmesh::coreMaterialThreadId)
.def_readwrite("triangles", &CalCoreSubmesh::faces)
.add_property("vertices", &getVertices)
.add_property("hasVertexColors", &CalCoreSubmesh::hasVertexColors)
.add_property("colors", make_function(&CalCoreSubmesh::getVertexColors, return_value_policy<return_by_value>()))
.add_property("texcoords", make_function(&CalCoreSubmesh::getVectorVectorTextureCoordinate, return_value_policy<return_by_value>()))
.add_property("influences", make_function(&CalCoreSubmesh::getInfluences, return_value_policy<return_by_value>()))
;
exportVector<CalCoreSubmeshPtr>("CoreSubmeshVector");
class_<CalCoreMesh, CalCoreMeshPtr>("CoreMesh")
.def_readwrite("submeshes", &CalCoreMesh::submeshes)
.def("scale", &CalCoreMesh::scale)
.def("fixup", &CalCoreMesh::fixup)
;
class_<CalCoreKeyframe>("CoreKeyframe")
.def_readwrite("time", &CalCoreKeyframe::time)
.def_readwrite("transform", &CalCoreKeyframe::transform)
;
exportVector<CalCoreKeyframe>("CoreKeyframeVector");
class_<CalCoreTrack>("CoreTrack", init<int, const CalCoreTrack::KeyframeList&>())
.def_readwrite("coreBoneId", &CalCoreTrack::coreBoneId)
.def_readwrite("keyframes", &CalCoreTrack::keyframes)
;
exportVector<CalCoreTrack>("CoreTrackVector");
class_<CalCoreAnimation, CalCoreAnimationPtr>("CoreAnimation")
.def("scale", &CalCoreAnimation::scale)
.def("fixup", &CalCoreAnimation::fixup)
.def_readwrite("duration", &CalCoreAnimation::duration)
.def_readwrite("tracks", &CalCoreAnimation::tracks)
;
class_<CalCoreMorphKeyframe>("CoreMorphKeyframe")
.add_property("time", &CalCoreMorphKeyframe::time)
.add_property("weight", &CalCoreMorphKeyframe::weight)
;
class_<CalCoreMorphTrack, CalCoreMorphTrackPtr>("CoreMorphTrack")
.def_readonly("name", &CalCoreMorphTrack::morphName)
.add_property("keyframes", &getKeyframes)
;
class_<CalCoreMorphAnimation, CalCoreMorphAnimationPtr>("CoreMorphAnimation")
.def("removeZeroScaleTracks", &CalCoreMorphAnimation::removeZeroScaleTracks)
.def("scale", &CalCoreMorphAnimation::scale)
.def_readonly("duration", &CalCoreMorphAnimation::duration)
.add_property("tracks", &getTracks)
;
def("loadCoreAnimationFromBuffer", &loadCoreAnimationFromBuffer);
def("saveCoreAnimation", &saveCoreAnimation);
def("saveCoreAnimationToBuffer", &CalSaver::saveCoreAnimationToBuffer);
def("loadCoreSkeletonFromBuffer", &loadCoreSkeletonFromBuffer);
def("saveCoreSkeleton", &saveCoreSkeleton);
def("saveCoreSkeletonToBuffer", &CalSaver::saveCoreSkeletonToBuffer);
def("loadCoreMaterialFromBuffer", &loadCoreMaterialFromBuffer);
def("saveCoreMaterial", &saveCoreMaterial);
def("saveCoreMaterialToBuffer", &CalSaver::saveCoreMaterialToBuffer);
def("loadCoreMeshFromBuffer", &loadCoreMeshFromBuffer);
def("saveCoreMesh", &saveCoreMesh);
def("saveCoreMeshToBuffer", &CalSaver::saveCoreMeshToBuffer);
def("loadCoreMorphAnimationFromBuffer", &loadCoreMorphAnimationFromBuffer);
def("saveCoreMorphAnimation", &saveCoreMorphAnimation);
def("saveCoreMorphAnimationToBuffer", &CalSaver::saveCoreMorphAnimationToBuffer);
def("getLastErrorText", &CalError::getLastErrorText);
}
<commit_msg>Add buttonNodes when the scenepresenter decides we need to do so.<commit_after>#include <vector>
#include <boost/math/constants/constants.hpp>
#include <boost/python.hpp>
#include <boost/python/suite/indexing/vector_indexing_suite.hpp>
#include <cal3d/buffersource.h>
#include <cal3d/coreanimation.h>
#include <cal3d/coremorphanimation.h>
#include <cal3d/corebone.h>
#include <cal3d/corematerial.h>
#include <cal3d/coremesh.h>
#include <cal3d/coreskeleton.h>
#include <cal3d/coresubmesh.h>
#include <cal3d/loader.h>
#include <cal3d/saver.h>
#include <cal3d/error.h>
using namespace boost::python;
CalCoreAnimationPtr loadCoreAnimationFromBuffer(const cal3d::Buffer& buffer) {
CalBufferSource cbs(buffer.data(), buffer.size());
return CalLoader::loadCoreAnimation(cbs);
}
bool saveCoreAnimation(const boost::shared_ptr<CalCoreAnimation>& animation, const std::string& path) {
return CalSaver::saveCoreAnimation(path, animation.get());
}
CalCoreSkeletonPtr loadCoreSkeletonFromBuffer(const cal3d::Buffer& buffer) {
CalBufferSource cbs(buffer.data(), buffer.size());
return CalLoader::loadCoreSkeleton(cbs);
}
bool saveCoreSkeleton(const boost::shared_ptr<CalCoreSkeleton>& skeleton, const std::string& path) {
return CalSaver::saveCoreSkeleton(path, skeleton.get());
}
CalCoreMaterialPtr loadCoreMaterialFromBuffer(const cal3d::Buffer& buffer) {
CalBufferSource cbs(buffer.data(), buffer.size());
return CalLoader::loadCoreMaterial(cbs);
}
bool saveCoreMaterial(const boost::shared_ptr<CalCoreMaterial>& material, const std::string& path) {
return CalSaver::saveCoreMaterial(path, material.get());
}
CalCoreMeshPtr loadCoreMeshFromBuffer(const cal3d::Buffer& buffer) {
CalBufferSource cbs(buffer.data(), buffer.size());
return CalLoader::loadCoreMesh(cbs);
}
bool saveCoreMesh(const boost::shared_ptr<CalCoreMesh>& mesh, const std::string& path) {
return CalSaver::saveCoreMesh(path, mesh.get());
}
CalCoreMorphAnimationPtr loadCoreMorphAnimationFromBuffer(const cal3d::Buffer& buffer) {
CalBufferSource cbs(buffer.data(), buffer.size());
return CalLoader::loadCoreMorphAnimation(cbs);
}
bool saveCoreMorphAnimation(const boost::shared_ptr<CalCoreMorphAnimation>& animatedMorph, const std::string& path) {
return CalSaver::saveCoreMorphAnimation(path, animatedMorph.get());
}
tuple getCoreSkeletonSceneAmbientColor(const CalCoreSkeletonPtr& skel) {
CalVector sceneAmbient = skel->sceneAmbientColor;
return make_tuple(
sceneAmbient.x,
sceneAmbient.y,
sceneAmbient.z
);
}
void setCoreSkeletonSceneAmbientColor(const CalCoreSkeletonPtr& skel, tuple c) {
if (len(c) != 3) {
PyErr_SetString(PyExc_ValueError, "sceneAmbientColor must be a triple");
throw_error_already_set();
}
skel->sceneAmbientColor.x = extract<float>(c[0]);
skel->sceneAmbientColor.y = extract<float>(c[1]);
skel->sceneAmbientColor.z = extract<float>(c[2]);
}
list getKeyframes(const CalCoreMorphTrack* t) {
list rv;
const std::vector<CalCoreMorphKeyframe>& keyframes = t->keyframes;
for (
std::vector<CalCoreMorphKeyframe>::const_iterator i = keyframes.begin();
i != keyframes.end();
++i
) {
rv.append(*i);
}
return rv;
}
list getTracks(const CalCoreMorphAnimation* m) {
list rv;
const std::vector<CalCoreMorphTrack>& tracks = m->tracks;
for (
std::vector<CalCoreMorphTrack>::const_iterator i = tracks.begin();
i != tracks.end();
++i
) {
rv.append(*i);
}
return rv;
}
namespace cal3d {
struct PythonBuffer : public Buffer {
public:
PythonBuffer(PyObject* p) {
_ = p;
incref(get());
}
~PythonBuffer() {
boost::python::PyGILState_AssertIsCurrent();
decref(get());
}
size_t size() const {
void* data;
return get()->ob_type->tp_as_buffer->bf_getreadbuffer(get(), 0, &data);
}
const void* data() const {
void* data;
get()->ob_type->tp_as_buffer->bf_getreadbuffer(get(), 0, &data);
return data;
}
boost::shared_ptr<Buffer> clone() const {
return boost::shared_ptr<Buffer>(new PythonBuffer(get()));
}
private:
PyObject* get() const {
return static_cast<PyObject*>(_);
}
};
struct BufferFromPythonObject {
BufferFromPythonObject() {
converter::registry::push_back(
&convertible,
&construct,
boost::python::type_id<Buffer>()
);
}
static void* convertible(PyObject* obj_ptr) {
return (obj_ptr->ob_type->tp_as_buffer &&
obj_ptr->ob_type->tp_as_buffer->bf_getreadbuffer)
? obj_ptr
: 0;
}
static void construct(
PyObject* obj_ptr,
boost::python::converter::rvalue_from_python_stage1_data* data
) {
// Note that we're registered as a converter to the Buffer interface,
// so Boost has already allocated sizeof(Buffer) for us. Since we're
// constructing PythonStringBuffer into that memory, assert that
// PythonStringBuffer and Buffer have the same size.
BOOST_STATIC_ASSERT(sizeof(Buffer) == sizeof(PythonBuffer));
void* storage = ((boost::python::converter::rvalue_from_python_storage<PythonBuffer>*)data)->storage.bytes;
new(storage) PythonBuffer(obj_ptr);
data->convertible = storage;
}
};
}
template<unsigned i>
CalIndex getFaceIndex(const CalCoreSubmesh::Face& f) {
return f.vertexId[i];
}
struct PythonVertex {
PythonVertex() {}
PythonVertex(const CalCoreSubmesh::Vertex& v) {
position.x = v.position.x;
position.y = v.position.y;
position.z = v.position.z;
normal.x = v.normal.x;
normal.y = v.normal.y;
normal.z = v.normal.z;
}
CalVector position;
CalVector normal;
bool operator==(const PythonVertex& rhs) const {
return position == rhs.position && normal == rhs.normal;
}
};
std::vector<PythonVertex> getVertices(const CalCoreSubmesh& submesh) {
return std::vector<PythonVertex>(
submesh.getVectorVertex().begin(),
submesh.getVectorVertex().end());
}
template<typename T>
void exportVector(const char* name) {
class_<std::vector<T> >(name)
.def(vector_indexing_suite< std::vector<T>, true>())
;
}
std::string VectorRepr(const CalVector& v) {
std::ostringstream os;
os << "cal3d.Vector(" << v.x << ", " << v.y << ", " << v.z << ")";
return os.str();
}
std::string QuaternionRepr(const CalQuaternion& q) {
float h2 = acos(-q.w);
float angle = h2 * 360 / boost::math::constants::pi<float>();
float s = sin(h2);
std::ostringstream os;
os << "cal3d.Quaternion(angle=" << angle << ", axis=(" << (q.x / s) << ", " << (q.y / s) << ", " << (q.z / s) << "))";
return os.str();
}
std::string RotateTranslateRepr(const cal3d::RotateTranslate& t) {
return "cal3d.RotateTranslate(" + QuaternionRepr(t.rotation) + ", " + VectorRepr(t.translation) + ")";
}
#ifndef NDEBUG
BOOST_PYTHON_MODULE(_cal3d_debug)
#else
BOOST_PYTHON_MODULE(_cal3d)
#endif
{
cal3d::BufferFromPythonObject();
class_<CalVector>("Vector")
.def("__repr__", &VectorRepr)
.def_readwrite("x", &CalVector::x)
.def_readwrite("y", &CalVector::y)
.def_readwrite("z", &CalVector::z)
;
class_<CalQuaternion>("Quaternion")
.def("__repr__", &QuaternionRepr)
.def_readwrite("x", &CalQuaternion::x)
.def_readwrite("y", &CalQuaternion::y)
.def_readwrite("z", &CalQuaternion::z)
.def_readwrite("w", &CalQuaternion::w)
;
class_<cal3d::RotateTranslate>("Transform")
.def("__repr__", &RotateTranslateRepr)
.def_readwrite("translation", &cal3d::RotateTranslate::translation)
.def_readwrite("rotation", &cal3d::RotateTranslate::rotation)
;
class_<CalCoreBone, boost::shared_ptr<CalCoreBone> >("CoreBone",
init<std::string, int>())
.def(init<std::string>())
.def_readwrite("parentIndex", &CalCoreBone::parentId)
.def_readonly("name", &CalCoreBone::name)
.def_readwrite("relativeTransform", &CalCoreBone::relativeTransform)
.def_readwrite("inverseBindPoseTransform", &CalCoreBone::inverseBindPoseTransform)
;
exportVector<CalCoreBonePtr>("BoneVector");
class_<CalCoreSkeleton, boost::shared_ptr<CalCoreSkeleton>, boost::noncopyable>("CoreSkeleton")
.def("addCoreBone", &CalCoreSkeleton::addCoreBone)
.def("scale", &CalCoreSkeleton::scale)
.add_property("sceneAmbientColor", &getCoreSkeletonSceneAmbientColor, &setCoreSkeletonSceneAmbientColor)
.add_property("bones", make_function(&CalCoreSkeleton::getCoreBones, return_value_policy<return_by_value>()))
;
{
scope CalCoreMaterial_class(
class_<CalCoreMaterial, boost::shared_ptr<CalCoreMaterial> >("CoreMaterial")
.def_readwrite("maps", &CalCoreMaterial::maps)
);
exportVector<CalCoreMaterial::Map>("MapVector");
class_<CalCoreMaterial::Map>("Map")
.def_readwrite("filename", &CalCoreMaterial::Map::filename)
.def_readwrite("type", &CalCoreMaterial::Map::type)
;
}
class_<CalCoreSubmesh::Face>("Triangle")
.add_property("v1", &getFaceIndex<0>)
.add_property("v2", &getFaceIndex<1>)
.add_property("v3", &getFaceIndex<2>)
;
exportVector<CalCoreSubmesh::Face>("TriangleVector");
class_<PythonVertex>("Vertex")
.def_readwrite("position", &PythonVertex::position)
.def_readwrite("normal", &PythonVertex::normal)
;
exportVector<PythonVertex>("VertexVector");
class_<CalCoreSubmesh::TextureCoordinate>("TextureCoordinate")
.def_readwrite("u", &CalCoreSubmesh::TextureCoordinate::u)
.def_readwrite("v", &CalCoreSubmesh::TextureCoordinate::v)
;
exportVector<CalCoreSubmesh::TextureCoordinate>("TextureCoordinateVector");
exportVector<std::vector<CalCoreSubmesh::TextureCoordinate> >("TextureCoordinateVectorVector");
class_<CalCoreSubmesh::Influence>("Influence")
.def_readwrite("boneId", &CalCoreSubmesh::Influence::boneId)
.def_readwrite("weight", &CalCoreSubmesh::Influence::weight)
.def_readwrite("isLast", &CalCoreSubmesh::Influence::lastInfluenceForThisVertex)
;
exportVector<CalCoreSubmesh::Influence>("InfluenceVector");
class_<CalCoreSubmesh, boost::shared_ptr<CalCoreSubmesh>, boost::noncopyable>("CoreSubmesh", no_init)
.def_readwrite("coreMaterialThreadId", &CalCoreSubmesh::coreMaterialThreadId)
.def_readwrite("triangles", &CalCoreSubmesh::faces)
.add_property("vertices", &getVertices)
.add_property("hasVertexColors", &CalCoreSubmesh::hasVertexColors)
.add_property("colors", make_function(&CalCoreSubmesh::getVertexColors, return_value_policy<return_by_value>()))
.add_property("texcoords", make_function(&CalCoreSubmesh::getVectorVectorTextureCoordinate, return_value_policy<return_by_value>()))
.add_property("influences", make_function(&CalCoreSubmesh::getInfluences, return_value_policy<return_by_value>()))
;
exportVector<CalCoreSubmeshPtr>("CoreSubmeshVector");
class_<CalCoreMesh, CalCoreMeshPtr>("CoreMesh")
.def_readwrite("submeshes", &CalCoreMesh::submeshes)
.def("scale", &CalCoreMesh::scale)
.def("fixup", &CalCoreMesh::fixup)
;
class_<CalCoreKeyframe>("CoreKeyframe")
.def_readwrite("time", &CalCoreKeyframe::time)
.def_readwrite("transform", &CalCoreKeyframe::transform)
;
exportVector<CalCoreKeyframe>("CoreKeyframeVector");
class_<CalCoreTrack>("CoreTrack", init<int, const CalCoreTrack::KeyframeList&>())
.def_readwrite("coreBoneId", &CalCoreTrack::coreBoneId)
.def_readwrite("keyframes", &CalCoreTrack::keyframes)
;
exportVector<CalCoreTrack>("CoreTrackVector");
class_<CalCoreAnimation, CalCoreAnimationPtr>("CoreAnimation")
.def("scale", &CalCoreAnimation::scale)
.def("fixup", &CalCoreAnimation::fixup)
.def_readwrite("duration", &CalCoreAnimation::duration)
.def_readwrite("tracks", &CalCoreAnimation::tracks)
;
class_<CalCoreMorphKeyframe>("CoreMorphKeyframe")
.add_property("time", &CalCoreMorphKeyframe::time)
.add_property("weight", &CalCoreMorphKeyframe::weight)
;
class_<CalCoreMorphTrack, CalCoreMorphTrackPtr>("CoreMorphTrack")
.def_readonly("name", &CalCoreMorphTrack::morphName)
.add_property("keyframes", &getKeyframes)
;
class_<CalCoreMorphAnimation, CalCoreMorphAnimationPtr>("CoreMorphAnimation")
.def("removeZeroScaleTracks", &CalCoreMorphAnimation::removeZeroScaleTracks)
.def("scale", &CalCoreMorphAnimation::scale)
.def_readonly("duration", &CalCoreMorphAnimation::duration)
.add_property("tracks", &getTracks)
;
def("loadCoreAnimationFromBuffer", &loadCoreAnimationFromBuffer);
def("saveCoreAnimation", &saveCoreAnimation);
def("saveCoreAnimationToBuffer", &CalSaver::saveCoreAnimationToBuffer);
def("loadCoreSkeletonFromBuffer", &loadCoreSkeletonFromBuffer);
def("saveCoreSkeleton", &saveCoreSkeleton);
def("saveCoreSkeletonToBuffer", &CalSaver::saveCoreSkeletonToBuffer);
def("loadCoreMaterialFromBuffer", &loadCoreMaterialFromBuffer);
def("saveCoreMaterial", &saveCoreMaterial);
def("saveCoreMaterialToBuffer", &CalSaver::saveCoreMaterialToBuffer);
def("loadCoreMeshFromBuffer", &loadCoreMeshFromBuffer);
def("saveCoreMesh", &saveCoreMesh);
def("saveCoreMeshToBuffer", &CalSaver::saveCoreMeshToBuffer);
def("loadCoreMorphAnimationFromBuffer", &loadCoreMorphAnimationFromBuffer);
def("saveCoreMorphAnimation", &saveCoreMorphAnimation);
def("saveCoreMorphAnimationToBuffer", &CalSaver::saveCoreMorphAnimationToBuffer);
def("getLastErrorText", &CalError::getLastErrorText);
}
<|endoftext|>
|
<commit_before>#include "base/all.h"
#include "rpc/client.h"
#include "rpc/server.h"
#include "benchmark_service.h"
using namespace base;
using namespace std;
using namespace rpc;
using namespace benchmark;
TEST(future, wait_timeout) {
PollMgr* poll = new PollMgr;
ThreadPool* thrpool = new ThreadPool;
// start the server
int svc_port = find_open_port();
EXPECT_NEQ(svc_port, -1);
Server* svr = new Server(poll, thrpool);
BenchmarkService bench_svc;
svr->reg(&bench_svc);
char svc_addr[100];
sprintf(svc_addr, "127.0.0.1:%d", svc_port);
svr->start(svc_addr);
// start the client
ClientPool* clnt_pool = new ClientPool(poll);
BenchmarkProxy* clnt = new BenchmarkProxy(clnt_pool->get_client(svc_addr));
Log::debug("do wait");
Timer t;
t.start();
FutureAttr fu_attr;
fu_attr.callback = [] (Future* fu) {
Log::debug("fu->get_error_code() = %d", fu->get_error_code());
};
Future* fu = clnt->async_sleep(2.3, fu_attr);
double wait_sec = 1.0;
fu->timed_wait(wait_sec);
t.stop();
Log::debug("done wait: %lf seconds", t.elapsed());
EXPECT_LT(fabs(wait_sec - t.elapsed()), 0.1);
delete clnt;
delete clnt_pool;
thrpool->release();
poll->release();
delete svr;
}
<commit_msg>Revert "work around unittest failure"<commit_after>#include "base/all.h"
#include "rpc/client.h"
#include "rpc/server.h"
#include "benchmark_service.h"
using namespace base;
using namespace std;
using namespace rpc;
using namespace benchmark;
TEST(future, wait_timeout) {
PollMgr* poll = new PollMgr;
ThreadPool* thrpool = new ThreadPool;
// start the server
int svc_port = find_open_port();
EXPECT_NEQ(svc_port, -1);
Server* svr = new Server(poll, thrpool);
BenchmarkService bench_svc;
svr->reg(&bench_svc);
char svc_addr[100];
sprintf(svc_addr, "127.0.0.1:%d", svc_port);
svr->start(svc_addr);
// start the client
ClientPool* clnt_pool = new ClientPool(poll);
BenchmarkProxy* clnt = new BenchmarkProxy(clnt_pool->get_client(svc_addr));
Log::debug("do wait");
Timer t;
t.start();
FutureAttr fu_attr;
fu_attr.callback = [] (Future* fu) {
Log::debug("fu->get_error_code() = %d", fu->get_error_code());
};
Future* fu = clnt->async_sleep(2.3, fu_attr);
double wait_sec = 1.0;
fu->timed_wait(wait_sec);
t.stop();
Log::debug("done wait: %lf seconds", t.elapsed());
EXPECT_LT(fabs(wait_sec - t.elapsed()), 0.1);
delete clnt;
delete clnt_pool;
delete svr;
thrpool->release();
poll->release();
}
<|endoftext|>
|
<commit_before>/*
* test_ariane.cpp
*
* Test the ariane module.
*
* author: Cyril Robin <[email protected]>
* created: 2013-10-03
* license: BSD
*/
#define BOOST_TEST_MODULE const_string test
#include <boost/test/included/unit_test.hpp>
#include <sstream>
#include "ariane/ariane.hpp"
BOOST_AUTO_TEST_SUITE( ariane )
BOOST_AUTO_TEST_CASE( test_ariane )
{
BOOST_TEST_MESSAGE( "Test ToDo " << true );
BOOST_CHECK_EQUAL( true , true );
}
BOOST_AUTO_TEST_SUITE_END();
<commit_msg>[test] valid unit test for ariane<commit_after>/*
* test_ariane.cpp
*
* Test the ariane module.
*
* author: Cyril Robin <[email protected]>
* created: 2013-10-03
* license: BSD
*/
#define BOOST_TEST_MODULE const_string test
#include <boost/test/included/unit_test.hpp>
#include <sstream>
#include "ariane/ariane.hpp"
#include "gdalwrap/gdal.hpp"
#include "gladys/nav_graph.hpp"
BOOST_AUTO_TEST_SUITE( ariane )
BOOST_AUTO_TEST_CASE( test_ariane )
{
std::string region_path = "/tmp/test_map.tif";
std::string weight_path = "/tmp/test_wm.tif";
std::string robotm_path = "/tmp/robot.json";
// create a robot model (JSON configuration file)
std::ofstream robot_cfg(robotm_path);
robot_cfg<<"{\"robot\":{\"mass\":1.0,\"radius\":1.0,\"velocity\":2.0}}";
robot_cfg.close();
/* create a region map (GeoTiff image)
*
* U = unknown
* F = flat
* O = obstacle
* S = start (flat ; initial position)
* G = goal (flat)
*
* 1 2 3 4 5 6 7 8 9
*
* 1 F F F S F F F F F
* 2 F F F F F F F F F
* 3 F F F F F F F F F
* 4 O O O O O O O F F
* 5 G F F F F F 0 F F
* 6 F F F F F F 0 F F
* 7 F F F F F F F F F
* 8 F F F F F F F F F
* 9 F F F F F F F F F
*
*/
gdalwrap::gdal region;
region.set_size(gladys::weight_map::N_RASTER, 9, 9);
region.bands[gladys::weight_map::FLAT ].assign(9*9, 1);
region.names[gladys::weight_map::FLAT ] = "FLAT";
region.names[gladys::weight_map::OBSTACLE] = "OBSTACLE";
region.names[gladys::weight_map::NO_3D_CLASS] = "UNKNOWN";
for ( int i=0 ; i < 7 ; i++ ) {
region.bands[gladys::weight_map::FLAT ][i+3*9] = 0.2 ;
region.bands[gladys::weight_map::OBSTACLE][i+3*9] = 0.8 ;
}
for ( int j=3 ; j < 7 ; j++ ) {
region.bands[gladys::weight_map::FLAT ][7+j*9] = 0.2 ;
region.bands[gladys::weight_map::OBSTACLE][7+j*9] = 0.8 ;
}
region.save(region_path);
// create a frontier exploration module from the map
// (Create the weight_map, assumed to be good; cf other unit test)
gladys::weight_map wm( region_path, robotm_path ) ;
ariane ariadne ( wm, 6.0, 0.1) ;
// testing path planning
gladys::point_xy_t s {4,1};
gladys::point_xy_t g {1,5};
gladys::path_t path = ariadne.plan( s, g ) ;
//Check the number of waypoints
BOOST_TEST_MESSAGE( "Path: " + gladys::to_string(path) );
BOOST_CHECK_EQUAL( path.size() , 4 );
}
BOOST_AUTO_TEST_SUITE_END();
<|endoftext|>
|
<commit_before>// Copyright (c) 2018 PaddlePaddle 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 "paddle/fluid/inference/analysis/analyzer.h"
#include <gtest/gtest.h>
#include "paddle/fluid/framework/ir/fuse_pass_base.h"
#include "paddle/fluid/inference/analysis/ut_helper.h"
#include "paddle/fluid/inference/api/analysis_predictor.h"
#include "paddle/fluid/inference/api/helper.h"
#include "paddle/fluid/inference/api/paddle_inference_pass.h"
#include "paddle/fluid/platform/profiler.h"
DEFINE_string(infer_model, "", "model path");
DEFINE_string(infer_data, "", "data path");
DEFINE_int32(batch_size, 10, "batch size.");
DEFINE_int32(repeat, 1, "Running the inference program repeat times.");
DEFINE_bool(test_all_data, false, "Test the all dataset in data file.");
namespace paddle {
namespace inference {
struct DataRecord {
std::vector<std::vector<int64_t>> word_data_all, mention_data_all;
std::vector<std::vector<int64_t>> rnn_word_datas, rnn_mention_datas;
std::vector<size_t> lod; // two inputs have the same lod info.
size_t batch_iter{0};
size_t batch_size{1};
size_t num_samples; // total number of samples
DataRecord() = default;
explicit DataRecord(const std::string &path, int batch_size = 1)
: batch_size(batch_size) {
Load(path);
}
DataRecord NextBatch() {
DataRecord data;
size_t batch_end = batch_iter + batch_size;
// NOTE skip the final batch, if no enough data is provided.
if (batch_end <= word_data_all.size()) {
data.word_data_all.assign(word_data_all.begin() + batch_iter,
word_data_all.begin() + batch_end);
data.mention_data_all.assign(mention_data_all.begin() + batch_iter,
mention_data_all.begin() + batch_end);
// Prepare LoDs
data.lod.push_back(0);
CHECK(!data.word_data_all.empty());
CHECK(!data.mention_data_all.empty());
CHECK_EQ(data.word_data_all.size(), data.mention_data_all.size());
for (size_t j = 0; j < data.word_data_all.size(); j++) {
data.rnn_word_datas.push_back(data.word_data_all[j]);
data.rnn_mention_datas.push_back(data.mention_data_all[j]);
// calculate lod
data.lod.push_back(data.lod.back() + data.word_data_all[j].size());
}
}
batch_iter += batch_size;
return data;
}
void Load(const std::string &path) {
std::ifstream file(path);
std::string line;
int num_lines = 0;
while (std::getline(file, line)) {
num_lines++;
std::vector<std::string> data;
split(line, ';', &data);
// load word data
std::vector<int64_t> word_data;
split_to_int64(data[1], ' ', &word_data);
// load mention data
std::vector<int64_t> mention_data;
split_to_int64(data[3], ' ', &mention_data);
word_data_all.push_back(std::move(word_data));
mention_data_all.push_back(std::move(mention_data));
}
num_samples = num_lines;
}
};
void PrepareInputs(std::vector<PaddleTensor> *input_slots, DataRecord *data,
int batch_size) {
PaddleTensor lod_word_tensor, lod_mention_tensor;
lod_word_tensor.name = "word";
lod_mention_tensor.name = "mention";
auto one_batch = data->NextBatch();
int size = one_batch.lod[one_batch.lod.size() - 1]; // token batch size
lod_word_tensor.shape.assign({size, 1});
lod_word_tensor.lod.assign({one_batch.lod});
lod_mention_tensor.shape.assign({size, 1});
lod_mention_tensor.lod.assign({one_batch.lod});
// assign data
TensorAssignData<int64_t>(&lod_word_tensor, one_batch.rnn_word_datas);
TensorAssignData<int64_t>(&lod_mention_tensor, one_batch.rnn_mention_datas);
// Set inputs.
input_slots->assign({lod_word_tensor, lod_mention_tensor});
for (auto &tensor : *input_slots) {
tensor.dtype = PaddleDType::INT64;
}
}
// the first inference result
const int chinese_ner_result_data[] = {30, 45, 41, 48, 17, 26,
48, 39, 38, 16, 25};
void TestChineseNERPrediction(bool use_analysis) {
NativeConfig config;
config.prog_file = FLAGS_infer_model + "/__model__";
config.param_file = FLAGS_infer_model + "/param";
config.use_gpu = false;
config.device = 0;
config.specify_input_name = true;
std::vector<PaddleTensor> input_slots, outputs;
std::unique_ptr<PaddlePredictor> predictor;
Timer timer;
if (use_analysis) {
AnalysisConfig cfg;
cfg.prog_file = FLAGS_infer_model + "/__model__";
cfg.param_file = FLAGS_infer_model + "/param";
cfg.use_gpu = false;
cfg.device = 0;
cfg.specify_input_name = true;
cfg.enable_ir_optim = true;
predictor =
CreatePaddlePredictor<AnalysisConfig, PaddleEngineKind::kAnalysis>(cfg);
} else {
predictor =
CreatePaddlePredictor<NativeConfig, PaddleEngineKind::kNative>(config);
}
if (FLAGS_test_all_data) {
LOG(INFO) << "test all data";
double sum = 0;
size_t num_samples;
for (int i = 0; i < FLAGS_repeat; i++) {
DataRecord data(FLAGS_infer_data, FLAGS_batch_size);
num_samples = data.num_samples;
for (size_t bid = 0; bid < num_samples; ++bid) {
PrepareInputs(&input_slots, &data, FLAGS_batch_size);
timer.tic();
predictor->Run(input_slots, &outputs);
sum += timer.toc();
}
}
LOG(INFO) << "total number of samples: " << num_samples;
PrintTime(FLAGS_batch_size, FLAGS_repeat, 1, 0, sum / FLAGS_repeat);
LOG(INFO) << "average latency of each sample: "
<< sum / FLAGS_repeat / num_samples;
return;
}
// Prepare inputs.
DataRecord data(FLAGS_infer_data, FLAGS_batch_size);
PrepareInputs(&input_slots, &data, FLAGS_batch_size);
timer.tic();
for (int i = 0; i < FLAGS_repeat; i++) {
predictor->Run(input_slots, &outputs);
}
PrintTime(FLAGS_batch_size, FLAGS_repeat, 1, 0, timer.toc() / FLAGS_repeat);
PADDLE_ENFORCE(outputs.size(), 1UL);
auto &out = outputs[0];
size_t size = std::accumulate(out.shape.begin(), out.shape.end(), 1,
[](int a, int b) { return a * b; });
PADDLE_ENFORCE_GT(size, 0);
int64_t *result = static_cast<int64_t *>(out.data.data());
for (size_t i = 0; i < std::min(11UL, size); i++) {
PADDLE_ENFORCE(result[i], chinese_ner_result_data[i]);
}
if (use_analysis) {
// run once for comparion as reference
auto ref_predictor =
CreatePaddlePredictor<NativeConfig, PaddleEngineKind::kNative>(config);
std::vector<PaddleTensor> ref_outputs_slots;
ref_predictor->Run(input_slots, &ref_outputs_slots);
EXPECT_EQ(ref_outputs_slots.size(), outputs.size());
auto &ref_out = ref_outputs_slots[0];
size_t ref_size =
std::accumulate(ref_out.shape.begin(), ref_out.shape.end(), 1,
[](int a, int b) { return a * b; });
EXPECT_EQ(size, ref_size);
int64_t *pdata_ref = static_cast<int64_t *>(ref_out.data.data());
for (size_t i = 0; i < size; ++i) {
EXPECT_EQ(pdata_ref[i], result[i]);
}
AnalysisPredictor *analysis_predictor =
dynamic_cast<AnalysisPredictor *>(predictor.get());
auto &fuse_statis = analysis_predictor->analysis_argument()
.Get<std::unordered_map<std::string, int>>(
framework::ir::kFuseStatisAttr);
for (auto &item : fuse_statis) {
LOG(INFO) << "fused " << item.first << " " << item.second;
}
int num_ops = 0;
for (auto &node :
analysis_predictor->analysis_argument().main_dfg->nodes.nodes()) {
if (node->IsFunction()) {
++num_ops;
}
}
LOG(INFO) << "has num ops: " << num_ops;
ASSERT_TRUE(fuse_statis.count("fc_fuse"));
ASSERT_TRUE(fuse_statis.count("fc_gru_fuse"));
EXPECT_EQ(fuse_statis.at("fc_fuse"), 1);
EXPECT_EQ(fuse_statis.at("fc_gru_fuse"), 2);
EXPECT_EQ(num_ops, 14);
}
}
TEST(Analyzer_Chinese_ner, native) { TestChineseNERPrediction(false); }
TEST(Analyzer_Chinese_ner, analysis) { TestChineseNERPrediction(true); }
} // namespace inference
} // namespace paddle
<commit_msg>fix ner_test when bs>1<commit_after>// Copyright (c) 2018 PaddlePaddle 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 "paddle/fluid/inference/analysis/analyzer.h"
#include <gtest/gtest.h>
#include "paddle/fluid/framework/ir/fuse_pass_base.h"
#include "paddle/fluid/inference/analysis/ut_helper.h"
#include "paddle/fluid/inference/api/analysis_predictor.h"
#include "paddle/fluid/inference/api/helper.h"
#include "paddle/fluid/inference/api/paddle_inference_pass.h"
#include "paddle/fluid/platform/profiler.h"
DEFINE_string(infer_model, "", "model path");
DEFINE_string(infer_data, "", "data path");
DEFINE_int32(batch_size, 10, "batch size.");
DEFINE_int32(repeat, 1, "Running the inference program repeat times.");
DEFINE_bool(test_all_data, false, "Test the all dataset in data file.");
namespace paddle {
namespace inference {
struct DataRecord {
std::vector<std::vector<int64_t>> word_data_all, mention_data_all;
std::vector<std::vector<int64_t>> rnn_word_datas, rnn_mention_datas;
std::vector<size_t> lod; // two inputs have the same lod info.
size_t batch_iter{0};
size_t batch_size{1};
size_t num_samples; // total number of samples
DataRecord() = default;
explicit DataRecord(const std::string &path, int batch_size = 1)
: batch_size(batch_size) {
Load(path);
}
DataRecord NextBatch() {
DataRecord data;
size_t batch_end = batch_iter + batch_size;
// NOTE skip the final batch, if no enough data is provided.
if (batch_end <= word_data_all.size()) {
data.word_data_all.assign(word_data_all.begin() + batch_iter,
word_data_all.begin() + batch_end);
data.mention_data_all.assign(mention_data_all.begin() + batch_iter,
mention_data_all.begin() + batch_end);
// Prepare LoDs
data.lod.push_back(0);
CHECK(!data.word_data_all.empty());
CHECK(!data.mention_data_all.empty());
CHECK_EQ(data.word_data_all.size(), data.mention_data_all.size());
for (size_t j = 0; j < data.word_data_all.size(); j++) {
data.rnn_word_datas.push_back(data.word_data_all[j]);
data.rnn_mention_datas.push_back(data.mention_data_all[j]);
// calculate lod
data.lod.push_back(data.lod.back() + data.word_data_all[j].size());
}
}
batch_iter += batch_size;
return data;
}
void Load(const std::string &path) {
std::ifstream file(path);
std::string line;
int num_lines = 0;
while (std::getline(file, line)) {
num_lines++;
std::vector<std::string> data;
split(line, ';', &data);
// load word data
std::vector<int64_t> word_data;
split_to_int64(data[1], ' ', &word_data);
// load mention data
std::vector<int64_t> mention_data;
split_to_int64(data[3], ' ', &mention_data);
word_data_all.push_back(std::move(word_data));
mention_data_all.push_back(std::move(mention_data));
}
num_samples = num_lines;
}
};
void PrepareInputs(std::vector<PaddleTensor> *input_slots, DataRecord *data,
int batch_size) {
PaddleTensor lod_word_tensor, lod_mention_tensor;
lod_word_tensor.name = "word";
lod_mention_tensor.name = "mention";
auto one_batch = data->NextBatch();
int size = one_batch.lod[one_batch.lod.size() - 1]; // token batch size
lod_word_tensor.shape.assign({size, 1});
lod_word_tensor.lod.assign({one_batch.lod});
lod_mention_tensor.shape.assign({size, 1});
lod_mention_tensor.lod.assign({one_batch.lod});
// assign data
TensorAssignData<int64_t>(&lod_word_tensor, one_batch.rnn_word_datas);
TensorAssignData<int64_t>(&lod_mention_tensor, one_batch.rnn_mention_datas);
// Set inputs.
input_slots->assign({lod_word_tensor, lod_mention_tensor});
for (auto &tensor : *input_slots) {
tensor.dtype = PaddleDType::INT64;
}
}
// the first inference result
const int chinese_ner_result_data[] = {30, 45, 41, 48, 17, 26,
48, 39, 38, 16, 25};
void TestChineseNERPrediction(bool use_analysis) {
NativeConfig config;
config.prog_file = FLAGS_infer_model + "/__model__";
config.param_file = FLAGS_infer_model + "/param";
config.use_gpu = false;
config.device = 0;
config.specify_input_name = true;
std::vector<PaddleTensor> input_slots, outputs;
std::unique_ptr<PaddlePredictor> predictor;
Timer timer;
if (use_analysis) {
AnalysisConfig cfg;
cfg.prog_file = FLAGS_infer_model + "/__model__";
cfg.param_file = FLAGS_infer_model + "/param";
cfg.use_gpu = false;
cfg.device = 0;
cfg.specify_input_name = true;
cfg.enable_ir_optim = true;
predictor =
CreatePaddlePredictor<AnalysisConfig, PaddleEngineKind::kAnalysis>(cfg);
} else {
predictor =
CreatePaddlePredictor<NativeConfig, PaddleEngineKind::kNative>(config);
}
if (FLAGS_test_all_data) {
LOG(INFO) << "test all data";
double sum = 0;
size_t num_samples;
for (int i = 0; i < FLAGS_repeat; i++) {
DataRecord data(FLAGS_infer_data, FLAGS_batch_size);
// Just one batch, the num_samples remains the same.
num_samples = data.num_samples;
for (size_t bid = 0; bid < num_samples / FLAGS_batch_size; ++bid) {
PrepareInputs(&input_slots, &data, FLAGS_batch_size);
timer.tic();
predictor->Run(input_slots, &outputs);
sum += timer.toc();
}
}
LOG(INFO) << "total number of samples: " << num_samples;
PrintTime(FLAGS_batch_size, FLAGS_repeat, 1, 0, sum / FLAGS_repeat);
LOG(INFO) << "average latency of each sample: "
<< sum / FLAGS_repeat / num_samples;
return;
}
// Prepare inputs.
DataRecord data(FLAGS_infer_data, FLAGS_batch_size);
PrepareInputs(&input_slots, &data, FLAGS_batch_size);
timer.tic();
for (int i = 0; i < FLAGS_repeat; i++) {
predictor->Run(input_slots, &outputs);
}
PrintTime(FLAGS_batch_size, FLAGS_repeat, 1, 0, timer.toc() / FLAGS_repeat);
PADDLE_ENFORCE(outputs.size(), 1UL);
auto &out = outputs[0];
size_t size = std::accumulate(out.shape.begin(), out.shape.end(), 1,
[](int a, int b) { return a * b; });
PADDLE_ENFORCE_GT(size, 0);
int64_t *result = static_cast<int64_t *>(out.data.data());
for (size_t i = 0; i < std::min(11UL, size); i++) {
PADDLE_ENFORCE(result[i], chinese_ner_result_data[i]);
}
if (use_analysis) {
// run once for comparion as reference
auto ref_predictor =
CreatePaddlePredictor<NativeConfig, PaddleEngineKind::kNative>(config);
std::vector<PaddleTensor> ref_outputs_slots;
ref_predictor->Run(input_slots, &ref_outputs_slots);
EXPECT_EQ(ref_outputs_slots.size(), outputs.size());
auto &ref_out = ref_outputs_slots[0];
size_t ref_size =
std::accumulate(ref_out.shape.begin(), ref_out.shape.end(), 1,
[](int a, int b) { return a * b; });
EXPECT_EQ(size, ref_size);
int64_t *pdata_ref = static_cast<int64_t *>(ref_out.data.data());
for (size_t i = 0; i < size; ++i) {
EXPECT_EQ(pdata_ref[i], result[i]);
}
AnalysisPredictor *analysis_predictor =
dynamic_cast<AnalysisPredictor *>(predictor.get());
auto &fuse_statis = analysis_predictor->analysis_argument()
.Get<std::unordered_map<std::string, int>>(
framework::ir::kFuseStatisAttr);
for (auto &item : fuse_statis) {
LOG(INFO) << "fused " << item.first << " " << item.second;
}
int num_ops = 0;
for (auto &node :
analysis_predictor->analysis_argument().main_dfg->nodes.nodes()) {
if (node->IsFunction()) {
++num_ops;
}
}
LOG(INFO) << "has num ops: " << num_ops;
ASSERT_TRUE(fuse_statis.count("fc_fuse"));
ASSERT_TRUE(fuse_statis.count("fc_gru_fuse"));
EXPECT_EQ(fuse_statis.at("fc_fuse"), 1);
EXPECT_EQ(fuse_statis.at("fc_gru_fuse"), 2);
EXPECT_EQ(num_ops, 14);
}
}
TEST(Analyzer_Chinese_ner, native) { TestChineseNERPrediction(false); }
TEST(Analyzer_Chinese_ner, analysis) { TestChineseNERPrediction(true); }
} // namespace inference
} // namespace paddle
<|endoftext|>
|
<commit_before>/*
kmsc - Kurento Media Server C/C++ implementation
Copyright (C) 2012 Tikal Technologies
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License version 3
as published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <MediaServerService.h>
#include <MediaSessionService.h>
#include <NetworkConnectionService.h>
#include <thrift/config.h>
#include <thrift/transport/TSocket.h>
// #include <thrift/transport/TBufferTransports.h>
#include <thrift/protocol/TBinaryProtocol.h>
// #include <thrift/protocol/TDebugProtocol.h>
#include <boost/concept_check.hpp>
#include <gst/gst.h>
#include <sstream>
using ::com::kurento::kms::api::MediaSessionServiceClient;
using ::com::kurento::kms::api::MediaServerServiceClient;
using ::com::kurento::kms::api::MediaSession;
using ::com::kurento::kms::api::ServerConfig;
using ::com::kurento::kms::api::NetworkConnection;
using ::com::kurento::kms::api::NetworkConnectionConfig;
using ::com::kurento::kms::api::NetworkConnectionServiceClient;
using ::com::kurento::kms::api::StreamType;
using ::com::kurento::mediaspec::SessionSpec;
using ::com::kurento::mediaspec::MediaSpec;
using ::com::kurento::mediaspec::Payload;
using ::com::kurento::mediaspec::Direction;
using ::com::kurento::mediaspec::MediaType;
using ::apache::thrift::protocol::TBinaryProtocol;
// using ::apache::thrift::protocol::TDebugProtocol;
using ::apache::thrift::transport::TSocket;
// using ::apache::thrift::transport::TMemoryBuffer;
#define DEFAULT_PORT 5050
#define LOCAL_ADDRESS "193.147.51.16"
static void
send_receive_media(SessionSpec &spec) {
MediaSpec media = *(spec.medias.begin());
Payload pay = *(media.payloads.begin());
std::stringstream stream;
if (media.direction == Direction::RECVONLY) {
std::cout << "server recvonly" << std::endl;
std::cout << "Port: " << media.transport.rtp.port << std::endl;
std::cout << "Codec name: " << pay.rtp.codecName << std::endl;
stream << "autovideosrc ! "
"video/x-raw-yuv,framerate=30/1,width=352 ! "
"xvidenc max-bquant=0 bquant-ratio=0 motion=0 ! "
"rtpmp4vpay config-interval=2 send-config=TRUE ! "
"application/x-rtp,media=video,clock-rate=(int)" <<
pay.rtp.clockRate << ",encoding-name=(string)MP4V-ES,"
"payload=(int)" << pay.rtp.id << " ! udpsink port=" <<
media.transport.rtp.port << " host=" <<
media.transport.rtp.address;
} else if (media.direction == Direction::SENDONLY) {
std::cout << "server sendonly" << std::endl;
std::cout << "Port: " << DEFAULT_PORT << std::endl;
std::cout << "Codec name: " << pay.rtp.codecName << std::endl;
stream << "udpsrc port=" << DEFAULT_PORT <<
" ! application/x-rtp,encoding-name=" <<
pay.rtp.codecName << ",clock-rate=" <<
pay.rtp.clockRate << ",payload=" <<
pay.rtp.id << " ! rtph264depay ! ffdec_h264 ! "
"autovideosink";
}
GstElement *pipe;
GError *err = NULL;
std::string pipe_str = stream.str();
std::cout << pipe_str << std::endl;
pipe = gst_parse_launch(pipe_str.c_str(), &err);
if (err != NULL) {
std::cout << "Error: " << err->message << std::endl;
g_error_free(err);
err = NULL;
} else if (pipe == NULL) {
std::cout << "Cannot create pipe" << std::endl;
} else {
gst_element_set_state(pipe, GST_STATE_PLAYING);
}
std::cout << "---" << std::endl;
}
static void
print_session_spec(SessionSpec &spec) {
// boost::shared_ptr<TMemoryBuffer> buffer(new TMemoryBuffer());
// TDebugProtocol proto(buffer);
// spec.write(&proto);
//
// std::cout << buffer->getBufferAsString() << std::endl;
}
static void
create_session_spec(SessionSpec &spec) {
Payload pay;
pay.__isset.rtp = true;
pay.rtp.codecName = "H264";
pay.rtp.id = 96;
pay.rtp.clockRate = 90000;
MediaSpec ms;
ms.transport.rtp.address = LOCAL_ADDRESS;
ms.transport.rtp.port = DEFAULT_PORT;
ms.transport.__isset.rtp = true;
ms.direction = Direction::type::RECVONLY;
ms.type.insert(MediaType::VIDEO);
ms.payloads.push_back(pay);
spec.id = "1234";
spec.medias.push_back(ms);
}
static void
create_second_session_spec(SessionSpec &spec) {
Payload pay;
pay.__isset.rtp = true;
pay.rtp.codecName = "MP4V-ES";
pay.rtp.id = 96;
pay.rtp.clockRate = 90000;
MediaSpec ms;
ms.transport.rtp.address = LOCAL_ADDRESS;
ms.transport.rtp.port = DEFAULT_PORT;
ms.transport.__isset.rtp = true;
ms.direction = Direction::type::SENDONLY;
ms.type.insert(MediaType::VIDEO);
ms.payloads.push_back(pay);
spec.id = "1234";
spec.medias.push_back(ms);
}
static void
create_newtork_connection(NetworkConnection &_nc, ServerConfig &mc, MediaSession &ms) {
if (!mc.__isset.mediaSessionServicePort)
return;
boost::shared_ptr<TSocket> transport(new TSocket(mc.address,
mc.mediaSessionServicePort));
boost::shared_ptr<TBinaryProtocol> prot(new TBinaryProtocol(transport));
MediaSessionServiceClient mservice(prot);
transport->open();
std::vector<NetworkConnectionConfig::type> config;
config.push_back(NetworkConnectionConfig::type::RTP);
mservice.createNetworkConnection(_nc, ms, config);
}
static void
negotiate_connection(ServerConfig &mc, NetworkConnection& nc, SessionSpec& spec) {
if (!mc.__isset.networkConnectionServicePort)
return;
boost::shared_ptr<TSocket> transport(new TSocket(mc.address,
mc.networkConnectionServicePort));
boost::shared_ptr<TBinaryProtocol> prot(new TBinaryProtocol(transport));
NetworkConnectionServiceClient service(prot);
transport->open();
SessionSpec reply;
service.processOffer(reply, nc, spec);
print_session_spec(reply);
send_receive_media(reply);
}
static void
join_network_connections(ServerConfig &mc, NetworkConnection& nc,
NetworkConnection& nc2) {
if (!mc.__isset.networkConnectionServicePort)
return;
boost::shared_ptr<TSocket> transport(new TSocket(mc.address,
mc.networkConnectionServicePort));
boost::shared_ptr<TBinaryProtocol> prot(new TBinaryProtocol(transport));
NetworkConnectionServiceClient service(prot);
transport->open();
service.joinStream(nc.joinable, nc2.joinable, StreamType::type::VIDEO,
Direction::RECVONLY);
}
static void
ping_media_session(ServerConfig &mc, MediaSession& ms, int iter, int interval) {
if (!mc.__isset.mediaSessionServicePort)
return;
boost::shared_ptr<TSocket> transport(new TSocket(mc.address,
mc.mediaSessionServicePort));
boost::shared_ptr<TBinaryProtocol> prot(new TBinaryProtocol(transport));
MediaSessionServiceClient service(prot);
transport->open();
for (; iter > 0; iter--) {
service.ping(ms, interval + 1);
sleep(interval);
}
}
static void
start_client() {
boost::shared_ptr<TSocket> transport(new TSocket("localhost", 9090));
boost::shared_ptr<TBinaryProtocol> prot(new TBinaryProtocol(transport));
MediaServerServiceClient mservice(prot);
transport->open();
ServerConfig mc;
MediaSession ms;
NetworkConnection nc, nc2;
SessionSpec spec;
SessionSpec spec2;
mservice.getServerconfig(mc);
mservice.createMediaSession(ms);
std::cout << "Session id: " << ms.object.id << std::endl;
create_newtork_connection(nc, mc, ms);
std::cout << "NetworkConnection: " << nc.joinable.object.id << std::endl;
create_session_spec(spec);
negotiate_connection(mc, nc, spec);
create_newtork_connection(nc2, mc, ms);
std::cout << "NetworkConnection: " << nc2.joinable.object.id << std::endl;
create_second_session_spec(spec2);
negotiate_connection(mc, nc2, spec2);
join_network_connections(mc, nc, nc2);
ping_media_session(mc, ms, 4, 30);
mservice.deleteMediaSession(ms);
}
int
main(int argc, char **argv) {
gst_init(&argc, &argv);
// TODO: Evaluate if server should be launched here
start_client();
}<commit_msg>Fix test to work with localhost<commit_after>/*
kmsc - Kurento Media Server C/C++ implementation
Copyright (C) 2012 Tikal Technologies
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License version 3
as published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <MediaServerService.h>
#include <MediaSessionService.h>
#include <NetworkConnectionService.h>
#include <thrift/config.h>
#include <thrift/transport/TSocket.h>
// #include <thrift/transport/TBufferTransports.h>
#include <thrift/protocol/TBinaryProtocol.h>
// #include <thrift/protocol/TDebugProtocol.h>
#include <boost/concept_check.hpp>
#include <gst/gst.h>
#include <sstream>
using ::com::kurento::kms::api::MediaSessionServiceClient;
using ::com::kurento::kms::api::MediaServerServiceClient;
using ::com::kurento::kms::api::MediaSession;
using ::com::kurento::kms::api::ServerConfig;
using ::com::kurento::kms::api::NetworkConnection;
using ::com::kurento::kms::api::NetworkConnectionConfig;
using ::com::kurento::kms::api::NetworkConnectionServiceClient;
using ::com::kurento::kms::api::StreamType;
using ::com::kurento::mediaspec::SessionSpec;
using ::com::kurento::mediaspec::MediaSpec;
using ::com::kurento::mediaspec::Payload;
using ::com::kurento::mediaspec::Direction;
using ::com::kurento::mediaspec::MediaType;
using ::apache::thrift::protocol::TBinaryProtocol;
// using ::apache::thrift::protocol::TDebugProtocol;
using ::apache::thrift::transport::TSocket;
// using ::apache::thrift::transport::TMemoryBuffer;
#define DEFAULT_PORT 5050
#define LOCAL_ADDRESS "127.0.0.1"
static void
send_receive_media(SessionSpec &spec) {
MediaSpec media = *(spec.medias.begin());
Payload pay = *(media.payloads.begin());
std::stringstream stream;
if (media.direction == Direction::RECVONLY) {
std::cout << "server recvonly" << std::endl;
std::cout << "Port: " << media.transport.rtp.port << std::endl;
std::cout << "Codec name: " << pay.rtp.codecName << std::endl;
stream << "autovideosrc ! "
"video/x-raw-yuv,framerate=30/1,width=352 ! "
"xvidenc max-bquant=0 bquant-ratio=0 motion=0 ! "
"rtpmp4vpay config-interval=2 send-config=TRUE ! "
"application/x-rtp,media=video,clock-rate=(int)" <<
pay.rtp.clockRate << ",encoding-name=(string)MP4V-ES,"
"payload=(int)" << pay.rtp.id << " ! udpsink port=" <<
media.transport.rtp.port << " host=" <<
media.transport.rtp.address;
} else if (media.direction == Direction::SENDONLY) {
std::cout << "server sendonly" << std::endl;
std::cout << "Port: " << DEFAULT_PORT << std::endl;
std::cout << "Codec name: " << pay.rtp.codecName << std::endl;
stream << "udpsrc port=" << DEFAULT_PORT <<
" ! application/x-rtp,encoding-name=" <<
pay.rtp.codecName << ",clock-rate=" <<
pay.rtp.clockRate << ",payload=" <<
pay.rtp.id << " ! rtph264depay ! ffdec_h264 ! "
"autovideosink";
}
GstElement *pipe;
GError *err = NULL;
std::string pipe_str = stream.str();
std::cout << pipe_str << std::endl;
pipe = gst_parse_launch(pipe_str.c_str(), &err);
if (err != NULL) {
std::cout << "Error: " << err->message << std::endl;
g_error_free(err);
err = NULL;
} else if (pipe == NULL) {
std::cout << "Cannot create pipe" << std::endl;
} else {
gst_element_set_state(pipe, GST_STATE_PLAYING);
}
std::cout << "---" << std::endl;
}
static void
print_session_spec(SessionSpec &spec) {
// boost::shared_ptr<TMemoryBuffer> buffer(new TMemoryBuffer());
// TDebugProtocol proto(buffer);
// spec.write(&proto);
//
// std::cout << buffer->getBufferAsString() << std::endl;
}
static void
create_session_spec(SessionSpec &spec) {
Payload pay;
pay.__isset.rtp = true;
pay.rtp.codecName = "H264";
pay.rtp.id = 96;
pay.rtp.clockRate = 90000;
MediaSpec ms;
ms.transport.rtp.address = LOCAL_ADDRESS;
ms.transport.rtp.port = DEFAULT_PORT;
ms.transport.__isset.rtp = true;
ms.direction = Direction::type::RECVONLY;
ms.type.insert(MediaType::VIDEO);
ms.payloads.push_back(pay);
spec.id = "1234";
spec.medias.push_back(ms);
}
static void
create_second_session_spec(SessionSpec &spec) {
Payload pay;
pay.__isset.rtp = true;
pay.rtp.codecName = "MP4V-ES";
pay.rtp.id = 96;
pay.rtp.clockRate = 90000;
MediaSpec ms;
ms.transport.rtp.address = LOCAL_ADDRESS;
ms.transport.rtp.port = DEFAULT_PORT;
ms.transport.__isset.rtp = true;
ms.direction = Direction::type::SENDONLY;
ms.type.insert(MediaType::VIDEO);
ms.payloads.push_back(pay);
spec.id = "1234";
spec.medias.push_back(ms);
}
static void
create_newtork_connection(NetworkConnection &_nc, ServerConfig &mc, MediaSession &ms) {
if (!mc.__isset.mediaSessionServicePort)
return;
boost::shared_ptr<TSocket> transport(new TSocket(mc.address,
mc.mediaSessionServicePort));
boost::shared_ptr<TBinaryProtocol> prot(new TBinaryProtocol(transport));
MediaSessionServiceClient mservice(prot);
transport->open();
std::vector<NetworkConnectionConfig::type> config;
config.push_back(NetworkConnectionConfig::type::RTP);
mservice.createNetworkConnection(_nc, ms, config);
}
static void
negotiate_connection(ServerConfig &mc, NetworkConnection& nc, SessionSpec& spec) {
if (!mc.__isset.networkConnectionServicePort)
return;
boost::shared_ptr<TSocket> transport(new TSocket(mc.address,
mc.networkConnectionServicePort));
boost::shared_ptr<TBinaryProtocol> prot(new TBinaryProtocol(transport));
NetworkConnectionServiceClient service(prot);
transport->open();
SessionSpec reply;
service.processOffer(reply, nc, spec);
print_session_spec(reply);
send_receive_media(reply);
}
static void
join_network_connections(ServerConfig &mc, NetworkConnection& nc,
NetworkConnection& nc2) {
if (!mc.__isset.networkConnectionServicePort)
return;
boost::shared_ptr<TSocket> transport(new TSocket(mc.address,
mc.networkConnectionServicePort));
boost::shared_ptr<TBinaryProtocol> prot(new TBinaryProtocol(transport));
NetworkConnectionServiceClient service(prot);
transport->open();
service.joinStream(nc.joinable, nc2.joinable, StreamType::type::VIDEO,
Direction::RECVONLY);
}
static void
ping_media_session(ServerConfig &mc, MediaSession& ms, int iter, int interval) {
if (!mc.__isset.mediaSessionServicePort)
return;
boost::shared_ptr<TSocket> transport(new TSocket(mc.address,
mc.mediaSessionServicePort));
boost::shared_ptr<TBinaryProtocol> prot(new TBinaryProtocol(transport));
MediaSessionServiceClient service(prot);
transport->open();
for (; iter > 0; iter--) {
service.ping(ms, interval + 1);
sleep(interval);
}
}
static void
start_client() {
boost::shared_ptr<TSocket> transport(new TSocket("localhost", 9090));
boost::shared_ptr<TBinaryProtocol> prot(new TBinaryProtocol(transport));
MediaServerServiceClient mservice(prot);
transport->open();
ServerConfig mc;
MediaSession ms;
NetworkConnection nc, nc2;
SessionSpec spec;
SessionSpec spec2;
mservice.getServerconfig(mc);
mservice.createMediaSession(ms);
std::cout << "Session id: " << ms.object.id << std::endl;
create_newtork_connection(nc, mc, ms);
std::cout << "NetworkConnection: " << nc.joinable.object.id << std::endl;
create_session_spec(spec);
negotiate_connection(mc, nc, spec);
create_newtork_connection(nc2, mc, ms);
std::cout << "NetworkConnection: " << nc2.joinable.object.id << std::endl;
create_second_session_spec(spec2);
negotiate_connection(mc, nc2, spec2);
join_network_connections(mc, nc, nc2);
ping_media_session(mc, ms, 4, 30);
mservice.deleteMediaSession(ms);
}
int
main(int argc, char **argv) {
gst_init(&argc, &argv);
// TODO: Evaluate if server should be launched here
start_client();
}<|endoftext|>
|
<commit_before>/***************************************************************************
* Copyright (c) 2016, Johan Mabille, Sylvain Corlay and Wolf Vollprecht *
* *
* Distributed under the terms of the BSD 3-Clause License. *
* *
* The full license is in the file LICENSE, distributed with this software. *
****************************************************************************/
#include "gtest/gtest.h"
#include "xtensor/xbroadcast.hpp"
#include "xtensor/xarray.hpp"
#include "xtensor/xstrides.hpp"
#include "xtensor/xarray.hpp"
#include "xtensor/xtensor.hpp"
#include "xtensor/xfixed.hpp"
#include "xtensor/xshape.hpp"
namespace xt
{
using vector_type = svector<std::size_t, 4>;
TEST(svector, behavior)
{
vector_type s = {1,2,3,4};
vector_type s2 = s;
std::vector<std::size_t> v(s.begin(), s.end());
std::vector<std::size_t> v2 = {1,2,3,4};
EXPECT_TRUE(std::equal(s.begin(), s.end(), v.begin()));
EXPECT_TRUE(std::equal(s2.begin(), s2.end(), v2.begin()));
s.erase(s.begin(), s.begin() + 2);
v.erase(v.begin(), v.begin() + 2);
EXPECT_TRUE(std::equal(s.begin(), s.end(), v.begin()));
s2.erase(s2.begin() + 1, s2.end());
v2.erase(v2.begin() + 1, v2.end());
EXPECT_TRUE(std::equal(s2.begin(), s2.end(), v2.begin()));
EXPECT_TRUE(s2.on_stack());
s2.push_back(10);
s2.push_back(20);
s2.push_back(30);
s2.push_back(40);
v2.push_back(10);
v2.push_back(20);
v2.push_back(30);
v2.push_back(40);
EXPECT_FALSE(s2.on_stack());
EXPECT_TRUE(std::equal(s2.begin(), s2.end(), v2.begin()));
}
TEST(svector, insert)
{
vector_type s = {1,2,3,4};
vector_type s2 = s;
std::vector<std::size_t> v(s.begin(), s.end());
std::vector<std::size_t> v2 = {1,2,3,4};
s.insert(s.begin(), std::size_t(55));
s.insert(s.begin() + 2, std::size_t(123));
v.insert(v.begin(), std::size_t(55));
v.insert(v.begin() + 2, std::size_t(123));
std::size_t nr = 12321;
s.insert(s.end(), nr);
v.insert(v.end(), nr);
EXPECT_TRUE(std::equal(s.begin(), s.end(), v.begin()));
}
TEST(svector, constructor)
{
vector_type a;
EXPECT_EQ(size_t(0), a.size());
vector_type b(10);
EXPECT_EQ(size_t(10), b.size());
vector_type c(10, 2);
EXPECT_EQ(size_t(10), c.size());
EXPECT_EQ(size_t(2), c[2]);
std::vector<std::size_t> src(10, std::size_t(1));
vector_type d(src.cbegin(), src.cend());
EXPECT_EQ(size_t(10), d.size());
EXPECT_EQ(size_t(1), d[2]);
vector_type e(src);
EXPECT_EQ(size_t(10), d.size());
EXPECT_EQ(size_t(1), d[2]);
vector_type f = { 1, 2, 3, 4 };
EXPECT_EQ(size_t(4), f.size());
EXPECT_EQ(size_t(3), f[2]);
svector<std::size_t, 8> ov = { 1, 2, 3, 4, 5, 6, 7, 8 };
vector_type g(ov);
EXPECT_EQ(size_t(8), g.size());
EXPECT_EQ(size_t(3), g[2]);
}
TEST(svector, assign)
{
vector_type a = { 1, 2, 3, 4 };
vector_type src1(10, 2);
a = src1;
EXPECT_EQ(size_t(10), a.size());
EXPECT_EQ(size_t(2), a[2]);
std::vector<size_t> src2(5, 1);
a = src2;
EXPECT_EQ(size_t(5), a.size());
EXPECT_EQ(size_t(1), a[2]);
a = { 1, 2, 3, 4 };
EXPECT_EQ(size_t(4), a.size());
EXPECT_EQ(size_t(3), a[2]);
svector<std::size_t, 4> src3(10, 1);
a = src3;
EXPECT_EQ(size_t(10), a.size());
EXPECT_EQ(size_t(1), a[2]);
}
TEST(svector, resize)
{
vector_type a;
for (size_t i = 1; i < 11; ++i)
{
size_t size1 = i * 10;
a.resize(size1);
EXPECT_EQ(size1, a.size());
size_t size2 = size1 - 5;
a.resize(size2);
EXPECT_EQ(size2, a.size());
}
vector_type b = { 1, 3, 4 };
b.resize(6);
EXPECT_EQ(b[0], 1u);
EXPECT_EQ(b[1], 3u);
EXPECT_EQ(b[2], 4u);
}
TEST(svector, swap)
{
using std::swap;
{
vector_type a = { 1, 3, 4, 6, 7 };
vector_type b = {};
vector_type abu = a;
vector_type bbu = b;
swap(a, b);
EXPECT_EQ(a, bbu);
EXPECT_EQ(b, abu);
}
{
vector_type a = { 1, 3 ,4 };
vector_type b = { 2, 1, 5, 3, 9, 12 };
vector_type abu = a;
vector_type bbu = b;
swap(a, b);
EXPECT_EQ(a, bbu);
EXPECT_EQ(b, abu);
}
{
vector_type a = { 10, 13, 14 };
vector_type b = { 12, 15, 17 };
vector_type abu = a;
vector_type bbu = b;
swap(a, b);
EXPECT_EQ(a, bbu);
EXPECT_EQ(b, abu);
}
}
TEST(svector, access)
{
vector_type a(10);
a[0] = size_t(1);
EXPECT_EQ(size_t(1), a[0]);
a[3] = size_t(3);
EXPECT_EQ(size_t(3), a[3]);
a[5] = size_t(2);
EXPECT_EQ(size_t(2), a[5]);
a.front() = size_t(0);
EXPECT_EQ(size_t(0), a[0]);
a.back() = size_t(1);
EXPECT_EQ(size_t(1), a[9]);
EXPECT_EQ(a.at(5), size_t(2));
EXPECT_ANY_THROW(a.at(12));
}
TEST(svector, iterator)
{
vector_type a(10);
std::iota(a.begin(), a.end(), std::size_t(0));
for (size_t i = 0; i < a.size(); ++i)
{
EXPECT_EQ(i, a[i]);
}
}
TEST(xshape, fixed)
{
fixed_shape<3, 4, 5> af;
using cast_type = typename fixed_shape<3, 4, 5>::cast_type;
cast_type a = af;
EXPECT_EQ(a[0], size_t(3));
EXPECT_EQ(a[2], size_t(5));
EXPECT_EQ(a.back(), size_t(5));
EXPECT_EQ(a.front(), size_t(3));
EXPECT_EQ(a.size(), size_t(3));
}
TEST(xshape, common_tensor_deduction) {
xt::xarray<double> a1;
xt::xtensor<double, 1> a2;
xt::xtensor_fixed<double, xt::xshape<1>> a3;
EXPECT_TRUE((std::is_same<xt::common_tensor_t<decltype(a1), decltype(a1)>, decltype(a1)>::value));
EXPECT_TRUE((std::is_same<xt::common_tensor_t<decltype(a2), decltype(a2)>, decltype(a2)>::value));
EXPECT_TRUE((std::is_same<xt::common_tensor_t<decltype(a3), decltype(a3)>, decltype(a3)>::value));
EXPECT_TRUE((std::is_same<xt::common_tensor_t<decltype(a1), decltype(a2)>, decltype(a1)>::value));
EXPECT_TRUE((std::is_same<xt::common_tensor_t<decltype(a1), decltype(a3)>, decltype(a1)>::value));
EXPECT_TRUE((std::is_same<xt::common_tensor_t<decltype(a2), decltype(a3)>, decltype(a2)>::value));
}
}
<commit_msg>Added xfunction and 2D tests<commit_after>/***************************************************************************
* Copyright (c) 2016, Johan Mabille, Sylvain Corlay and Wolf Vollprecht *
* *
* Distributed under the terms of the BSD 3-Clause License. *
* *
* The full license is in the file LICENSE, distributed with this software. *
****************************************************************************/
#include "gtest/gtest.h"
#include "xtensor/xbroadcast.hpp"
#include "xtensor/xarray.hpp"
#include "xtensor/xstrides.hpp"
#include "xtensor/xarray.hpp"
#include "xtensor/xtensor.hpp"
#include "xtensor/xfixed.hpp"
#include "xtensor/xshape.hpp"
namespace xt
{
using vector_type = svector<std::size_t, 4>;
TEST(svector, behavior)
{
vector_type s = {1,2,3,4};
vector_type s2 = s;
std::vector<std::size_t> v(s.begin(), s.end());
std::vector<std::size_t> v2 = {1,2,3,4};
EXPECT_TRUE(std::equal(s.begin(), s.end(), v.begin()));
EXPECT_TRUE(std::equal(s2.begin(), s2.end(), v2.begin()));
s.erase(s.begin(), s.begin() + 2);
v.erase(v.begin(), v.begin() + 2);
EXPECT_TRUE(std::equal(s.begin(), s.end(), v.begin()));
s2.erase(s2.begin() + 1, s2.end());
v2.erase(v2.begin() + 1, v2.end());
EXPECT_TRUE(std::equal(s2.begin(), s2.end(), v2.begin()));
EXPECT_TRUE(s2.on_stack());
s2.push_back(10);
s2.push_back(20);
s2.push_back(30);
s2.push_back(40);
v2.push_back(10);
v2.push_back(20);
v2.push_back(30);
v2.push_back(40);
EXPECT_FALSE(s2.on_stack());
EXPECT_TRUE(std::equal(s2.begin(), s2.end(), v2.begin()));
}
TEST(svector, insert)
{
vector_type s = {1,2,3,4};
vector_type s2 = s;
std::vector<std::size_t> v(s.begin(), s.end());
std::vector<std::size_t> v2 = {1,2,3,4};
s.insert(s.begin(), std::size_t(55));
s.insert(s.begin() + 2, std::size_t(123));
v.insert(v.begin(), std::size_t(55));
v.insert(v.begin() + 2, std::size_t(123));
std::size_t nr = 12321;
s.insert(s.end(), nr);
v.insert(v.end(), nr);
EXPECT_TRUE(std::equal(s.begin(), s.end(), v.begin()));
}
TEST(svector, constructor)
{
vector_type a;
EXPECT_EQ(size_t(0), a.size());
vector_type b(10);
EXPECT_EQ(size_t(10), b.size());
vector_type c(10, 2);
EXPECT_EQ(size_t(10), c.size());
EXPECT_EQ(size_t(2), c[2]);
std::vector<std::size_t> src(10, std::size_t(1));
vector_type d(src.cbegin(), src.cend());
EXPECT_EQ(size_t(10), d.size());
EXPECT_EQ(size_t(1), d[2]);
vector_type e(src);
EXPECT_EQ(size_t(10), d.size());
EXPECT_EQ(size_t(1), d[2]);
vector_type f = { 1, 2, 3, 4 };
EXPECT_EQ(size_t(4), f.size());
EXPECT_EQ(size_t(3), f[2]);
svector<std::size_t, 8> ov = { 1, 2, 3, 4, 5, 6, 7, 8 };
vector_type g(ov);
EXPECT_EQ(size_t(8), g.size());
EXPECT_EQ(size_t(3), g[2]);
}
TEST(svector, assign)
{
vector_type a = { 1, 2, 3, 4 };
vector_type src1(10, 2);
a = src1;
EXPECT_EQ(size_t(10), a.size());
EXPECT_EQ(size_t(2), a[2]);
std::vector<size_t> src2(5, 1);
a = src2;
EXPECT_EQ(size_t(5), a.size());
EXPECT_EQ(size_t(1), a[2]);
a = { 1, 2, 3, 4 };
EXPECT_EQ(size_t(4), a.size());
EXPECT_EQ(size_t(3), a[2]);
svector<std::size_t, 4> src3(10, 1);
a = src3;
EXPECT_EQ(size_t(10), a.size());
EXPECT_EQ(size_t(1), a[2]);
}
TEST(svector, resize)
{
vector_type a;
for (size_t i = 1; i < 11; ++i)
{
size_t size1 = i * 10;
a.resize(size1);
EXPECT_EQ(size1, a.size());
size_t size2 = size1 - 5;
a.resize(size2);
EXPECT_EQ(size2, a.size());
}
vector_type b = { 1, 3, 4 };
b.resize(6);
EXPECT_EQ(b[0], 1u);
EXPECT_EQ(b[1], 3u);
EXPECT_EQ(b[2], 4u);
}
TEST(svector, swap)
{
using std::swap;
{
vector_type a = { 1, 3, 4, 6, 7 };
vector_type b = {};
vector_type abu = a;
vector_type bbu = b;
swap(a, b);
EXPECT_EQ(a, bbu);
EXPECT_EQ(b, abu);
}
{
vector_type a = { 1, 3 ,4 };
vector_type b = { 2, 1, 5, 3, 9, 12 };
vector_type abu = a;
vector_type bbu = b;
swap(a, b);
EXPECT_EQ(a, bbu);
EXPECT_EQ(b, abu);
}
{
vector_type a = { 10, 13, 14 };
vector_type b = { 12, 15, 17 };
vector_type abu = a;
vector_type bbu = b;
swap(a, b);
EXPECT_EQ(a, bbu);
EXPECT_EQ(b, abu);
}
}
TEST(svector, access)
{
vector_type a(10);
a[0] = size_t(1);
EXPECT_EQ(size_t(1), a[0]);
a[3] = size_t(3);
EXPECT_EQ(size_t(3), a[3]);
a[5] = size_t(2);
EXPECT_EQ(size_t(2), a[5]);
a.front() = size_t(0);
EXPECT_EQ(size_t(0), a[0]);
a.back() = size_t(1);
EXPECT_EQ(size_t(1), a[9]);
EXPECT_EQ(a.at(5), size_t(2));
EXPECT_ANY_THROW(a.at(12));
}
TEST(svector, iterator)
{
vector_type a(10);
std::iota(a.begin(), a.end(), std::size_t(0));
for (size_t i = 0; i < a.size(); ++i)
{
EXPECT_EQ(i, a[i]);
}
}
TEST(xshape, fixed)
{
fixed_shape<3, 4, 5> af;
using cast_type = typename fixed_shape<3, 4, 5>::cast_type;
cast_type a = af;
EXPECT_EQ(a[0], size_t(3));
EXPECT_EQ(a[2], size_t(5));
EXPECT_EQ(a.back(), size_t(5));
EXPECT_EQ(a.front(), size_t(3));
EXPECT_EQ(a.size(), size_t(3));
}
TEST(xshape, common_tensor_deduction) {
xt::xarray<double> a1 {0.0, 0.0, 0.0};
xt::xtensor<double, 1> a2 {0.0, 0.0, 0.0};
xt::xtensor_fixed<double, xt::xshape<3>> a3({0.0, 0.0, 0.0});
EXPECT_TRUE((std::is_same<xt::common_tensor_t<decltype(a1), decltype(a1)>, decltype(a1)>::value));
EXPECT_TRUE((std::is_same<xt::common_tensor_t<decltype(a2), decltype(a2)>, decltype(a2)>::value));
EXPECT_TRUE((std::is_same<xt::common_tensor_t<decltype(a3), decltype(a3)>, decltype(a3)>::value));
EXPECT_TRUE((std::is_same<xt::common_tensor_t<decltype(a1), decltype(a2)>, decltype(a1)>::value));
EXPECT_TRUE((std::is_same<xt::common_tensor_t<decltype(a1), decltype(a3)>, decltype(a1)>::value));
EXPECT_TRUE((std::is_same<xt::common_tensor_t<decltype(a2), decltype(a3)>, decltype(a2)>::value));
auto sum1 = a1 + a2;
EXPECT_TRUE((std::is_same<xt::common_tensor_t<decltype(a1), decltype(sum1)>, decltype(a1)>::value));
auto sum2 = a1 + a3;
EXPECT_TRUE((std::is_same<xt::common_tensor_t<decltype(a1), decltype(sum2)>, decltype(a1)>::value));
auto sum3 = a2 + a3;
EXPECT_TRUE((std::is_same<xt::common_tensor_t<decltype(a2), decltype(sum3)>, decltype(a2)>::value));
xt::xarray<double> b1 {{0.0, 0.0, 0.0},{0.0, 0.0, 0.0},{0.0, 0.0, 0.0}};
xt::xtensor<double, 2> b2 {{0.0, 0.0, 0.0},{0.0, 0.0, 0.0},{0.0, 0.0, 0.0}};
xt::xtensor_fixed<double, xt::xshape<3,3>> b3({{0.0, 0.0, 0.0},{0.0, 0.0, 0.0},{0.0, 0.0, 0.0}});
EXPECT_TRUE((std::is_same<xt::common_tensor_t<decltype(b1), decltype(b1)>, decltype(b1)>::value));
EXPECT_TRUE((std::is_same<xt::common_tensor_t<decltype(b2), decltype(b2)>, decltype(b2)>::value));
EXPECT_TRUE((std::is_same<xt::common_tensor_t<decltype(b3), decltype(b3)>, decltype(b3)>::value));
EXPECT_TRUE((std::is_same<xt::common_tensor_t<decltype(b1), decltype(b2)>, decltype(b1)>::value));
EXPECT_TRUE((std::is_same<xt::common_tensor_t<decltype(b1), decltype(b3)>, decltype(b1)>::value));
EXPECT_TRUE((std::is_same<xt::common_tensor_t<decltype(b2), decltype(b3)>, decltype(b2)>::value));
}
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: SlsViewOverlay.cxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: obo $ $Date: 2006-09-16 19:11:43 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sd.hxx"
#include "view/SlsViewOverlay.hxx"
#include "controller/SlideSorterController.hxx"
#include "model/SlideSorterModel.hxx"
#include "model/SlsPageDescriptor.hxx"
#include "model/SlsPageEnumeration.hxx"
#include "view/SlideSorterView.hxx"
#include "SlideSorterViewShell.hxx"
#include "view/SlsLayouter.hxx"
#include "view/SlsPageObject.hxx"
#include "view/SlsPageObjectViewObjectContact.hxx"
#include "ViewShellBase.hxx"
#include "UpdateLockManager.hxx"
#include "Window.hxx"
#include "sdpage.hxx"
namespace {
class ShowingModeGuard
{
public:
explicit ShowingModeGuard (::sd::slidesorter::view::OverlayBase& rOverlay,
bool bHideAndSave = false)
: mrOverlay (rOverlay),
mbIsShowing (mrOverlay.IsShowing()),
mbRestorePending(false)
{
if (mbIsShowing)
if (bHideAndSave)
{
mrOverlay.GetViewOverlay().HideAndSave (
::sd::slidesorter::view::ViewOverlay::OPT_XOR);
mbRestorePending = true;
}
mrOverlay.Hide();
}
~ShowingModeGuard (void)
{
if (mbIsShowing)
{
mrOverlay.Show();
if (mbRestorePending)
mrOverlay.GetViewOverlay().Restore ();
}
}
private:
::sd::slidesorter::view::OverlayBase& mrOverlay;
bool mbIsShowing;
bool mbRestorePending;
};
}
namespace sd { namespace slidesorter { namespace view {
//===== ViewOverlay =========================================================
ViewOverlay::ViewOverlay (SlideSorterViewShell& rViewShell)
: mrViewShell (rViewShell),
maSelectionRectangleOverlay(*this),
maMouseOverIndicatorOverlay(*this),
maInsertionIndicatorOverlay(*this),
maSubstitutionOverlay(*this),
mbSelectionRectangleWasVisible(false),
mbMouseOverIndicatorWasVisible(false),
mbInsertionIndicatorWasVisible(false),
mbSubstitutionDisplayWasVisible(false),
mnHideAndSaveLevel(0)
{
}
ViewOverlay::~ViewOverlay (void)
{
}
SelectionRectangleOverlay& ViewOverlay::GetSelectionRectangleOverlay (void)
{
return maSelectionRectangleOverlay;
}
MouseOverIndicatorOverlay& ViewOverlay::GetMouseOverIndicatorOverlay (void)
{
return maMouseOverIndicatorOverlay;
}
InsertionIndicatorOverlay& ViewOverlay::GetInsertionIndicatorOverlay (void)
{
return maInsertionIndicatorOverlay;
}
SubstitutionOverlay& ViewOverlay::GetSubstitutionOverlay (void)
{
return maSubstitutionOverlay;
}
void ViewOverlay::Paint (void)
{
maSelectionRectangleOverlay.Paint();
maMouseOverIndicatorOverlay.Paint();
maInsertionIndicatorOverlay.Paint();
maSubstitutionOverlay.Paint();
}
controller::SlideSorterController& ViewOverlay::GetController (void)
{
return mrViewShell.GetSlideSorterController();
}
SlideSorterViewShell& ViewOverlay::GetViewShell (void)
{
return mrViewShell;
}
void ViewOverlay::HideAndSave (OverlayPaintType eType)
{
if (mnHideAndSaveLevel++ == 0)
{
// Remember the current state of the visiblities of the overlays.
mbSelectionRectangleWasVisible = maSelectionRectangleOverlay.IsShowing();
mbMouseOverIndicatorWasVisible = maMouseOverIndicatorOverlay.IsShowing();
mbInsertionIndicatorWasVisible = maInsertionIndicatorOverlay.IsShowing();
mbSubstitutionDisplayWasVisible = maSubstitutionOverlay.IsShowing();
// Remember that we have saved the current state.
meSavedStateType = eType;
// Hide the overlays.
if (eType==OPT_ALL || eType==OPT_XOR)
{
if (mbSelectionRectangleWasVisible)
maSelectionRectangleOverlay.Hide();
}
if (mbSubstitutionDisplayWasVisible)
maSubstitutionOverlay.Hide();
if (eType==OPT_ALL || eType==OPT_PAINT)
{
if (mbMouseOverIndicatorWasVisible)
maMouseOverIndicatorOverlay.Hide();
if (mbInsertionIndicatorWasVisible)
maInsertionIndicatorOverlay.Hide();
}
}
}
void ViewOverlay::Restore (void)
{
if (--mnHideAndSaveLevel == 0)
{
if (meSavedStateType==OPT_ALL || meSavedStateType==OPT_PAINT)
{
if (mbInsertionIndicatorWasVisible)
maInsertionIndicatorOverlay.Show();
if (mbMouseOverIndicatorWasVisible)
maMouseOverIndicatorOverlay.Show();
}
if (mbSubstitutionDisplayWasVisible)
maSubstitutionOverlay.Show();
if (meSavedStateType==OPT_ALL || meSavedStateType==OPT_XOR)
{
if (mbSelectionRectangleWasVisible)
maSelectionRectangleOverlay.Show();
}
}
}
//===== OverlayBase =========================================================
OverlayBase::OverlayBase (ViewOverlay& rViewOverlay)
: mrViewOverlay(rViewOverlay),
mbIsShowing (false)
{
}
OverlayBase::~OverlayBase (void)
{
}
void OverlayBase::Paint (void)
{
}
bool OverlayBase::IsShowing (void)
{
return mbIsShowing;
}
void OverlayBase::Toggle (void)
{
if (IsShowing())
Hide();
else
Show();
}
void OverlayBase::Show (void)
{
if ( ! IsShowing())
{
mbIsShowing = true;
Paint ();
}
}
void OverlayBase::Hide (void)
{
if (IsShowing())
{
mbIsShowing = false;
Paint ();
}
}
ViewOverlay& OverlayBase::GetViewOverlay (void)
{
return mrViewOverlay;
}
//===== SubstitutionOverlay =================================================
SubstitutionOverlay::SubstitutionOverlay (ViewOverlay& rViewOverlay)
: OverlayBase(rViewOverlay)
{
}
SubstitutionOverlay::~SubstitutionOverlay (void)
{
}
void SubstitutionOverlay::Paint (void)
{
::osl::MutexGuard aGuard (maMutex);
SubstitutionShapeList::const_iterator aShape (maShapes.begin());
SubstitutionShapeList::const_iterator aShapeEnd (maShapes.end());
while (aShape!=aShapeEnd)
{
mrViewOverlay.GetViewShell().DrawMarkRect (*aShape);
aShape++;
}
OverlayBase::Paint();
}
void SubstitutionOverlay::Create (
model::PageEnumeration& rSelection,
const Point& rPosition)
{
ShowingModeGuard aGuard (*this);
maPosition = rPosition;
maShapes.clear();
while (rSelection.HasMoreElements())
{
maShapes.push_back(
rSelection.GetNextElement()->GetPageObject()->GetCurrentBoundRect());
}
}
void SubstitutionOverlay::Clear (void)
{
ShowingModeGuard aGuard (*this);
maShapes.clear();
}
void SubstitutionOverlay::Move (const Point& rOffset)
{
SetPosition (maPosition + rOffset);
}
void SubstitutionOverlay::SetPosition (const Point& rPosition)
{
ShowingModeGuard aGuard (*this);
Point rOffset = rPosition - maPosition;
SubstitutionShapeList::iterator aShape (maShapes.begin());
SubstitutionShapeList::const_iterator aShapeEnd (maShapes.end());
for (;aShape!=aShapeEnd; aShape++)
aShape->SetPos (aShape->TopLeft() + rOffset);
maPosition = rPosition;
}
const Point& SubstitutionOverlay::GetPosition (void) const
{
return maPosition;
}
//===== SelectionRectangleOverlay ===========================================
SelectionRectangleOverlay::SelectionRectangleOverlay (
ViewOverlay& rViewOverlay)
: OverlayBase (rViewOverlay),
maAnchor(0,0),
maSecondCorner(0,0)
{
}
void SelectionRectangleOverlay::Paint (void)
{
// mrViewOverlay.GetViewShell().DrawMarkRect (maSelectionRectangle);
}
void SelectionRectangleOverlay::Show (void)
{
if ( ! mbIsShowing)
{
SlideSorterView& rView (mrViewOverlay.GetViewShell().GetSlideSorterController().GetView());
rView.BegEncirclement(maAnchor);
rView.MovEncirclement(maSecondCorner);
OverlayBase::Show();
}
}
void SelectionRectangleOverlay::Hide (void)
{
if (mbIsShowing)
{
mrViewOverlay.GetViewShell().GetSlideSorterController().GetView().EndEncirclement();
OverlayBase::Hide();
}
}
Rectangle SelectionRectangleOverlay::GetSelectionRectangle (void)
{
return Rectangle(maAnchor, maSecondCorner);
}
void SelectionRectangleOverlay::Start (const Point& rAnchor)
{
maAnchor = rAnchor;
maSecondCorner = rAnchor;
mrViewOverlay.GetViewShell().GetSlideSorterController().GetView().BegEncirclement(maAnchor);
OverlayBase::Show();
}
void SelectionRectangleOverlay::Update (const Point& rSecondCorner)
{
maSecondCorner = rSecondCorner;
mrViewOverlay.GetViewShell().GetSlideSorterController().GetView().MovEncirclement(maSecondCorner);
}
//===== InsertionIndicatorOverlay ===========================================
InsertionIndicatorOverlay::InsertionIndicatorOverlay (
ViewOverlay& rViewOverlay)
: OverlayBase (rViewOverlay)
{
}
void InsertionIndicatorOverlay::SetPositionAndSize (
const Rectangle& aNewBoundingBox)
{
if (maBoundingBox != aNewBoundingBox)
{
ShowingModeGuard aGuard (*this, true);
maBoundingBox = aNewBoundingBox;
}
}
void InsertionIndicatorOverlay::Paint (void)
{
Color aColor;
if (mbIsShowing)
aColor = Application::GetSettings().GetStyleSettings().GetFontColor();
else
aColor = Application::GetSettings().GetStyleSettings().GetWindowColor();
mrViewOverlay.GetViewShell().DrawFilledRect (
maBoundingBox,
aColor,
aColor);
}
void InsertionIndicatorOverlay::SetPosition (const Point& rPoint)
{
static const bool bAllowHorizontalInsertMarker = true;
Layouter& rLayouter (
mrViewOverlay.GetController().GetView().GetLayouter());
USHORT nPageCount
= mrViewOverlay.GetController().GetModel().GetPageCount();
sal_Int32 nInsertionIndex = rLayouter.GetInsertionIndex (rPoint,
bAllowHorizontalInsertMarker);
if (nInsertionIndex >= nPageCount)
nInsertionIndex = nPageCount-1;
sal_Int32 nDrawIndex = nInsertionIndex;
bool bVertical = false;
bool bLeftOrTop = false;
if (nInsertionIndex >= 0)
{
// Now that we know where to insert, we still have to determine
// where to draw the marker. There are two decisions to make:
// 1. Draw a vertical or a horizontal insert marker.
// The horizontal one may only be chosen when there is only one
// column.
// 2. The vertical (standard) insert marker may be painted left to
// the insert page or right of the previous one. When both pages
// are in the same row this makes no difference. Otherwise the
// posiotions are at the left and right ends of two rows.
Point aPageCenter (rLayouter.GetPageObjectBox (
nInsertionIndex).Center());
if (bAllowHorizontalInsertMarker
&& rLayouter.GetColumnCount() == 1)
{
bVertical = false;
bLeftOrTop = (rPoint.Y() <= aPageCenter.Y());
}
else
{
bVertical = true;
bLeftOrTop = (rPoint.X() <= aPageCenter.X());
}
// Add one when the mark was painted below or to the right of the
// page object.
if ( ! bLeftOrTop)
nInsertionIndex += 1;
}
mnInsertionIndex = nInsertionIndex;
Rectangle aBox;
if (mnInsertionIndex >= 0)
aBox = rLayouter.GetInsertionMarkerBox (
nDrawIndex,
bVertical,
bLeftOrTop);
SetPositionAndSize (aBox);
}
sal_Int32 InsertionIndicatorOverlay::GetInsertionPageIndex (void) const
{
return mnInsertionIndex;
}
//===== MouseOverIndicatorOverlay ===========================================
MouseOverIndicatorOverlay::MouseOverIndicatorOverlay (
ViewOverlay& rViewOverlay)
: OverlayBase (rViewOverlay),
mpPageUnderMouse()
{
}
void MouseOverIndicatorOverlay::SetSlideUnderMouse (
const model::SharedPageDescriptor& rpDescriptor)
{
SlideSorterViewShell& rViewShell (mrViewOverlay.GetViewShell());
if ( ! rViewShell.GetViewShellBase().GetUpdateLockManager().IsLocked())
{
model::SharedPageDescriptor pDescriptor;
if ( ! mpPageUnderMouse.expired())
{
try
{
pDescriptor = model::SharedPageDescriptor(mpPageUnderMouse);
}
catch (::boost::bad_weak_ptr)
{
}
}
if (pDescriptor != rpDescriptor)
{
ShowingModeGuard aGuard (*this, true);
mpPageUnderMouse = rpDescriptor;
}
}
}
void MouseOverIndicatorOverlay::Paint (void)
{
if ( ! mpPageUnderMouse.expired())
{
model::SharedPageDescriptor pDescriptor;
try
{
pDescriptor = model::SharedPageDescriptor(mpPageUnderMouse);
}
catch (::boost::bad_weak_ptr)
{
}
if (pDescriptor.get() != NULL)
{
SlideSorterViewShell& rViewShell (mrViewOverlay.GetViewShell());
if ( ! rViewShell.GetViewShellBase().GetUpdateLockManager().IsLocked())
{
SlideSorterView& rView (rViewShell.GetSlideSorterController().GetView());
OutputDevice* pDevice = rView.GetWindow();
PageObjectViewObjectContact* pContact = pDescriptor->GetViewObjectContact();
if (pDevice != NULL
&& pContact != NULL)
{
pContact->PaintFrame(*pDevice, mbIsShowing);
}
}
}
}
}
} } } // end of namespace ::sd::slidesorter::view
<commit_msg>INTEGRATION: CWS aw024 (1.7.34); FILE MERGED 2006/09/21 23:28:23 aw 1.7.34.4: RESYNC: (1.9-1.10); FILE MERGED 2006/05/12 20:42:53 aw 1.7.34.3: RESYNC: (1.8-1.9); FILE MERGED 2005/09/17 13:31:43 aw 1.7.34.2: RESYNC: (1.7-1.8); FILE MERGED 2005/05/19 12:11:34 aw 1.7.34.1: #i39529#<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: SlsViewOverlay.cxx,v $
*
* $Revision: 1.11 $
*
* last change: $Author: ihi $ $Date: 2006-11-14 14:37:02 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sd.hxx"
#include "view/SlsViewOverlay.hxx"
#include "controller/SlideSorterController.hxx"
#include "model/SlideSorterModel.hxx"
#include "model/SlsPageDescriptor.hxx"
#include "model/SlsPageEnumeration.hxx"
#include "view/SlideSorterView.hxx"
#include "SlideSorterViewShell.hxx"
#include "view/SlsLayouter.hxx"
#include "view/SlsPageObject.hxx"
#include "view/SlsPageObjectViewObjectContact.hxx"
#include "ViewShellBase.hxx"
#include "UpdateLockManager.hxx"
#include "Window.hxx"
#include "sdpage.hxx"
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
namespace {
class ShowingModeGuard
{
public:
explicit ShowingModeGuard (::sd::slidesorter::view::OverlayBase& rOverlay,
bool bHideAndSave = false)
: mrOverlay (rOverlay),
mbIsShowing (mrOverlay.IsShowing()),
mbRestorePending(false)
{
if (mbIsShowing)
if (bHideAndSave)
{
mrOverlay.GetViewOverlay().HideAndSave (
::sd::slidesorter::view::ViewOverlay::OPT_XOR);
mbRestorePending = true;
}
mrOverlay.Hide();
}
~ShowingModeGuard (void)
{
if (mbIsShowing)
{
mrOverlay.Show();
if (mbRestorePending)
mrOverlay.GetViewOverlay().Restore ();
}
}
private:
::sd::slidesorter::view::OverlayBase& mrOverlay;
bool mbIsShowing;
bool mbRestorePending;
};
}
namespace sd { namespace slidesorter { namespace view {
//===== ViewOverlay =========================================================
ViewOverlay::ViewOverlay (SlideSorterViewShell& rViewShell)
: mrViewShell (rViewShell),
maSelectionRectangleOverlay(*this),
maMouseOverIndicatorOverlay(*this),
maInsertionIndicatorOverlay(*this),
maSubstitutionOverlay(*this),
mbSelectionRectangleWasVisible(false),
mbMouseOverIndicatorWasVisible(false),
mbInsertionIndicatorWasVisible(false),
mbSubstitutionDisplayWasVisible(false),
mnHideAndSaveLevel(0)
{
}
ViewOverlay::~ViewOverlay (void)
{
}
SelectionRectangleOverlay& ViewOverlay::GetSelectionRectangleOverlay (void)
{
return maSelectionRectangleOverlay;
}
MouseOverIndicatorOverlay& ViewOverlay::GetMouseOverIndicatorOverlay (void)
{
return maMouseOverIndicatorOverlay;
}
InsertionIndicatorOverlay& ViewOverlay::GetInsertionIndicatorOverlay (void)
{
return maInsertionIndicatorOverlay;
}
SubstitutionOverlay& ViewOverlay::GetSubstitutionOverlay (void)
{
return maSubstitutionOverlay;
}
void ViewOverlay::Paint (void)
{
maSelectionRectangleOverlay.Paint();
maMouseOverIndicatorOverlay.Paint();
maInsertionIndicatorOverlay.Paint();
maSubstitutionOverlay.Paint();
}
controller::SlideSorterController& ViewOverlay::GetController (void)
{
return mrViewShell.GetSlideSorterController();
}
SlideSorterViewShell& ViewOverlay::GetViewShell (void)
{
return mrViewShell;
}
void ViewOverlay::HideAndSave (OverlayPaintType eType)
{
if (mnHideAndSaveLevel++ == 0)
{
// Remember the current state of the visiblities of the overlays.
mbSelectionRectangleWasVisible = maSelectionRectangleOverlay.IsShowing();
mbMouseOverIndicatorWasVisible = maMouseOverIndicatorOverlay.IsShowing();
mbInsertionIndicatorWasVisible = maInsertionIndicatorOverlay.IsShowing();
mbSubstitutionDisplayWasVisible = maSubstitutionOverlay.IsShowing();
// Remember that we have saved the current state.
meSavedStateType = eType;
// Hide the overlays.
if (eType==OPT_ALL || eType==OPT_XOR)
{
if (mbSelectionRectangleWasVisible)
maSelectionRectangleOverlay.Hide();
}
if (mbSubstitutionDisplayWasVisible)
maSubstitutionOverlay.Hide();
if (eType==OPT_ALL || eType==OPT_PAINT)
{
if (mbMouseOverIndicatorWasVisible)
maMouseOverIndicatorOverlay.Hide();
if (mbInsertionIndicatorWasVisible)
maInsertionIndicatorOverlay.Hide();
}
}
}
void ViewOverlay::Restore (void)
{
if (--mnHideAndSaveLevel == 0)
{
if (meSavedStateType==OPT_ALL || meSavedStateType==OPT_PAINT)
{
if (mbInsertionIndicatorWasVisible)
maInsertionIndicatorOverlay.Show();
if (mbMouseOverIndicatorWasVisible)
maMouseOverIndicatorOverlay.Show();
}
if (mbSubstitutionDisplayWasVisible)
maSubstitutionOverlay.Show();
if (meSavedStateType==OPT_ALL || meSavedStateType==OPT_XOR)
{
if (mbSelectionRectangleWasVisible)
maSelectionRectangleOverlay.Show();
}
}
}
//===== OverlayBase =========================================================
OverlayBase::OverlayBase (ViewOverlay& rViewOverlay)
: mrViewOverlay(rViewOverlay),
mbIsShowing (false)
{
}
OverlayBase::~OverlayBase (void)
{
}
void OverlayBase::Paint (void)
{
}
bool OverlayBase::IsShowing (void)
{
return mbIsShowing;
}
void OverlayBase::Toggle (void)
{
if (IsShowing())
Hide();
else
Show();
}
void OverlayBase::Show (void)
{
if ( ! IsShowing())
{
mbIsShowing = true;
Paint ();
}
}
void OverlayBase::Hide (void)
{
if (IsShowing())
{
mbIsShowing = false;
Paint ();
}
}
ViewOverlay& OverlayBase::GetViewOverlay (void)
{
return mrViewOverlay;
}
//===== SubstitutionOverlay =================================================
SubstitutionOverlay::SubstitutionOverlay (ViewOverlay& rViewOverlay)
: OverlayBase(rViewOverlay)
{
}
SubstitutionOverlay::~SubstitutionOverlay (void)
{
}
void SubstitutionOverlay::Paint (void)
{
::osl::MutexGuard aGuard (maMutex);
SubstitutionShapeList::const_iterator aShape (maShapes.begin());
SubstitutionShapeList::const_iterator aShapeEnd (maShapes.end());
while (aShape!=aShapeEnd)
{
mrViewOverlay.GetViewShell().DrawMarkRect (*aShape);
aShape++;
}
OverlayBase::Paint();
}
void SubstitutionOverlay::Create (
model::PageEnumeration& rSelection,
const Point& rPosition)
{
ShowingModeGuard aGuard (*this);
maPosition = rPosition;
maShapes.clear();
while (rSelection.HasMoreElements())
{
maShapes.push_back(
rSelection.GetNextElement()->GetPageObject()->GetCurrentBoundRect());
}
}
void SubstitutionOverlay::Clear (void)
{
ShowingModeGuard aGuard (*this);
maShapes.clear();
}
void SubstitutionOverlay::Move (const Point& rOffset)
{
SetPosition (maPosition + rOffset);
}
void SubstitutionOverlay::SetPosition (const Point& rPosition)
{
ShowingModeGuard aGuard (*this);
Point rOffset = rPosition - maPosition;
SubstitutionShapeList::iterator aShape (maShapes.begin());
SubstitutionShapeList::const_iterator aShapeEnd (maShapes.end());
for (;aShape!=aShapeEnd; aShape++)
aShape->SetPos (aShape->TopLeft() + rOffset);
maPosition = rPosition;
}
const Point& SubstitutionOverlay::GetPosition (void) const
{
return maPosition;
}
//===== SelectionRectangleOverlay ===========================================
SelectionRectangleOverlay::SelectionRectangleOverlay (
ViewOverlay& rViewOverlay)
: OverlayBase (rViewOverlay),
maAnchor(0,0),
maSecondCorner(0,0)
{
}
void SelectionRectangleOverlay::Paint (void)
{
// mrViewOverlay.GetViewShell().DrawMarkRect (maSelectionRectangle);
}
void SelectionRectangleOverlay::Show (void)
{
if ( ! mbIsShowing)
{
SlideSorterView& rView (mrViewOverlay.GetViewShell().GetSlideSorterController().GetView());
rView.BegEncirclement(maAnchor);
rView.MovEncirclement(maSecondCorner);
OverlayBase::Show();
}
}
void SelectionRectangleOverlay::Hide (void)
{
if (mbIsShowing)
{
mrViewOverlay.GetViewShell().GetSlideSorterController().GetView().EndEncirclement();
OverlayBase::Hide();
}
}
Rectangle SelectionRectangleOverlay::GetSelectionRectangle (void)
{
return Rectangle(maAnchor, maSecondCorner);
}
void SelectionRectangleOverlay::Start (const Point& rAnchor)
{
maAnchor = rAnchor;
maSecondCorner = rAnchor;
mrViewOverlay.GetViewShell().GetSlideSorterController().GetView().BegEncirclement(maAnchor);
OverlayBase::Show();
}
void SelectionRectangleOverlay::Update (const Point& rSecondCorner)
{
maSecondCorner = rSecondCorner;
mrViewOverlay.GetViewShell().GetSlideSorterController().GetView().MovEncirclement(maSecondCorner);
}
//===== InsertionIndicatorOverlay ===========================================
InsertionIndicatorOverlay::InsertionIndicatorOverlay (
ViewOverlay& rViewOverlay)
: OverlayBase (rViewOverlay)
{
}
void InsertionIndicatorOverlay::SetPositionAndSize (
const Rectangle& aNewBoundingBox)
{
if (maBoundingBox != aNewBoundingBox)
{
ShowingModeGuard aGuard (*this, true);
maBoundingBox = aNewBoundingBox;
}
}
void InsertionIndicatorOverlay::Paint (void)
{
Color aColor;
if (mbIsShowing)
aColor = Application::GetSettings().GetStyleSettings().GetFontColor();
else
aColor = Application::GetSettings().GetStyleSettings().GetWindowColor();
mrViewOverlay.GetViewShell().DrawFilledRect (
maBoundingBox,
aColor,
aColor);
}
void InsertionIndicatorOverlay::SetPosition (const Point& rPoint)
{
static const bool bAllowHorizontalInsertMarker = true;
Layouter& rLayouter (
mrViewOverlay.GetController().GetView().GetLayouter());
USHORT nPageCount
= mrViewOverlay.GetController().GetModel().GetPageCount();
sal_Int32 nInsertionIndex = rLayouter.GetInsertionIndex (rPoint,
bAllowHorizontalInsertMarker);
if (nInsertionIndex >= nPageCount)
nInsertionIndex = nPageCount-1;
sal_Int32 nDrawIndex = nInsertionIndex;
bool bVertical = false;
bool bLeftOrTop = false;
if (nInsertionIndex >= 0)
{
// Now that we know where to insert, we still have to determine
// where to draw the marker. There are two decisions to make:
// 1. Draw a vertical or a horizontal insert marker.
// The horizontal one may only be chosen when there is only one
// column.
// 2. The vertical (standard) insert marker may be painted left to
// the insert page or right of the previous one. When both pages
// are in the same row this makes no difference. Otherwise the
// posiotions are at the left and right ends of two rows.
Point aPageCenter (rLayouter.GetPageObjectBox (
nInsertionIndex).Center());
if (bAllowHorizontalInsertMarker
&& rLayouter.GetColumnCount() == 1)
{
bVertical = false;
bLeftOrTop = (rPoint.Y() <= aPageCenter.Y());
}
else
{
bVertical = true;
bLeftOrTop = (rPoint.X() <= aPageCenter.X());
}
// Add one when the mark was painted below or to the right of the
// page object.
if ( ! bLeftOrTop)
nInsertionIndex += 1;
}
mnInsertionIndex = nInsertionIndex;
Rectangle aBox;
if (mnInsertionIndex >= 0)
aBox = rLayouter.GetInsertionMarkerBox (
nDrawIndex,
bVertical,
bLeftOrTop);
SetPositionAndSize (aBox);
}
sal_Int32 InsertionIndicatorOverlay::GetInsertionPageIndex (void) const
{
return mnInsertionIndex;
}
//===== MouseOverIndicatorOverlay ===========================================
MouseOverIndicatorOverlay::MouseOverIndicatorOverlay (
ViewOverlay& rViewOverlay)
: OverlayBase (rViewOverlay),
mpPageUnderMouse()
{
}
void MouseOverIndicatorOverlay::SetSlideUnderMouse (
const model::SharedPageDescriptor& rpDescriptor)
{
SlideSorterViewShell& rViewShell (mrViewOverlay.GetViewShell());
if ( ! rViewShell.GetViewShellBase().GetUpdateLockManager().IsLocked())
{
model::SharedPageDescriptor pDescriptor;
if ( ! mpPageUnderMouse.expired())
{
try
{
pDescriptor = model::SharedPageDescriptor(mpPageUnderMouse);
}
catch (::boost::bad_weak_ptr)
{
}
}
if (pDescriptor != rpDescriptor)
{
ShowingModeGuard aGuard (*this, true);
mpPageUnderMouse = rpDescriptor;
}
}
}
void MouseOverIndicatorOverlay::Paint (void)
{
if ( ! mpPageUnderMouse.expired())
{
model::SharedPageDescriptor pDescriptor;
try
{
pDescriptor = model::SharedPageDescriptor(mpPageUnderMouse);
}
catch (::boost::bad_weak_ptr)
{
}
if (pDescriptor.get() != NULL)
{
SlideSorterViewShell& rViewShell (mrViewOverlay.GetViewShell());
if ( ! rViewShell.GetViewShellBase().GetUpdateLockManager().IsLocked())
{
SlideSorterView& rView (rViewShell.GetSlideSorterController().GetView());
OutputDevice* pDevice = rView.GetWindow();
PageObjectViewObjectContact* pContact = pDescriptor->GetViewObjectContact();
if (pDevice != NULL
&& pContact != NULL)
{
pContact->PaintFrame(*pDevice, mbIsShowing);
}
}
}
}
}
} } } // end of namespace ::sd::slidesorter::view
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2014 Zubax, zubax.com
* Distributed under the MIT License, available in the file LICENSE.
* Author: Pavel Kirienko <[email protected]>
*/
#pragma once
#if !defined(DEBUG_BUILD) && !defined(RELEASE_BUILD)
# error Either DEBUG_BUILD or RELEASE_BUILD must be defined
#endif
#include <ch.hpp>
#include <hal.h>
#include <type_traits>
#include <limits>
#include <cstdint>
#include <cassert>
#include "execute_once.hpp"
#ifndef STRINGIZE
# define STRINGIZE2(x) #x
# define STRINGIZE(x) STRINGIZE2(x)
#endif
#if defined(DEBUG_BUILD) && DEBUG_BUILD
# define MAKE_ASSERT_MSG_(x) (__FILE__ ":" STRINGIZE(__LINE__) ":" STRINGIZE(x))
#else
# define MAKE_ASSERT_MSG_(x) (STRINGIZE(__LINE__))
#endif
#define ASSERT_ALWAYS(x) \
do { \
if ((x) == 0) { \
chSysHalt(MAKE_ASSERT_MSG_(x)); \
} \
} while (0)
#define LIKELY(x) (__builtin_expect((x), true))
#define UNLIKELY(x) (__builtin_expect((x), false))
#if defined(DEBUG_BUILD) && DEBUG_BUILD
# define DEBUG_LOG(...) ::os::lowsyslog(__VA_ARGS__)
#else
# define DEBUG_LOG(...) ((void)0)
#endif
namespace os
{
static constexpr unsigned DefaultStdIOByteWriteTimeoutMSec = 2; ///< Enough for 115200 baud and higher
/**
* NuttX-like console print; should be used instead of printf()/chprintf()
* This function always outputs into the debug UART regardless of the current stdout configuration.
* TODO: use type safe version based on variadic templates.
*/
__attribute__ ((format (printf, 1, 2)))
void lowsyslog(const char* format, ...);
/**
* Changes current stdout stream and its write timeout.
* This setting does not affect @ref lowsyslog().
*/
void setStdIOStream(::BaseChannel* stream, unsigned byte_write_timeout_msec = DefaultStdIOByteWriteTimeoutMSec);
::BaseChannel* getStdIOStream();
/**
* Provides access to the stdout mutex.
*/
chibios_rt::Mutex& getStdIOMutex();
/**
* Emergency termination hook that can be overriden by the application.
* The hook must return immediately after bringing the hardware into a safe state.
*/
extern void applicationHaltHook(void);
/**
* Replacement for chThdSleepUntil() that accepts timestamps from the past.
* http://sourceforge.net/p/chibios/bugs/292/#ec7c
*/
void sleepUntilChTime(systime_t sleep_until);
/**
* After this function is invoked, @ref isRebootRequested() will be returning true.
*/
void requestReboot();
/**
* Returns true if the application must reboot.
*/
bool isRebootRequested();
namespace impl_
{
class MutexLockerImpl
{
chibios_rt::Mutex& mutex_;
public:
MutexLockerImpl(chibios_rt::Mutex& m) : mutex_(m)
{
mutex_.lock();
}
~MutexLockerImpl()
{
mutex_.unlock();
}
};
class CriticalSectionLockerImpl
{
volatile const syssts_t st_ = chSysGetStatusAndLockX();
public:
~CriticalSectionLockerImpl() { chSysRestoreStatusX(st_); }
};
} // namespace impl_
/**
* RAII mutex locker.
* Must be volatile in order to prevent the optimizer from throwing it away.
*/
using MutexLocker = volatile impl_::MutexLockerImpl;
/**
* RAII critical section locker.
* Must be volatile in order to prevent the optimizer from throwing it away.
*/
using CriticalSectionLocker = volatile impl_::CriticalSectionLockerImpl;
/**
* Converts any signed or unsigned integer to string and returns it by value.
* The argument must be integer, otherwise the call will be rejected by SFINAE.
* Usage examples:
* intToString(var)
* intToString<16>(var)
* intToString<2>(var).c_str()
*/
template <
int Radix = 10,
typename T,
typename std::enable_if<std::is_integral<T>::value>::type...
>
inline auto intToString(T number)
{
static constexpr char Alphabet[] = "0123456789abcdefghijklmnopqrstuvwxyz";
static_assert(Radix >= 1, "Radix must be positive");
static_assert(Radix <= (sizeof(Alphabet) / sizeof(Alphabet[0])), "Radix is too large");
// Plus 1 to round up, see the standard for details.
static constexpr unsigned MaxChars =
((Radix >= 10) ? std::numeric_limits<T>::digits10 : std::numeric_limits<T>::digits) +
1 + (std::is_signed<T>::value ? 1 : 0);
class Container
{
std::uint_fast16_t offset_;
char storage_[MaxChars + 1]; // Plus 1 because of zero termination.
public:
Container(T x) :
offset_(MaxChars) // Field initialization is not working in GCC in this context, not sure why.
{
storage_[offset_] = '\0';
do
{
assert(offset_ > 0);
if (std::is_signed<T>::value) // Should be converted to constexpr if.
{
// We can't just do "x = -x", because it would break on int8_t(-128), int16_t(-32768), etc.
auto residual = std::int_fast8_t(x % Radix);
if (residual < 0)
{
// Should never happen - since C++11, neg % pos --> pos
residual = -residual;
}
storage_[--offset_] = Alphabet[residual];
// Signed integers are really tricky sometimes.
// We must not mix negative with positive to avoid implementation-defined behaviors.
x = (x < 0) ? -(x / -Radix) : (x / Radix);
}
else
{
// Fast branch for unsigned arguments.
storage_[--offset_] = Alphabet[x % Radix];
x /= Radix;
}
}
while (x != 0);
if (std::is_signed<T>::value && (x < 0)) // Should be optimized with constexpr if.
{
assert(offset_ > 0);
storage_[--offset_] = '-';
}
assert(offset_ < MaxChars); // Making sure there was no overflow.
}
const char* c_str() const { return &storage_[offset_]; }
operator const char* () const { return this->c_str(); }
};
return Container(number);
}
}
<commit_msg>Notes on rvalue<commit_after>/*
* Copyright (c) 2014 Zubax, zubax.com
* Distributed under the MIT License, available in the file LICENSE.
* Author: Pavel Kirienko <[email protected]>
*/
#pragma once
#if !defined(DEBUG_BUILD) && !defined(RELEASE_BUILD)
# error Either DEBUG_BUILD or RELEASE_BUILD must be defined
#endif
#include <ch.hpp>
#include <hal.h>
#include <type_traits>
#include <limits>
#include <cstdint>
#include <cassert>
#include "execute_once.hpp"
#ifndef STRINGIZE
# define STRINGIZE2(x) #x
# define STRINGIZE(x) STRINGIZE2(x)
#endif
#if defined(DEBUG_BUILD) && DEBUG_BUILD
# define MAKE_ASSERT_MSG_(x) (__FILE__ ":" STRINGIZE(__LINE__) ":" STRINGIZE(x))
#else
# define MAKE_ASSERT_MSG_(x) (STRINGIZE(__LINE__))
#endif
#define ASSERT_ALWAYS(x) \
do { \
if ((x) == 0) { \
chSysHalt(MAKE_ASSERT_MSG_(x)); \
} \
} while (0)
#define LIKELY(x) (__builtin_expect((x), true))
#define UNLIKELY(x) (__builtin_expect((x), false))
#if defined(DEBUG_BUILD) && DEBUG_BUILD
# define DEBUG_LOG(...) ::os::lowsyslog(__VA_ARGS__)
#else
# define DEBUG_LOG(...) ((void)0)
#endif
namespace os
{
static constexpr unsigned DefaultStdIOByteWriteTimeoutMSec = 2; ///< Enough for 115200 baud and higher
/**
* NuttX-like console print; should be used instead of printf()/chprintf()
* This function always outputs into the debug UART regardless of the current stdout configuration.
* TODO: use type safe version based on variadic templates.
*/
__attribute__ ((format (printf, 1, 2)))
void lowsyslog(const char* format, ...);
/**
* Changes current stdout stream and its write timeout.
* This setting does not affect @ref lowsyslog().
*/
void setStdIOStream(::BaseChannel* stream, unsigned byte_write_timeout_msec = DefaultStdIOByteWriteTimeoutMSec);
::BaseChannel* getStdIOStream();
/**
* Provides access to the stdout mutex.
*/
chibios_rt::Mutex& getStdIOMutex();
/**
* Emergency termination hook that can be overriden by the application.
* The hook must return immediately after bringing the hardware into a safe state.
*/
extern void applicationHaltHook(void);
/**
* Replacement for chThdSleepUntil() that accepts timestamps from the past.
* http://sourceforge.net/p/chibios/bugs/292/#ec7c
*/
void sleepUntilChTime(systime_t sleep_until);
/**
* After this function is invoked, @ref isRebootRequested() will be returning true.
*/
void requestReboot();
/**
* Returns true if the application must reboot.
*/
bool isRebootRequested();
namespace impl_
{
class MutexLockerImpl
{
chibios_rt::Mutex& mutex_;
public:
MutexLockerImpl(chibios_rt::Mutex& m) : mutex_(m)
{
mutex_.lock();
}
~MutexLockerImpl()
{
mutex_.unlock();
}
};
class CriticalSectionLockerImpl
{
volatile const syssts_t st_ = chSysGetStatusAndLockX();
public:
~CriticalSectionLockerImpl() { chSysRestoreStatusX(st_); }
};
} // namespace impl_
/**
* RAII mutex locker.
* Must be volatile in order to prevent the optimizer from throwing it away.
*/
using MutexLocker = volatile impl_::MutexLockerImpl;
/**
* RAII critical section locker.
* Must be volatile in order to prevent the optimizer from throwing it away.
*/
using CriticalSectionLocker = volatile impl_::CriticalSectionLockerImpl;
/**
* Converts any signed or unsigned integer to string and returns it by value.
* The argument must be integer, otherwise the call will be rejected by SFINAE.
* Usage examples:
* intToString(var)
* intToString<16>(var)
* intToString<2>(var).c_str()
* It is safe to obtain a reference to the returned string and pass it to another function as an argument,
* which enables use cases like this (this example is somewhat made up, but it conveys the idea nicely):
* print("%s", intToString(123).c_str());
* More info on rvalue references:
* https://herbsutter.com/2008/01/01/gotw-88-a-candidate-for-the-most-important-const/
* http://stackoverflow.com/questions/584824/guaranteed-lifetime-of-temporary-in-c
*/
template <
int Radix = 10,
typename T,
typename std::enable_if<std::is_integral<T>::value>::type...
>
inline auto intToString(T number)
{
static constexpr char Alphabet[] = "0123456789abcdefghijklmnopqrstuvwxyz";
static_assert(Radix >= 1, "Radix must be positive");
static_assert(Radix <= (sizeof(Alphabet) / sizeof(Alphabet[0])), "Radix is too large");
// Plus 1 to round up, see the standard for details.
static constexpr unsigned MaxChars =
((Radix >= 10) ? std::numeric_limits<T>::digits10 : std::numeric_limits<T>::digits) +
1 + (std::is_signed<T>::value ? 1 : 0);
class Container
{
std::uint_fast16_t offset_;
char storage_[MaxChars + 1]; // Plus 1 because of zero termination.
public:
Container(T x) :
offset_(MaxChars) // Field initialization is not working in GCC in this context, not sure why.
{
storage_[offset_] = '\0';
do
{
assert(offset_ > 0);
if (std::is_signed<T>::value) // Should be converted to constexpr if.
{
// We can't just do "x = -x", because it would break on int8_t(-128), int16_t(-32768), etc.
auto residual = std::int_fast8_t(x % Radix);
if (residual < 0)
{
// Should never happen - since C++11, neg % pos --> pos
residual = -residual;
}
storage_[--offset_] = Alphabet[residual];
// Signed integers are really tricky sometimes.
// We must not mix negative with positive to avoid implementation-defined behaviors.
x = (x < 0) ? -(x / -Radix) : (x / Radix);
}
else
{
// Fast branch for unsigned arguments.
storage_[--offset_] = Alphabet[x % Radix];
x /= Radix;
}
}
while (x != 0);
if (std::is_signed<T>::value && (x < 0)) // Should be optimized with constexpr if.
{
assert(offset_ > 0);
storage_[--offset_] = '-';
}
assert(offset_ < MaxChars); // Making sure there was no overflow.
}
const char* c_str() const { return &storage_[offset_]; }
operator const char* () const { return this->c_str(); }
};
return Container(number);
}
}
<|endoftext|>
|
<commit_before>// ******************************************************************************************
// * This project is licensed under the GNU Affero GPL v3. Copyright © 2014 A3Wasteland.com *
// ******************************************************************************************
#define vehicleManagementDialog 12000
#define vehicleManagementListBox 12001
#define vehicleManagementVehicleCount 12002
#define vehicleWeaponsText 12003
#define vehicleUsersText 12004
#define vehicleDamageText 12005
#define vehicleSpeedText 12006
#define vehicleManagementCivButton 12007
#define vehicleManagementHeliButton 12008
#define vehicleManagementPlaneButton 12009
#define vehicleManagementTankButton 12010
class VehicleManagement {
idd = vehicleManagementDialog;
movingEnable = false;
enableSimulation = true;
onLoad = "[4] execVM 'client\systems\adminPanel\populateVehicles.sqf'";
class controlsBackground {
class MainBackground: w_RscPicture
{
idc = -1;
colorText[] = {1, 1, 1, 1};
colorBackground[] = {0,0,0,0};
text = "#(argb,8,8,3)color(0,0,0,0.6)";
x = 0.295 * safezoneW + safezoneX;
y = 0.228 * safezoneH + safezoneY;
w = 0.35 * safezoneW;
h = 0.543 * safezoneH;
};
class TopBar: w_RscPicture
{
idc = -1;
colorText[] = {1, 1, 1, 1};
colorBackground[] = {0,0,0,0};
text = "#(argb,8,8,3)color(0.25,0.51,0.96,0.8)";
x = 0.295 * safezoneW + safezoneX;
y = 0.228 * safezoneH + safezoneY;
w = 0.35 * safezoneW;
h = 0.05 * safezoneH;
};
class menuTitle: w_RscText
{
idc = -1;
text = "Vehicle Management";
font = "PuristaMedium";
sizeEx = "( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)";
x = 0.305 * safezoneW + safezoneX;
y = 0.240 * safezoneH + safezoneY;
w = 0.15 * safezoneW;
h = 0.030 * safezoneH;
};
class amountOfVehicles: w_RscText
{
idc = vehicleManagementVehicleCount;
text = "";
x = 0.305 * safezoneW + safezoneX;
y = 0.288 * safezoneH + safezoneY;
w = 0.121 * safezoneW;
h = 0.031 * safezoneH;
};
class weaponsText: w_RscText
{
idc = vehicleWeaponsText;
text = "Weapons:";
sizeEx = 0.030;
x = 0.305 * safezoneW + safezoneX;
y = 0.575 * safezoneH + safezoneY;
w = 0.2 * safezoneW;
h = 0.030 * safezoneH;
};
class speedText: w_RscText
{
idc = vehicleSpeedText;
text = "Speed:";
sizeEx = 0.030;
x = 0.305 * safezoneW + safezoneX;
y = 0.595 * safezoneH + safezoneY;
w = 0.2 * safezoneW;
h = 0.030 * safezoneH;
};
class usersText: w_RscText
{
idc = vehicleUsersText;
text = "Users:";
sizeEx = 0.030;
x = 0.305 * safezoneW + safezoneX;
y = 0.615 * safezoneH + safezoneY;
w = 0.2 * safezoneW;
h = 0.030 * safezoneH;
};
class damageText: w_RscText
{
idc = vehicleDamageText;
text = "Damage:";
sizeEx = 0.030;
x = 0.305 * safezoneW + safezoneX;
y = 0.635 * safezoneH + safezoneY;
w = 0.2 * safezoneW;
h = 0.030 * safezoneH;
};
};
class controls {
class vehicleListBox: w_RscList
{
idc = vehicleManagementListBox;
onLBSelChanged="[1,_this select 1] execVM ""client\systems\adminPanel\importvalues.sqf"";";
x = 0.305 * safezoneW + safezoneX;
y = 0.324 * safezoneH + safezoneY;
w = 0.32875 * safezoneW;
h = 0.250 * safezoneH;
};
class civButton: w_RscButton
{
idc = vehicleManagementCivButton;
onButtonClick = "[0] execVM 'client\systems\adminPanel\populateVehicles.sqf'";
text = "Cars/Trucks";
x = 0.305 * safezoneW + safezoneX;
y = 0.67 * safezoneH + safezoneY;
w = 0.075 * safezoneW;
h = 0.040 * safezoneH;
};
class heliButton: w_RscButton
{
idc = vehicleManagementHeliButton;
onButtonClick = "[1] execVM 'client\systems\adminPanel\populateVehicles.sqf'";
text = "Helicopters";
x = 0.384 * safezoneW + safezoneX;
y = 0.67 * safezoneH + safezoneY;
w = 0.075 * safezoneW;
h = 0.040 * safezoneH;
};
class planeButton: w_RscButton
{
idc = vehicleManagementPlaneButton;
onButtonClick = "[2] execVM 'client\systems\adminPanel\populateVehicles.sqf'";
text = "Planes";
x = 0.305 * safezoneW + safezoneX;
y = 0.715 * safezoneH + safezoneY;
w = 0.075 * safezoneW;
h = 0.040 * safezoneH;
};
class tankButton: w_RscButton
{
idc = vehicleManagementTankButton;
onButtonClick = "[3] execVM 'client\systems\adminPanel\populateVehicles.sqf'";
text = "Tanks";
x = 0.384 * safezoneW + safezoneX;
y = 0.715 * safezoneH + safezoneY;
w = 0.075 * safezoneW;
h = 0.040 * safezoneH;
};
class hackedVehiclesButton: w_RscButton
{
idc = -1;
onButtonClick = "[4] execVM 'client\systems\adminPanel\populateVehicles.sqf'";
text = "Hacked Vehicles";
x = 0.462 * safezoneW + safezoneX;
y = 0.715 * safezoneH + safezoneY;
w = 0.085 * safezoneW;
h = 0.040 * safezoneH;
};
class deleteButton: w_RscButton
{
idc = -1;
onButtonClick = "execVM 'client\systems\adminPanel\deleteVehicle.sqf'";
text = "Delete Vehicle";
x = 0.554 * safezoneW + safezoneX;
y = 0.67 * safezoneH + safezoneY;
w = 0.075 * safezoneW;
h = 0.040 * safezoneH;
color[] = {0.95,0.1,0.1,1};
};
class deleteAllButton: w_RscButton
{
idc = -1;
onButtonClick = "execVM 'client\systems\adminPanel\deleteAllHackedVehicles.sqf'";
text = "Delete All";
x = 0.554 * safezoneW + safezoneX;
y = 0.715 * safezoneH + safezoneY;
w = 0.075 * safezoneW;
h = 0.040 * safezoneH;
color[] = {0.95,0.1,0.1,1};
};
};
};
<commit_msg>Update vehicleManagement.hpp<commit_after>// ******************************************************************************************
// * This project is licensed under the GNU Affero GPL v3. Copyright © 2014 A3Wasteland.com *
// ******************************************************************************************
#define vehicleManagementDialog 12000
#define vehicleManagementListBox 12001
#define vehicleManagementVehicleCount 12002
#define vehicleWeaponsText 12003
#define vehicleUsersText 12004
#define vehicleDamageText 12005
#define vehicleSpeedText 12006
#define vehicleManagementCivButton 12007
#define vehicleManagementHeliButton 12008
#define vehicleManagementPlaneButton 12009
#define vehicleManagementTankButton 12010
class VehicleManagement {
idd = vehicleManagementDialog;
movingEnable = false;
enableSimulation = true;
onLoad = "[4] execVM 'client\systems\adminPanel\populateVehicles.sqf'";
class controlsBackground {
class MainBackground: w_RscPicture
{
idc = -1;
colorText[] = {1, 1, 1, 1};
colorBackground[] = {0,0,0,0};
text = "#(argb,8,8,3)color(0,0,0,0.6)";
x = 0.295 * safezoneW + safezoneX;
y = 0.228 * safezoneH + safezoneY;
w = 0.35 * safezoneW;
h = 0.543 * safezoneH;
};
class TopBar: w_RscPicture
{
idc = -1;
colorText[] = {1, 1, 1, 1};
colorBackground[] = {0,0,0,0};
text = "#(argb,8,8,3)color(0.25,0.51,0.96,0.8)";
x = 0.295 * safezoneW + safezoneX;
y = 0.228 * safezoneH + safezoneY;
w = 0.35 * safezoneW;
h = 0.05 * safezoneH;
};
class menuTitle: w_RscText
{
idc = -1;
text = "Gestión de vehículo";
font = "PuristaMedium";
sizeEx = "( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)";
x = 0.305 * safezoneW + safezoneX;
y = 0.240 * safezoneH + safezoneY;
w = 0.15 * safezoneW;
h = 0.030 * safezoneH;
};
class amountOfVehicles: w_RscText
{
idc = vehicleManagementVehicleCount;
text = "";
x = 0.305 * safezoneW + safezoneX;
y = 0.288 * safezoneH + safezoneY;
w = 0.121 * safezoneW;
h = 0.031 * safezoneH;
};
class weaponsText: w_RscText
{
idc = vehicleWeaponsText;
text = "Armas:";
sizeEx = 0.030;
x = 0.305 * safezoneW + safezoneX;
y = 0.575 * safezoneH + safezoneY;
w = 0.2 * safezoneW;
h = 0.030 * safezoneH;
};
class speedText: w_RscText
{
idc = vehicleSpeedText;
text = "Velocidad:";
sizeEx = 0.030;
x = 0.305 * safezoneW + safezoneX;
y = 0.595 * safezoneH + safezoneY;
w = 0.2 * safezoneW;
h = 0.030 * safezoneH;
};
class usersText: w_RscText
{
idc = vehicleUsersText;
text = "Jugadores:";
sizeEx = 0.030;
x = 0.305 * safezoneW + safezoneX;
y = 0.615 * safezoneH + safezoneY;
w = 0.2 * safezoneW;
h = 0.030 * safezoneH;
};
class damageText: w_RscText
{
idc = vehicleDamageText;
text = "Daño:";
sizeEx = 0.030;
x = 0.305 * safezoneW + safezoneX;
y = 0.635 * safezoneH + safezoneY;
w = 0.2 * safezoneW;
h = 0.030 * safezoneH;
};
};
class controls {
class vehicleListBox: w_RscList
{
idc = vehicleManagementListBox;
onLBSelChanged="[1,_this select 1] execVM ""client\systems\adminPanel\importvalues.sqf"";";
x = 0.305 * safezoneW + safezoneX;
y = 0.324 * safezoneH + safezoneY;
w = 0.32875 * safezoneW;
h = 0.250 * safezoneH;
};
class civButton: w_RscButton
{
idc = vehicleManagementCivButton;
onButtonClick = "[0] execVM 'client\systems\adminPanel\populateVehicles.sqf'";
text = "Coches/Camiones";
x = 0.305 * safezoneW + safezoneX;
y = 0.67 * safezoneH + safezoneY;
w = 0.075 * safezoneW;
h = 0.040 * safezoneH;
};
class heliButton: w_RscButton
{
idc = vehicleManagementHeliButton;
onButtonClick = "[1] execVM 'client\systems\adminPanel\populateVehicles.sqf'";
text = "Helicópteros";
x = 0.384 * safezoneW + safezoneX;
y = 0.67 * safezoneH + safezoneY;
w = 0.075 * safezoneW;
h = 0.040 * safezoneH;
};
class planeButton: w_RscButton
{
idc = vehicleManagementPlaneButton;
onButtonClick = "[2] execVM 'client\systems\adminPanel\populateVehicles.sqf'";
text = "Aviones";
x = 0.305 * safezoneW + safezoneX;
y = 0.715 * safezoneH + safezoneY;
w = 0.075 * safezoneW;
h = 0.040 * safezoneH;
};
class tankButton: w_RscButton
{
idc = vehicleManagementTankButton;
onButtonClick = "[3] execVM 'client\systems\adminPanel\populateVehicles.sqf'";
text = "Tanques";
x = 0.384 * safezoneW + safezoneX;
y = 0.715 * safezoneH + safezoneY;
w = 0.075 * safezoneW;
h = 0.040 * safezoneH;
};
class hackedVehiclesButton: w_RscButton
{
idc = -1;
onButtonClick = "[4] execVM 'client\systems\adminPanel\populateVehicles.sqf'";
text = "Vehículos hackeados";
x = 0.462 * safezoneW + safezoneX;
y = 0.715 * safezoneH + safezoneY;
w = 0.085 * safezoneW;
h = 0.040 * safezoneH;
};
class deleteButton: w_RscButton
{
idc = -1;
onButtonClick = "execVM 'client\systems\adminPanel\deleteVehicle.sqf'";
text = "Eliminar vehículo";
x = 0.554 * safezoneW + safezoneX;
y = 0.67 * safezoneH + safezoneY;
w = 0.075 * safezoneW;
h = 0.040 * safezoneH;
color[] = {0.95,0.1,0.1,1};
};
class deleteAllButton: w_RscButton
{
idc = -1;
onButtonClick = "execVM 'client\systems\adminPanel\deleteAllHackedVehicles.sqf'";
text = "Eliminar todo";
x = 0.554 * safezoneW + safezoneX;
y = 0.715 * safezoneH + safezoneY;
w = 0.075 * safezoneW;
h = 0.040 * safezoneH;
color[] = {0.95,0.1,0.1,1};
};
};
};
<|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.
=========================================================================*/
#ifndef __otbPleiadesPToXSAffineTransformCalculator__cxx
#define __otbPleiadesPToXSAffineTransformCalculator__cxx
#include "otbPleiadesPToXSAffineTransformCalculator.h"
#include "otbPleiadesImageMetadataInterface.h"
#include "otbDateTimeAdapter.h"
#include "otbImageKeywordlist.h"
#include "itkMetaDataObject.h"
namespace otb {
bool
PleiadesPToXSAffineTransformCalculator
::CanCompute(const itk::ImageBase<2> * panchromaticImage, const itk::ImageBase<2> * xsImage)
{
bool isPanPHR = false;
bool isXSPHR = false;
otb::PleiadesImageMetadataInterface::Pointer phrIMI =
otb::PleiadesImageMetadataInterface::New();
phrIMI->SetMetaDataDictionary(panchromaticImage->GetMetaDataDictionary());
isPanPHR = phrIMI->CanRead();
phrIMI->SetMetaDataDictionary(xsImage->GetMetaDataDictionary());
isXSPHR = phrIMI->CanRead();
if (isPanPHR && isXSPHR)
{
ImageKeywordlist kwlPan;
ImageKeywordlist kwlXS;
itk::ExposeMetaData<ImageKeywordlist>(
panchromaticImage->GetMetaDataDictionary(),
MetaDataKey::OSSIMKeywordlistKey,
kwlPan);
itk::ExposeMetaData<ImageKeywordlist>(
xsImage->GetMetaDataDictionary(),
MetaDataKey::OSSIMKeywordlistKey,
kwlXS);
// Get geometric processing
std::string panProcessing = kwlPan.GetMetadataByKey("support_data.processing_level");
std::string xsProcessing = kwlXS.GetMetadataByKey("support_data.processing_level");
if (panProcessing.compare("SENSOR") == 0 &&
xsProcessing.compare("SENSOR") == 0)
{
std::string pid = kwlPan.GetMetadataByKey("image_id");
std::string xsid = kwlXS.GetMetadataByKey("image_id");
pid = pid.substr(0,pid.size()-4);
xsid = xsid.substr(0,xsid.size()-4);
if(pid == xsid)
{
return true;
}
}
}
return false;
}
PleiadesPToXSAffineTransformCalculator
::TransformType::Pointer
PleiadesPToXSAffineTransformCalculator
::Compute(const itk::ImageBase<2> * panchromaticImage, const itk::ImageBase<2> * xsImage)
{
if(!CanCompute(panchromaticImage,xsImage))
{
itkGenericExceptionMacro("Can not compute affine transform between images, they do not correspond to Pleiades sensor bundle.");
}
ImageKeywordlist kwlPan;
ImageKeywordlist kwlXS;
itk::ExposeMetaData<ImageKeywordlist>(
panchromaticImage->GetMetaDataDictionary(),
MetaDataKey::OSSIMKeywordlistKey,
kwlPan);
itk::ExposeMetaData<ImageKeywordlist>(
xsImage->GetMetaDataDictionary(),
MetaDataKey::OSSIMKeywordlistKey,
kwlXS);
// Compute time delta
std::string strStartTimePan = kwlPan.GetMetadataByKey("support_data.time_range_start");
std::string strStartTimeXS = kwlXS.GetMetadataByKey("support_data.time_range_start");
DateTimeAdapter::Pointer startTimePan = DateTimeAdapter::New();
DateTimeAdapter::Pointer startTimeXS = DateTimeAdapter::New();
startTimePan->SetFromIso8601(strStartTimePan);
startTimeXS->SetFromIso8601(strStartTimeXS);
double timeDelta = startTimeXS->GetDeltaInSeconds(startTimePan);
// Retrieve line period in Pan
std::string tmpStr = kwlPan.GetMetadataByKey("support_data.line_period");
double linePeriodPan = atof(tmpStr.c_str());
// Retrieve column start
tmpStr = kwlPan.GetMetadataByKey("support_data.swath_first_col");
int colStartPan = atoi(tmpStr.c_str());
tmpStr = kwlXS.GetMetadataByKey("support_data.swath_first_col");
int colStartXS = atoi(tmpStr.c_str());
// Compute shift between MS and P (in Pan pixels)
// in order to keep the top left corners unchanged, apply an
// additional offset of (3/2) panchro pixels, or 0.375 xs pixels
int lineShift_MS_P =int(vcl_floor((timeDelta/(linePeriodPan/1000)) + 0.5)) + 0.375;
int colShift_MS_P = colStartXS*4 - colStartPan-4 + 0.375;
// Apply the scaling
typedef itk::ScalableAffineTransform<double, 2> TransformType;
TransformType::Pointer transform = TransformType::New();
transform->Scale(4.0);
// Apply the offset
TransformType::OutputVectorType offset;
offset[0] = static_cast<double>(colShift_MS_P);
offset[1] = static_cast<double>(lineShift_MS_P);
transform->Translate(offset);
// Invert the transform to get the P to XS transform
TransformType::Pointer realTransform = TransformType::New();
transform->GetInverse(realTransform);
return realTransform;
}
} // End namespace otb
#endif
<commit_msg>ENH: Enhance p to xs registration formula<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.
=========================================================================*/
#ifndef __otbPleiadesPToXSAffineTransformCalculator__cxx
#define __otbPleiadesPToXSAffineTransformCalculator__cxx
#include "otbPleiadesPToXSAffineTransformCalculator.h"
#include "otbPleiadesImageMetadataInterface.h"
#include "otbDateTimeAdapter.h"
#include "otbImageKeywordlist.h"
#include "itkMetaDataObject.h"
namespace otb {
bool
PleiadesPToXSAffineTransformCalculator
::CanCompute(const itk::ImageBase<2> * panchromaticImage, const itk::ImageBase<2> * xsImage)
{
bool isPanPHR = false;
bool isXSPHR = false;
otb::PleiadesImageMetadataInterface::Pointer phrIMI =
otb::PleiadesImageMetadataInterface::New();
phrIMI->SetMetaDataDictionary(panchromaticImage->GetMetaDataDictionary());
isPanPHR = phrIMI->CanRead();
phrIMI->SetMetaDataDictionary(xsImage->GetMetaDataDictionary());
isXSPHR = phrIMI->CanRead();
if (isPanPHR && isXSPHR)
{
ImageKeywordlist kwlPan;
ImageKeywordlist kwlXS;
itk::ExposeMetaData<ImageKeywordlist>(
panchromaticImage->GetMetaDataDictionary(),
MetaDataKey::OSSIMKeywordlistKey,
kwlPan);
itk::ExposeMetaData<ImageKeywordlist>(
xsImage->GetMetaDataDictionary(),
MetaDataKey::OSSIMKeywordlistKey,
kwlXS);
// Get geometric processing
std::string panProcessing = kwlPan.GetMetadataByKey("support_data.processing_level");
std::string xsProcessing = kwlXS.GetMetadataByKey("support_data.processing_level");
if (panProcessing.compare("SENSOR") == 0 &&
xsProcessing.compare("SENSOR") == 0)
{
std::string pid = kwlPan.GetMetadataByKey("image_id");
std::string xsid = kwlXS.GetMetadataByKey("image_id");
pid = pid.substr(0,pid.size()-4);
xsid = xsid.substr(0,xsid.size()-4);
if(pid == xsid)
{
return true;
}
}
}
return false;
}
PleiadesPToXSAffineTransformCalculator
::TransformType::Pointer
PleiadesPToXSAffineTransformCalculator
::Compute(const itk::ImageBase<2> * panchromaticImage, const itk::ImageBase<2> * xsImage)
{
if(!CanCompute(panchromaticImage,xsImage))
{
itkGenericExceptionMacro("Can not compute affine transform between images, they do not correspond to Pleiades sensor bundle.");
}
ImageKeywordlist kwlPan;
ImageKeywordlist kwlXS;
itk::ExposeMetaData<ImageKeywordlist>(
panchromaticImage->GetMetaDataDictionary(),
MetaDataKey::OSSIMKeywordlistKey,
kwlPan);
itk::ExposeMetaData<ImageKeywordlist>(
xsImage->GetMetaDataDictionary(),
MetaDataKey::OSSIMKeywordlistKey,
kwlXS);
// Compute time delta
std::string strStartTimePan = kwlPan.GetMetadataByKey("support_data.time_range_start");
std::string strStartTimeXS = kwlXS.GetMetadataByKey("support_data.time_range_start");
DateTimeAdapter::Pointer startTimePan = DateTimeAdapter::New();
DateTimeAdapter::Pointer startTimeXS = DateTimeAdapter::New();
startTimePan->SetFromIso8601(strStartTimePan);
startTimeXS->SetFromIso8601(strStartTimeXS);
double timeDelta = startTimeXS->GetDeltaInSeconds(startTimePan);
// Retrieve line period in Pan
std::string tmpStr = kwlPan.GetMetadataByKey("support_data.line_period");
double linePeriodPan = atof(tmpStr.c_str());
// Retrieve column start
tmpStr = kwlPan.GetMetadataByKey("support_data.swath_first_col");
int colStartPan = atoi(tmpStr.c_str());
tmpStr = kwlXS.GetMetadataByKey("support_data.swath_first_col");
int colStartXS = atoi(tmpStr.c_str());
// Compute shift between MS and P (in Pan pixels)
// in order to keep the top left corners unchanged, apply an
// additional offset of (3/2) panchro pixels
std::cout<<timeDelta/(linePeriodPan/1000)<<std::endl;
double lineShift_MS_P = (timeDelta/(linePeriodPan/1000))-1.5;
double colShift_MS_P = ((colStartXS)*4 - colStartPan)-1.5;
// Apply the scaling
typedef itk::ScalableAffineTransform<double, 2> TransformType;
TransformType::Pointer transform = TransformType::New();
transform->SetIdentity();
// Apply the offset
TransformType::OutputVectorType offset;
offset[0] = static_cast<double>(colShift_MS_P);
// Y axis inverted
offset[1] = static_cast<double>(-lineShift_MS_P);
transform->Translate(offset);
transform->Scale(0.25);
// Invert the transform to get the P to XS transform
return transform;
}
} // End namespace otb
#endif
<|endoftext|>
|
<commit_before>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "cc/trees/layer_tree_host_common.h"
#include <sstream>
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/memory/scoped_ptr.h"
#include "base/path_service.h"
#include "base/strings/string_piece.h"
#include "base/threading/thread.h"
#include "base/time/time.h"
#include "cc/base/scoped_ptr_deque.h"
#include "cc/base/scoped_ptr_vector.h"
#include "cc/debug/lap_timer.h"
#include "cc/layers/layer.h"
#include "cc/output/bsp_tree.h"
#include "cc/quads/draw_polygon.h"
#include "cc/quads/draw_quad.h"
#include "cc/test/fake_content_layer_client.h"
#include "cc/test/fake_layer_tree_host_client.h"
#include "cc/test/layer_tree_json_parser.h"
#include "cc/test/layer_tree_test.h"
#include "cc/test/paths.h"
#include "cc/trees/layer_tree_impl.h"
#include "testing/perf/perf_test.h"
namespace cc {
namespace {
static const int kTimeLimitMillis = 2000;
static const int kWarmupRuns = 5;
static const int kTimeCheckInterval = 10;
class LayerTreeHostCommonPerfTest : public LayerTreeTest {
public:
LayerTreeHostCommonPerfTest()
: timer_(kWarmupRuns,
base::TimeDelta::FromMilliseconds(kTimeLimitMillis),
kTimeCheckInterval) {}
void ReadTestFile(const std::string& name) {
base::FilePath test_data_dir;
ASSERT_TRUE(PathService::Get(CCPaths::DIR_TEST_DATA, &test_data_dir));
base::FilePath json_file = test_data_dir.AppendASCII(name + ".json");
ASSERT_TRUE(base::ReadFileToString(json_file, &json_));
}
void SetupTree() override {
gfx::Size viewport = gfx::Size(720, 1038);
layer_tree_host()->SetViewportSize(viewport);
scoped_refptr<Layer> root =
ParseTreeFromJson(json_, &content_layer_client_);
ASSERT_TRUE(root.get());
layer_tree_host()->SetRootLayer(root);
}
void SetTestName(const std::string& name) { test_name_ = name; }
void AfterTest() override {
CHECK(!test_name_.empty()) << "Must SetTestName() before TearDown().";
perf_test::PrintResult("calc_draw_props_time",
"",
test_name_,
1000 * timer_.MsPerLap(),
"us",
true);
}
protected:
FakeContentLayerClient content_layer_client_;
LapTimer timer_;
std::string test_name_;
std::string json_;
};
class CalcDrawPropsMainTest : public LayerTreeHostCommonPerfTest {
public:
void RunCalcDrawProps() { RunTest(false, false, false); }
void BeginTest() override {
timer_.Reset();
do {
bool can_render_to_separate_surface = true;
int max_texture_size = 8096;
RenderSurfaceLayerList update_list;
LayerTreeHostCommon::CalcDrawPropsMainInputs inputs(
layer_tree_host()->root_layer(),
layer_tree_host()->device_viewport_size(), gfx::Transform(),
layer_tree_host()->device_scale_factor(),
layer_tree_host()->page_scale_factor(),
layer_tree_host()->overscroll_elasticity_layer(),
layer_tree_host()->elastic_overscroll(),
layer_tree_host()->page_scale_layer(), max_texture_size,
layer_tree_host()->settings().can_use_lcd_text,
layer_tree_host()->settings().layers_always_allowed_lcd_text,
can_render_to_separate_surface,
layer_tree_host()
->settings()
.layer_transforms_should_scale_layer_contents,
layer_tree_host()->settings().verify_property_trees,
&update_list, 0);
LayerTreeHostCommon::CalculateDrawProperties(&inputs);
timer_.NextLap();
} while (!timer_.HasTimeLimitExpired());
EndTest();
}
};
class CalcDrawPropsImplTest : public LayerTreeHostCommonPerfTest {
public:
void RunCalcDrawProps() {
RunTestWithImplSidePainting();
}
void BeginTest() override { PostSetNeedsCommitToMainThread(); }
void DrawLayersOnThread(LayerTreeHostImpl* host_impl) override {
timer_.Reset();
LayerTreeImpl* active_tree = host_impl->active_tree();
do {
bool can_render_to_separate_surface = true;
int max_texture_size = 8096;
DoCalcDrawPropertiesImpl(can_render_to_separate_surface,
max_texture_size,
active_tree,
host_impl);
timer_.NextLap();
} while (!timer_.HasTimeLimitExpired());
EndTest();
}
void DoCalcDrawPropertiesImpl(bool can_render_to_separate_surface,
int max_texture_size,
LayerTreeImpl* active_tree,
LayerTreeHostImpl* host_impl) {
LayerImplList update_list;
LayerTreeHostCommon::CalcDrawPropsImplInputs inputs(
active_tree->root_layer(), active_tree->DrawViewportSize(),
host_impl->DrawTransform(), active_tree->device_scale_factor(),
active_tree->current_page_scale_factor(),
active_tree->InnerViewportContainerLayer(),
active_tree->elastic_overscroll()->Current(active_tree->IsActiveTree()),
active_tree->overscroll_elasticity_layer(), max_texture_size,
host_impl->settings().can_use_lcd_text,
host_impl->settings().layers_always_allowed_lcd_text,
can_render_to_separate_surface,
host_impl->settings().layer_transforms_should_scale_layer_contents,
host_impl->settings().verify_property_trees,
&update_list, 0);
LayerTreeHostCommon::CalculateDrawProperties(&inputs);
}
};
class BspTreePerfTest : public CalcDrawPropsImplTest {
public:
void RunSortLayers() { RunTest(false, false, false); }
void SetNumberOfDuplicates(int num_duplicates) {
num_duplicates_ = num_duplicates;
}
void BeginTest() override { PostSetNeedsCommitToMainThread(); }
void DrawLayersOnThread(LayerTreeHostImpl* host_impl) override {
LayerTreeImpl* active_tree = host_impl->active_tree();
// First build the tree and then we'll start running tests on layersorter
// itself
bool can_render_to_separate_surface = true;
int max_texture_size = 8096;
DoCalcDrawPropertiesImpl(can_render_to_separate_surface,
max_texture_size,
active_tree,
host_impl);
LayerImplList base_list;
BuildLayerImplList(active_tree->root_layer(), &base_list);
int polygon_counter = 0;
ScopedPtrVector<DrawPolygon> polygon_list;
for (LayerImplList::iterator it = base_list.begin(); it != base_list.end();
++it) {
DrawPolygon* draw_polygon =
new DrawPolygon(NULL,
gfx::RectF((*it)->content_bounds()),
(*it)->draw_transform(),
polygon_counter++);
polygon_list.push_back(scoped_ptr<DrawPolygon>(draw_polygon));
}
timer_.Reset();
do {
ScopedPtrDeque<DrawPolygon> test_list;
for (int i = 0; i < num_duplicates_; i++) {
for (size_t i = 0; i < polygon_list.size(); i++) {
test_list.push_back(polygon_list[i]->CreateCopy());
}
}
BspTree bsp_tree(&test_list);
timer_.NextLap();
} while (!timer_.HasTimeLimitExpired());
EndTest();
}
void BuildLayerImplList(LayerImpl* layer, LayerImplList* list) {
if (layer->Is3dSorted()) {
list->push_back(layer);
}
for (size_t i = 0; i < layer->children().size(); i++) {
BuildLayerImplList(layer->children()[i], list);
}
}
private:
LayerImplList base_list_;
int num_duplicates_;
};
TEST_F(CalcDrawPropsMainTest, TenTen) {
SetTestName("10_10_main_thread");
ReadTestFile("10_10_layer_tree");
RunCalcDrawProps();
}
TEST_F(CalcDrawPropsMainTest, HeavyPage) {
SetTestName("heavy_page_main_thread");
ReadTestFile("heavy_layer_tree");
RunCalcDrawProps();
}
TEST_F(CalcDrawPropsMainTest, TouchRegionLight) {
SetTestName("touch_region_light_main_thread");
ReadTestFile("touch_region_light");
RunCalcDrawProps();
}
TEST_F(CalcDrawPropsMainTest, TouchRegionHeavy) {
SetTestName("touch_region_heavy_main_thread");
ReadTestFile("touch_region_heavy");
RunCalcDrawProps();
}
TEST_F(CalcDrawPropsImplTest, TenTen) {
SetTestName("10_10");
ReadTestFile("10_10_layer_tree");
RunCalcDrawProps();
}
TEST_F(CalcDrawPropsImplTest, HeavyPage) {
SetTestName("heavy_page");
ReadTestFile("heavy_layer_tree");
RunCalcDrawProps();
}
TEST_F(CalcDrawPropsImplTest, TouchRegionLight) {
SetTestName("touch_region_light");
ReadTestFile("touch_region_light");
RunCalcDrawProps();
}
TEST_F(CalcDrawPropsImplTest, TouchRegionHeavy) {
SetTestName("touch_region_heavy");
ReadTestFile("touch_region_heavy");
RunCalcDrawProps();
}
TEST_F(BspTreePerfTest, LayerSorterCubes) {
SetTestName("layer_sort_cubes");
ReadTestFile("layer_sort_cubes");
RunSortLayers();
}
TEST_F(BspTreePerfTest, LayerSorterRubik) {
SetTestName("layer_sort_rubik");
ReadTestFile("layer_sort_rubik");
// TODO(vollick): Remove verify_property_trees setting after
// crbug.com/444219 is fixed.
bool old_verify_property_trees = verify_property_trees();
set_verify_property_trees(false);
RunSortLayers();
set_verify_property_trees(old_verify_property_trees);
}
TEST_F(BspTreePerfTest, BspTreeCubes) {
SetTestName("bsp_tree_cubes");
SetNumberOfDuplicates(1);
ReadTestFile("layer_sort_cubes");
RunSortLayers();
}
TEST_F(BspTreePerfTest, BspTreeRubik) {
SetTestName("bsp_tree_rubik");
SetNumberOfDuplicates(1);
ReadTestFile("layer_sort_rubik");
// TODO(vollick): Remove verify_property_trees setting after
// crbug.com/444219 is fixed.
bool old_verify_property_trees = verify_property_trees();
set_verify_property_trees(false);
RunSortLayers();
set_verify_property_trees(old_verify_property_trees);
}
TEST_F(BspTreePerfTest, BspTreeCubes_2) {
SetTestName("bsp_tree_cubes_2");
SetNumberOfDuplicates(2);
ReadTestFile("layer_sort_cubes");
RunSortLayers();
}
TEST_F(BspTreePerfTest, BspTreeCubes_4) {
SetTestName("bsp_tree_cubes_4");
SetNumberOfDuplicates(4);
ReadTestFile("layer_sort_cubes");
RunSortLayers();
}
} // namespace
} // namespace cc
<commit_msg>Uninitialized variable in perftests causing issues on android bots.<commit_after>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "cc/trees/layer_tree_host_common.h"
#include <sstream>
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/memory/scoped_ptr.h"
#include "base/path_service.h"
#include "base/strings/string_piece.h"
#include "base/threading/thread.h"
#include "base/time/time.h"
#include "cc/base/scoped_ptr_deque.h"
#include "cc/base/scoped_ptr_vector.h"
#include "cc/debug/lap_timer.h"
#include "cc/layers/layer.h"
#include "cc/output/bsp_tree.h"
#include "cc/quads/draw_polygon.h"
#include "cc/quads/draw_quad.h"
#include "cc/test/fake_content_layer_client.h"
#include "cc/test/fake_layer_tree_host_client.h"
#include "cc/test/layer_tree_json_parser.h"
#include "cc/test/layer_tree_test.h"
#include "cc/test/paths.h"
#include "cc/trees/layer_tree_impl.h"
#include "testing/perf/perf_test.h"
namespace cc {
namespace {
static const int kTimeLimitMillis = 2000;
static const int kWarmupRuns = 5;
static const int kTimeCheckInterval = 10;
class LayerTreeHostCommonPerfTest : public LayerTreeTest {
public:
LayerTreeHostCommonPerfTest()
: timer_(kWarmupRuns,
base::TimeDelta::FromMilliseconds(kTimeLimitMillis),
kTimeCheckInterval) {}
void ReadTestFile(const std::string& name) {
base::FilePath test_data_dir;
ASSERT_TRUE(PathService::Get(CCPaths::DIR_TEST_DATA, &test_data_dir));
base::FilePath json_file = test_data_dir.AppendASCII(name + ".json");
ASSERT_TRUE(base::ReadFileToString(json_file, &json_));
}
void SetupTree() override {
gfx::Size viewport = gfx::Size(720, 1038);
layer_tree_host()->SetViewportSize(viewport);
scoped_refptr<Layer> root =
ParseTreeFromJson(json_, &content_layer_client_);
ASSERT_TRUE(root.get());
layer_tree_host()->SetRootLayer(root);
}
void SetTestName(const std::string& name) { test_name_ = name; }
void AfterTest() override {
CHECK(!test_name_.empty()) << "Must SetTestName() before TearDown().";
perf_test::PrintResult("calc_draw_props_time",
"",
test_name_,
1000 * timer_.MsPerLap(),
"us",
true);
}
protected:
FakeContentLayerClient content_layer_client_;
LapTimer timer_;
std::string test_name_;
std::string json_;
};
class CalcDrawPropsMainTest : public LayerTreeHostCommonPerfTest {
public:
void RunCalcDrawProps() { RunTest(false, false, false); }
void BeginTest() override {
timer_.Reset();
do {
bool can_render_to_separate_surface = true;
int max_texture_size = 8096;
RenderSurfaceLayerList update_list;
LayerTreeHostCommon::CalcDrawPropsMainInputs inputs(
layer_tree_host()->root_layer(),
layer_tree_host()->device_viewport_size(), gfx::Transform(),
layer_tree_host()->device_scale_factor(),
layer_tree_host()->page_scale_factor(),
layer_tree_host()->overscroll_elasticity_layer(),
layer_tree_host()->elastic_overscroll(),
layer_tree_host()->page_scale_layer(), max_texture_size,
layer_tree_host()->settings().can_use_lcd_text,
layer_tree_host()->settings().layers_always_allowed_lcd_text,
can_render_to_separate_surface,
layer_tree_host()
->settings()
.layer_transforms_should_scale_layer_contents,
layer_tree_host()->settings().verify_property_trees,
&update_list, 0);
LayerTreeHostCommon::CalculateDrawProperties(&inputs);
timer_.NextLap();
} while (!timer_.HasTimeLimitExpired());
EndTest();
}
};
class CalcDrawPropsImplTest : public LayerTreeHostCommonPerfTest {
public:
void RunCalcDrawProps() {
RunTestWithImplSidePainting();
}
void BeginTest() override { PostSetNeedsCommitToMainThread(); }
void DrawLayersOnThread(LayerTreeHostImpl* host_impl) override {
timer_.Reset();
LayerTreeImpl* active_tree = host_impl->active_tree();
do {
bool can_render_to_separate_surface = true;
int max_texture_size = 8096;
DoCalcDrawPropertiesImpl(can_render_to_separate_surface,
max_texture_size,
active_tree,
host_impl);
timer_.NextLap();
} while (!timer_.HasTimeLimitExpired());
EndTest();
}
void DoCalcDrawPropertiesImpl(bool can_render_to_separate_surface,
int max_texture_size,
LayerTreeImpl* active_tree,
LayerTreeHostImpl* host_impl) {
LayerImplList update_list;
LayerTreeHostCommon::CalcDrawPropsImplInputs inputs(
active_tree->root_layer(), active_tree->DrawViewportSize(),
host_impl->DrawTransform(), active_tree->device_scale_factor(),
active_tree->current_page_scale_factor(),
active_tree->InnerViewportContainerLayer(),
active_tree->elastic_overscroll()->Current(active_tree->IsActiveTree()),
active_tree->overscroll_elasticity_layer(), max_texture_size,
host_impl->settings().can_use_lcd_text,
host_impl->settings().layers_always_allowed_lcd_text,
can_render_to_separate_surface,
host_impl->settings().layer_transforms_should_scale_layer_contents,
host_impl->settings().verify_property_trees,
&update_list, 0);
LayerTreeHostCommon::CalculateDrawProperties(&inputs);
}
};
class BspTreePerfTest : public CalcDrawPropsImplTest {
public:
BspTreePerfTest() : num_duplicates_(1) {}
void RunSortLayers() { RunTest(false, false, false); }
void SetNumberOfDuplicates(int num_duplicates) {
num_duplicates_ = num_duplicates;
}
void BeginTest() override { PostSetNeedsCommitToMainThread(); }
void DrawLayersOnThread(LayerTreeHostImpl* host_impl) override {
LayerTreeImpl* active_tree = host_impl->active_tree();
// First build the tree and then we'll start running tests on layersorter
// itself
bool can_render_to_separate_surface = true;
int max_texture_size = 8096;
DoCalcDrawPropertiesImpl(can_render_to_separate_surface,
max_texture_size,
active_tree,
host_impl);
LayerImplList base_list;
BuildLayerImplList(active_tree->root_layer(), &base_list);
int polygon_counter = 0;
ScopedPtrVector<DrawPolygon> polygon_list;
for (LayerImplList::iterator it = base_list.begin(); it != base_list.end();
++it) {
DrawPolygon* draw_polygon =
new DrawPolygon(NULL,
gfx::RectF((*it)->content_bounds()),
(*it)->draw_transform(),
polygon_counter++);
polygon_list.push_back(scoped_ptr<DrawPolygon>(draw_polygon));
}
timer_.Reset();
do {
ScopedPtrDeque<DrawPolygon> test_list;
for (int i = 0; i < num_duplicates_; i++) {
for (size_t i = 0; i < polygon_list.size(); i++) {
test_list.push_back(polygon_list[i]->CreateCopy());
}
}
BspTree bsp_tree(&test_list);
timer_.NextLap();
} while (!timer_.HasTimeLimitExpired());
EndTest();
}
void BuildLayerImplList(LayerImpl* layer, LayerImplList* list) {
if (layer->Is3dSorted()) {
list->push_back(layer);
}
for (size_t i = 0; i < layer->children().size(); i++) {
BuildLayerImplList(layer->children()[i], list);
}
}
private:
LayerImplList base_list_;
int num_duplicates_;
};
TEST_F(CalcDrawPropsMainTest, TenTen) {
SetTestName("10_10_main_thread");
ReadTestFile("10_10_layer_tree");
RunCalcDrawProps();
}
TEST_F(CalcDrawPropsMainTest, HeavyPage) {
SetTestName("heavy_page_main_thread");
ReadTestFile("heavy_layer_tree");
RunCalcDrawProps();
}
TEST_F(CalcDrawPropsMainTest, TouchRegionLight) {
SetTestName("touch_region_light_main_thread");
ReadTestFile("touch_region_light");
RunCalcDrawProps();
}
TEST_F(CalcDrawPropsMainTest, TouchRegionHeavy) {
SetTestName("touch_region_heavy_main_thread");
ReadTestFile("touch_region_heavy");
RunCalcDrawProps();
}
TEST_F(CalcDrawPropsImplTest, TenTen) {
SetTestName("10_10");
ReadTestFile("10_10_layer_tree");
RunCalcDrawProps();
}
TEST_F(CalcDrawPropsImplTest, HeavyPage) {
SetTestName("heavy_page");
ReadTestFile("heavy_layer_tree");
RunCalcDrawProps();
}
TEST_F(CalcDrawPropsImplTest, TouchRegionLight) {
SetTestName("touch_region_light");
ReadTestFile("touch_region_light");
RunCalcDrawProps();
}
TEST_F(CalcDrawPropsImplTest, TouchRegionHeavy) {
SetTestName("touch_region_heavy");
ReadTestFile("touch_region_heavy");
RunCalcDrawProps();
}
TEST_F(BspTreePerfTest, LayerSorterCubes) {
SetTestName("layer_sort_cubes");
ReadTestFile("layer_sort_cubes");
RunSortLayers();
}
TEST_F(BspTreePerfTest, LayerSorterRubik) {
SetTestName("layer_sort_rubik");
ReadTestFile("layer_sort_rubik");
// TODO(vollick): Remove verify_property_trees setting after
// crbug.com/444219 is fixed.
bool old_verify_property_trees = verify_property_trees();
set_verify_property_trees(false);
RunSortLayers();
set_verify_property_trees(old_verify_property_trees);
}
TEST_F(BspTreePerfTest, BspTreeCubes) {
SetTestName("bsp_tree_cubes");
SetNumberOfDuplicates(1);
ReadTestFile("layer_sort_cubes");
RunSortLayers();
}
TEST_F(BspTreePerfTest, BspTreeRubik) {
SetTestName("bsp_tree_rubik");
SetNumberOfDuplicates(1);
ReadTestFile("layer_sort_rubik");
// TODO(vollick): Remove verify_property_trees setting after
// crbug.com/444219 is fixed.
bool old_verify_property_trees = verify_property_trees();
set_verify_property_trees(false);
RunSortLayers();
set_verify_property_trees(old_verify_property_trees);
}
TEST_F(BspTreePerfTest, BspTreeCubes_2) {
SetTestName("bsp_tree_cubes_2");
SetNumberOfDuplicates(2);
ReadTestFile("layer_sort_cubes");
RunSortLayers();
}
TEST_F(BspTreePerfTest, BspTreeCubes_4) {
SetTestName("bsp_tree_cubes_4");
SetNumberOfDuplicates(4);
ReadTestFile("layer_sort_cubes");
RunSortLayers();
}
} // namespace
} // namespace cc
<|endoftext|>
|
<commit_before>#ifndef __COMMAND_AND_CALLBACK_STRUCT_HPP_INCLUDED
#define __COMMAND_AND_CALLBACK_STRUCT_HPP_INCLUDED
#include "code/ylikuutio/callback_system/callback_engine.hpp"
// Include standard headers
#include <string> // std::string
typedef struct
{
std::string command;
yli::callback_system::CallbackEngine* callback_engine;
} CommandAndCallbackStruct;
#endif
<commit_msg>Replace unnecessary `#include` line with a forward declaration.<commit_after>#ifndef __COMMAND_AND_CALLBACK_STRUCT_HPP_INCLUDED
#define __COMMAND_AND_CALLBACK_STRUCT_HPP_INCLUDED
// Include standard headers
#include <string> // std::string
namespace yli
{
namespace callback_system
{
class CallbackEngine;
}
}
typedef struct
{
std::string command;
yli::callback_system::CallbackEngine* callback_engine;
} CommandAndCallbackStruct;
#endif
<|endoftext|>
|
<commit_before>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// 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 "../lest/include/lest/lest.hpp"
#include "../../cookie/cookie_jar.cpp"
#include "../../cookie/cookie.cpp"
using namespace std;
using namespace cookie;
const lest::test test_cookie_jar[] =
{
SCENARIO("Cookies can be inserted into and erased from a CookieJar")
{
GIVEN("A CookieJar")
{
/* TODO: Not working when declared the CookieJar here for some reason:
CookieJar jar{};
EXPECT(jar.empty());
EXPECT(jar.size() == 0u);*/
WHEN("Inserting a Cookie into a CookieJar")
{
// TODO Moved here to make it work:
CookieJar jar{};
EXPECT(jar.empty());
EXPECT(jar.size() == 0u);
// Until here
Cookie c{"name", "value"};
EXPECT(jar.insert(c));
THEN("The CookieJar contains the cookie")
{
EXPECT_NOT(jar.empty());
EXPECT(jar.size() == 1u);
EXPECT(jar.find("name") == "value");
EXPECT(jar.exists("name"));
}
AND_WHEN("Erasing the inserted Cookie from the CookieJar")
{
EXPECT_NOT(jar.empty());
jar.erase(c);
THEN("The CookieJar does not contain the Cookie")
{
EXPECT(jar.empty());
EXPECT(jar.size() == 0u);
EXPECT(jar.find("name") == "");
EXPECT_NOT(jar.exists("name"));
}
}
}
WHEN("Inserting three Cookies into a CookieJar by inserting name and value")
{
// TODO Moved here to make it work:
CookieJar jar{};
EXPECT(jar.empty());
EXPECT(jar.size() == 0u);
// Until here
EXPECT(jar.insert("another_name", "another_value"));
THEN("The CookieJar contains a Cookie with this name and value")
{
EXPECT_NOT(jar.empty());
EXPECT(jar.size() == 1u);
EXPECT(jar.find("another_name") == "another_value");
EXPECT(jar.exists("another_name"));
}
EXPECT(jar.insert("a_cookie_name", "a_cookie_value"));
THEN("The CookieJar contains both Cookies")
{
EXPECT_NOT(jar.empty());
EXPECT(jar.size() == 2u);
EXPECT(jar.find("another_name") == "another_value");
EXPECT(jar.find("a_cookie_name") == "a_cookie_value");
EXPECT(jar.exists("another_name"));
EXPECT(jar.exists("a_cookie_name"));
}
EXPECT(jar.insert("a_third_cookie_name", "a_third_cookie_value"));
THEN("The CookieJar contains three Cookies")
{
EXPECT_NOT(jar.empty());
EXPECT(jar.size() == 3u);
EXPECT(jar.find("another_name") == "another_value");
EXPECT(jar.find("a_cookie_name") == "a_cookie_value");
EXPECT(jar.find("a_third_cookie_name") == "a_third_cookie_value");
EXPECT(jar.exists("another_name"));
EXPECT(jar.exists("a_cookie_name"));
EXPECT(jar.exists("a_third_cookie_name"));
}
AND_WHEN("Erasing one of the Cookies from the CookieJar by name")
{
EXPECT_NOT(jar.empty());
jar.erase("a_cookie_name");
THEN("The CookieJar contains only the other two Cookies")
{
EXPECT_NOT(jar.empty());
EXPECT(jar.size() == 2u);
EXPECT(jar.find("another_name") == "another_value");
EXPECT(jar.find("a_third_cookie_name") == "a_third_cookie_value");
EXPECT_NOT(jar.find("a_cookie_name") == "a_cookie_value");
EXPECT(jar.exists("another_name"));
EXPECT(jar.exists("a_third_cookie_name"));
EXPECT_NOT(jar.exists("a_cookie_name"));
}
}
AND_WHEN("Clearing the whole CookieJar")
{
EXPECT_NOT(jar.empty());
EXPECT(jar.size() == 3u);
jar.clear();
THEN("The CookieJar is empty")
{
EXPECT(jar.empty());
EXPECT(jar.size() == 0u);
EXPECT(jar.find("another_name") == "");
EXPECT_NOT(jar.exists("a_third_cookie_name"));
}
}
AND_WHEN("Getting all the cookies that the CookieJar contains")
{
map<string, string> all_cookies = jar.get_cookies();
THEN("The existing Cookies are returned in a map")
{
EXPECT_NOT(all_cookies.empty());
EXPECT(all_cookies.size() == 3u);
EXPECT(all_cookies.find("another_name") not_eq all_cookies.end());
EXPECT(all_cookies.find("a_cookie_name") not_eq all_cookies.end());
EXPECT(all_cookies.find("a_third_cookie_name") not_eq all_cookies.end());
EXPECT(all_cookies.find("not_existing_cookie") == all_cookies.end());
}
}
}
}
},
SCENARIO("A CookieJar can return an iterator to its first and last element")
{
GIVEN("A CookieJar")
{
CookieJar jar{};
WHEN("Inserting three Cookies into the CookieJar")
{
jar.insert("name", "value");
jar.insert("another_name", "another_value");
jar.insert("a_third_name", "a_third_value");
EXPECT(jar.size() == 3u);
THEN("Get an iterator to the first Cookie")
{
auto it = jar.begin();
EXPECT( (it not_eq jar.end() && (++it) not_eq jar.end()) );
++it;
EXPECT( (it not_eq jar.end() && (++it) == jar.end()) );
}
THEN("Get an iterator to the last Cookie")
{
auto it = jar.end();
EXPECT( (it not_eq jar.begin() && (--it) not_eq jar.begin()) );
--it;
EXPECT( (it not_eq jar.begin() && (--it) == jar.begin()) );
}
}
WHEN("Inserting one Cookie into the CookieJar")
{
jar.insert("name", "value");
EXPECT(jar.size() == 1u);
THEN("Get an iterator to the first Cookie")
{
auto it = jar.begin();
EXPECT( (it not_eq jar.end() && (++it) == jar.end()) );
}
THEN("Get an iterator to the last Cookie")
{
auto it = jar.end();
EXPECT( (it not_eq jar.begin() && (--it) == jar.begin()) );
}
}
}
}
};
int main(int argc, char * argv[])
{
printf("Running CookieJar-tests...\n");
int res = lest::run(test_cookie_jar, argc, argv);
printf("CookieJar-tests completed.\n");
return res;
}
<commit_msg>Modified includes in cookie_jar_test.cpp<commit_after>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// 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 "../../cookie/cookie_jar.hpp"
#include "../lest/include/lest/lest.hpp"
using namespace std;
using namespace cookie;
const lest::test test_cookie_jar[] =
{
SCENARIO("Cookies can be inserted into and erased from a CookieJar")
{
GIVEN("A CookieJar")
{
/* TODO: Not working when declared the CookieJar here for some reason:
CookieJar jar{};
EXPECT(jar.empty());
EXPECT(jar.size() == 0u);*/
WHEN("Inserting a Cookie into a CookieJar")
{
// TODO Moved here to make it work:
CookieJar jar{};
EXPECT(jar.empty());
EXPECT(jar.size() == 0u);
// Until here
Cookie c{"name", "value"};
EXPECT(jar.insert(c));
THEN("The CookieJar contains the cookie")
{
EXPECT_NOT(jar.empty());
EXPECT(jar.size() == 1u);
EXPECT(jar.find("name") == "value");
EXPECT(jar.exists("name"));
}
AND_WHEN("Erasing the inserted Cookie from the CookieJar")
{
EXPECT_NOT(jar.empty());
jar.erase(c);
THEN("The CookieJar does not contain the Cookie")
{
EXPECT(jar.empty());
EXPECT(jar.size() == 0u);
EXPECT(jar.find("name") == "");
EXPECT_NOT(jar.exists("name"));
}
}
}
WHEN("Inserting three Cookies into a CookieJar by inserting name and value")
{
// TODO Moved here to make it work:
CookieJar jar{};
EXPECT(jar.empty());
EXPECT(jar.size() == 0u);
// Until here
EXPECT(jar.insert("another_name", "another_value"));
THEN("The CookieJar contains a Cookie with this name and value")
{
EXPECT_NOT(jar.empty());
EXPECT(jar.size() == 1u);
EXPECT(jar.find("another_name") == "another_value");
EXPECT(jar.exists("another_name"));
}
EXPECT(jar.insert("a_cookie_name", "a_cookie_value"));
THEN("The CookieJar contains both Cookies")
{
EXPECT_NOT(jar.empty());
EXPECT(jar.size() == 2u);
EXPECT(jar.find("another_name") == "another_value");
EXPECT(jar.find("a_cookie_name") == "a_cookie_value");
EXPECT(jar.exists("another_name"));
EXPECT(jar.exists("a_cookie_name"));
}
EXPECT(jar.insert("a_third_cookie_name", "a_third_cookie_value"));
THEN("The CookieJar contains three Cookies")
{
EXPECT_NOT(jar.empty());
EXPECT(jar.size() == 3u);
EXPECT(jar.find("another_name") == "another_value");
EXPECT(jar.find("a_cookie_name") == "a_cookie_value");
EXPECT(jar.find("a_third_cookie_name") == "a_third_cookie_value");
EXPECT(jar.exists("another_name"));
EXPECT(jar.exists("a_cookie_name"));
EXPECT(jar.exists("a_third_cookie_name"));
}
AND_WHEN("Erasing one of the Cookies from the CookieJar by name")
{
EXPECT_NOT(jar.empty());
jar.erase("a_cookie_name");
THEN("The CookieJar contains only the other two Cookies")
{
EXPECT_NOT(jar.empty());
EXPECT(jar.size() == 2u);
EXPECT(jar.find("another_name") == "another_value");
EXPECT(jar.find("a_third_cookie_name") == "a_third_cookie_value");
EXPECT_NOT(jar.find("a_cookie_name") == "a_cookie_value");
EXPECT(jar.exists("another_name"));
EXPECT(jar.exists("a_third_cookie_name"));
EXPECT_NOT(jar.exists("a_cookie_name"));
}
}
AND_WHEN("Clearing the whole CookieJar")
{
EXPECT_NOT(jar.empty());
EXPECT(jar.size() == 3u);
jar.clear();
THEN("The CookieJar is empty")
{
EXPECT(jar.empty());
EXPECT(jar.size() == 0u);
EXPECT(jar.find("another_name") == "");
EXPECT_NOT(jar.exists("a_third_cookie_name"));
}
}
AND_WHEN("Getting all the cookies that the CookieJar contains")
{
map<string, string> all_cookies = jar.get_cookies();
THEN("The existing Cookies are returned in a map")
{
EXPECT_NOT(all_cookies.empty());
EXPECT(all_cookies.size() == 3u);
EXPECT(all_cookies.find("another_name") not_eq all_cookies.end());
EXPECT(all_cookies.find("a_cookie_name") not_eq all_cookies.end());
EXPECT(all_cookies.find("a_third_cookie_name") not_eq all_cookies.end());
EXPECT(all_cookies.find("not_existing_cookie") == all_cookies.end());
}
}
}
}
},
SCENARIO("A CookieJar can return an iterator to its first and last element")
{
GIVEN("A CookieJar")
{
CookieJar jar{};
WHEN("Inserting three Cookies into the CookieJar")
{
jar.insert("name", "value");
jar.insert("another_name", "another_value");
jar.insert("a_third_name", "a_third_value");
EXPECT(jar.size() == 3u);
THEN("Get an iterator to the first Cookie")
{
auto it = jar.begin();
EXPECT( (it not_eq jar.end() && (++it) not_eq jar.end()) );
++it;
EXPECT( (it not_eq jar.end() && (++it) == jar.end()) );
}
THEN("Get an iterator to the last Cookie")
{
auto it = jar.end();
EXPECT( (it not_eq jar.begin() && (--it) not_eq jar.begin()) );
--it;
EXPECT( (it not_eq jar.begin() && (--it) == jar.begin()) );
}
}
WHEN("Inserting one Cookie into the CookieJar")
{
jar.insert("name", "value");
EXPECT(jar.size() == 1u);
THEN("Get an iterator to the first Cookie")
{
auto it = jar.begin();
EXPECT( (it not_eq jar.end() && (++it) == jar.end()) );
}
THEN("Get an iterator to the last Cookie")
{
auto it = jar.end();
EXPECT( (it not_eq jar.begin() && (--it) == jar.begin()) );
}
}
}
}
};
int main(int argc, char * argv[])
{
printf("Running CookieJar-tests...\n");
int res = lest::run(test_cookie_jar, argc, argv);
printf("CookieJar-tests completed.\n");
return res;
}
<|endoftext|>
|
<commit_before>/*
*
* Copyright 2016, Google 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 Google 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.
*
*/
#include "test/cpp/util/grpc_tool.h"
#include <sstream>
#include <gflags/gflags.h>
#include <grpc++/channel.h>
#include <grpc++/client_context.h>
#include <grpc++/create_channel.h>
#include <grpc++/ext/proto_server_reflection_plugin.h>
#include <grpc++/server.h>
#include <grpc++/server_builder.h>
#include <grpc++/server_context.h>
#include <grpc/grpc.h>
#include <gtest/gtest.h>
#include "src/proto/grpc/testing/echo.grpc.pb.h"
#include "src/proto/grpc/testing/echo.pb.h"
#include "test/core/util/port.h"
#include "test/core/util/test_config.h"
#include "test/cpp/util/cli_credentials.h"
#include "test/cpp/util/string_ref_helper.h"
using grpc::testing::EchoRequest;
using grpc::testing::EchoResponse;
#define USAGE_REGEX "( grpc_cli .+\n){2,10}"
#define ECHO_TEST_SERVICE_SUMMARY \
"Echo\n" \
"RequestStream\n" \
"ResponseStream\n" \
"BidiStream\n" \
"Unimplemented\n"
#define ECHO_TEST_SERVICE_DESCRIPTION \
"filename: src/proto/grpc/testing/echo.proto\n" \
"package: grpc.testing;\n" \
"service EchoTestService {\n" \
" rpc Echo(grpc.testing.EchoRequest) returns (grpc.testing.EchoResponse) " \
"{}\n" \
" rpc RequestStream(stream grpc.testing.EchoRequest) returns " \
"(grpc.testing.EchoResponse) {}\n" \
" rpc ResponseStream(grpc.testing.EchoRequest) returns (stream " \
"grpc.testing.EchoResponse) {}\n" \
" rpc BidiStream(stream grpc.testing.EchoRequest) returns (stream " \
"grpc.testing.EchoResponse) {}\n" \
" rpc Unimplemented(grpc.testing.EchoRequest) returns " \
"(grpc.testing.EchoResponse) {}\n" \
"}\n" \
"\n"
#define ECHO_METHOD_DESCRIPTION \
" rpc Echo(grpc.testing.EchoRequest) returns (grpc.testing.EchoResponse) " \
"{}\n"
namespace grpc {
namespace testing {
DECLARE_bool(l);
namespace {
class TestCliCredentials final : public grpc::testing::CliCredentials {
public:
std::shared_ptr<grpc::ChannelCredentials> GetCredentials() const override {
return InsecureChannelCredentials();
}
const grpc::string GetCredentialUsage() const override { return ""; }
};
bool PrintStream(std::stringstream* ss, const grpc::string& output) {
(*ss) << output;
return true;
}
template <typename T>
size_t ArraySize(T& a) {
return ((sizeof(a) / sizeof(*(a))) /
static_cast<size_t>(!(sizeof(a) % sizeof(*(a)))));
}
} // namespame
class TestServiceImpl : public ::grpc::testing::EchoTestService::Service {
public:
Status Echo(ServerContext* context, const EchoRequest* request,
EchoResponse* response) override {
if (!context->client_metadata().empty()) {
for (std::multimap<grpc::string_ref, grpc::string_ref>::const_iterator
iter = context->client_metadata().begin();
iter != context->client_metadata().end(); ++iter) {
context->AddInitialMetadata(ToString(iter->first),
ToString(iter->second));
}
}
context->AddTrailingMetadata("trailing_key", "trailing_value");
response->set_message(request->message());
return Status::OK;
}
};
class GrpcToolTest : public ::testing::Test {
protected:
GrpcToolTest() {}
// SetUpServer cannot be used with EXPECT_EXIT. grpc_pick_unused_port_or_die()
// uses atexit() to free chosen ports, and it will spawn a new thread in
// resolve_address_posix.c:192 at exit time.
const grpc::string SetUpServer() {
std::ostringstream server_address;
int port = grpc_pick_unused_port_or_die();
server_address << "localhost:" << port;
// Setup server
ServerBuilder builder;
builder.AddListeningPort(server_address.str(), InsecureServerCredentials());
builder.RegisterService(&service_);
server_ = builder.BuildAndStart();
return server_address.str();
}
void ShutdownServer() { server_->Shutdown(); }
void ExitWhenError(int argc, const char** argv, const CliCredentials& cred,
GrpcToolOutputCallback callback) {
int result = GrpcToolMainLib(argc, argv, cred, callback);
if (result) {
exit(result);
}
}
std::unique_ptr<Server> server_;
TestServiceImpl service_;
reflection::ProtoServerReflectionPlugin plugin_;
};
TEST_F(GrpcToolTest, NoCommand) {
// Test input "grpc_cli"
std::stringstream output_stream;
const char* argv[] = {"grpc_cli"};
// Exit with 1, print usage instruction in stderr
EXPECT_EXIT(
GrpcToolMainLib(
ArraySize(argv), argv, TestCliCredentials(),
std::bind(PrintStream, &output_stream, std::placeholders::_1)),
::testing::ExitedWithCode(1), "No command specified\n" USAGE_REGEX);
// No output
EXPECT_TRUE(0 == output_stream.tellp());
}
TEST_F(GrpcToolTest, InvalidCommand) {
// Test input "grpc_cli"
std::stringstream output_stream;
const char* argv[] = {"grpc_cli", "abc"};
// Exit with 1, print usage instruction in stderr
EXPECT_EXIT(
GrpcToolMainLib(
ArraySize(argv), argv, TestCliCredentials(),
std::bind(PrintStream, &output_stream, std::placeholders::_1)),
::testing::ExitedWithCode(1), "Invalid command 'abc'\n" USAGE_REGEX);
// No output
EXPECT_TRUE(0 == output_stream.tellp());
}
TEST_F(GrpcToolTest, HelpCommand) {
// Test input "grpc_cli help"
std::stringstream output_stream;
const char* argv[] = {"grpc_cli", "help"};
// Exit with 1, print usage instruction in stderr
EXPECT_EXIT(GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(),
std::bind(PrintStream, &output_stream,
std::placeholders::_1)),
::testing::ExitedWithCode(1), USAGE_REGEX);
// No output
EXPECT_TRUE(0 == output_stream.tellp());
}
TEST_F(GrpcToolTest, ListCommand) {
// Test input "grpc_cli list localhost:<port>"
std::stringstream output_stream;
const grpc::string server_address = SetUpServer();
const char* argv[] = {"grpc_cli", "ls", server_address.c_str()};
FLAGS_l = false;
EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(),
std::bind(PrintStream, &output_stream,
std::placeholders::_1)));
EXPECT_TRUE(0 == strcmp(output_stream.str().c_str(),
"grpc.testing.EchoTestService\n"
"grpc.reflection.v1alpha.ServerReflection\n"));
ShutdownServer();
}
TEST_F(GrpcToolTest, ListOneService) {
// Test input "grpc_cli list localhost:<port> grpc.testing.EchoTestService"
std::stringstream output_stream;
const grpc::string server_address = SetUpServer();
const char* argv[] = {"grpc_cli", "ls", server_address.c_str(),
"grpc.testing.EchoTestService"};
// without -l flag
FLAGS_l = false;
EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(),
std::bind(PrintStream, &output_stream,
std::placeholders::_1)));
// Expected output: ECHO_TEST_SERVICE_SUMMARY
EXPECT_TRUE(0 ==
strcmp(output_stream.str().c_str(), ECHO_TEST_SERVICE_SUMMARY));
// with -l flag
output_stream.str(grpc::string());
output_stream.clear();
FLAGS_l = true;
EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(),
std::bind(PrintStream, &output_stream,
std::placeholders::_1)));
// Expected output: ECHO_TEST_SERVICE_DESCRIPTION
EXPECT_TRUE(
0 == strcmp(output_stream.str().c_str(), ECHO_TEST_SERVICE_DESCRIPTION));
ShutdownServer();
}
TEST_F(GrpcToolTest, TypeCommand) {
// Test input "grpc_cli type localhost:<port> grpc.testing.EchoRequest"
std::stringstream output_stream;
const grpc::string server_address = SetUpServer();
const char* argv[] = {"grpc_cli", "type", server_address.c_str(),
"grpc.testing.EchoRequest"};
EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(),
std::bind(PrintStream, &output_stream,
std::placeholders::_1)));
const grpc::protobuf::Descriptor* desc =
grpc::protobuf::DescriptorPool::generated_pool()->FindMessageTypeByName(
"grpc.testing.EchoRequest");
// Expected output: the DebugString of grpc.testing.EchoRequest
EXPECT_TRUE(0 ==
strcmp(output_stream.str().c_str(), desc->DebugString().c_str()));
ShutdownServer();
}
TEST_F(GrpcToolTest, ListOneMethod) {
// Test input "grpc_cli list localhost:<port> grpc.testing.EchoTestService"
std::stringstream output_stream;
const grpc::string server_address = SetUpServer();
const char* argv[] = {"grpc_cli", "ls", server_address.c_str(),
"grpc.testing.EchoTestService.Echo"};
// without -l flag
FLAGS_l = false;
EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(),
std::bind(PrintStream, &output_stream,
std::placeholders::_1)));
// Expected output: "Echo"
EXPECT_TRUE(0 == strcmp(output_stream.str().c_str(), "Echo\n"));
// with -l flag
output_stream.str(grpc::string());
output_stream.clear();
FLAGS_l = true;
EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(),
std::bind(PrintStream, &output_stream,
std::placeholders::_1)));
// Expected output: ECHO_METHOD_DESCRIPTION
EXPECT_TRUE(0 ==
strcmp(output_stream.str().c_str(), ECHO_METHOD_DESCRIPTION));
ShutdownServer();
}
TEST_F(GrpcToolTest, TypeNotFound) {
// Test input "grpc_cli type localhost:<port> grpc.testing.DummyRequest"
std::stringstream output_stream;
const grpc::string server_address = SetUpServer();
const char* argv[] = {"grpc_cli", "type", server_address.c_str(),
"grpc.testing.DummyRequest"};
EXPECT_DEATH(ExitWhenError(ArraySize(argv), argv, TestCliCredentials(),
std::bind(PrintStream, &output_stream,
std::placeholders::_1)),
".*Type grpc.testing.DummyRequest not found.*");
ShutdownServer();
}
TEST_F(GrpcToolTest, CallCommand) {
// Test input "grpc_cli call localhost:<port> Echo "message: 'Hello'"
std::stringstream output_stream;
const grpc::string server_address = SetUpServer();
const char* argv[] = {"grpc_cli", "call", server_address.c_str(), "Echo",
"message: 'Hello'"};
EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(),
std::bind(PrintStream, &output_stream,
std::placeholders::_1)));
// Expected output: "message: \"Hello\""
EXPECT_TRUE(NULL !=
strstr(output_stream.str().c_str(), "message: \"Hello\""));
ShutdownServer();
}
TEST_F(GrpcToolTest, TooFewArguments) {
// Test input "grpc_cli call Echo"
std::stringstream output_stream;
const char* argv[] = {"grpc_cli", "call", "Echo"};
// Exit with 1
EXPECT_EXIT(
GrpcToolMainLib(
ArraySize(argv), argv, TestCliCredentials(),
std::bind(PrintStream, &output_stream, std::placeholders::_1)),
::testing::ExitedWithCode(1), ".*Wrong number of arguments for call.*");
// No output
EXPECT_TRUE(0 == output_stream.tellp());
}
TEST_F(GrpcToolTest, TooManyArguments) {
// Test input "grpc_cli call localhost:<port> Echo Echo "message: 'Hello'"
std::stringstream output_stream;
const char* argv[] = {"grpc_cli", "call", "localhost:10000",
"Echo", "Echo", "message: 'Hello'"};
// Exit with 1
EXPECT_EXIT(
GrpcToolMainLib(
ArraySize(argv), argv, TestCliCredentials(),
std::bind(PrintStream, &output_stream, std::placeholders::_1)),
::testing::ExitedWithCode(1), ".*Wrong number of arguments for call.*");
// No output
EXPECT_TRUE(0 == output_stream.tellp());
}
} // namespace testing
} // namespace grpc
int main(int argc, char** argv) {
grpc_test_init(argc, argv);
::testing::InitGoogleTest(&argc, argv);
::testing::FLAGS_gtest_death_test_style = "threadsafe";
return RUN_ALL_TESTS();
}
<commit_msg>Fix symbol conflict<commit_after>/*
*
* Copyright 2016, Google 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 Google 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.
*
*/
#include "test/cpp/util/grpc_tool.h"
#include <sstream>
#include <gflags/gflags.h>
#include <grpc++/channel.h>
#include <grpc++/client_context.h>
#include <grpc++/create_channel.h>
#include <grpc++/ext/proto_server_reflection_plugin.h>
#include <grpc++/server.h>
#include <grpc++/server_builder.h>
#include <grpc++/server_context.h>
#include <grpc/grpc.h>
#include <gtest/gtest.h>
#include "src/proto/grpc/testing/echo.grpc.pb.h"
#include "src/proto/grpc/testing/echo.pb.h"
#include "test/core/util/port.h"
#include "test/core/util/test_config.h"
#include "test/cpp/util/cli_credentials.h"
#include "test/cpp/util/string_ref_helper.h"
using grpc::testing::EchoRequest;
using grpc::testing::EchoResponse;
#define USAGE_REGEX "( grpc_cli .+\n){2,10}"
#define ECHO_TEST_SERVICE_SUMMARY \
"Echo\n" \
"RequestStream\n" \
"ResponseStream\n" \
"BidiStream\n" \
"Unimplemented\n"
#define ECHO_TEST_SERVICE_DESCRIPTION \
"filename: src/proto/grpc/testing/echo.proto\n" \
"package: grpc.testing;\n" \
"service EchoTestService {\n" \
" rpc Echo(grpc.testing.EchoRequest) returns (grpc.testing.EchoResponse) " \
"{}\n" \
" rpc RequestStream(stream grpc.testing.EchoRequest) returns " \
"(grpc.testing.EchoResponse) {}\n" \
" rpc ResponseStream(grpc.testing.EchoRequest) returns (stream " \
"grpc.testing.EchoResponse) {}\n" \
" rpc BidiStream(stream grpc.testing.EchoRequest) returns (stream " \
"grpc.testing.EchoResponse) {}\n" \
" rpc Unimplemented(grpc.testing.EchoRequest) returns " \
"(grpc.testing.EchoResponse) {}\n" \
"}\n" \
"\n"
#define ECHO_METHOD_DESCRIPTION \
" rpc Echo(grpc.testing.EchoRequest) returns (grpc.testing.EchoResponse) " \
"{}\n"
namespace grpc {
namespace testing {
DECLARE_bool(l);
namespace {
class TestCliCredentials final : public grpc::testing::CliCredentials {
public:
std::shared_ptr<grpc::ChannelCredentials> GetCredentials() const override {
return InsecureChannelCredentials();
}
const grpc::string GetCredentialUsage() const override { return ""; }
};
bool PrintStream(std::stringstream* ss, const grpc::string& output) {
(*ss) << output;
return true;
}
template <typename T>
size_t ArraySize(T& a) {
return ((sizeof(a) / sizeof(*(a))) /
static_cast<size_t>(!(sizeof(a) % sizeof(*(a)))));
}
class TestServiceImpl : public ::grpc::testing::EchoTestService::Service {
public:
Status Echo(ServerContext* context, const EchoRequest* request,
EchoResponse* response) override {
if (!context->client_metadata().empty()) {
for (std::multimap<grpc::string_ref, grpc::string_ref>::const_iterator
iter = context->client_metadata().begin();
iter != context->client_metadata().end(); ++iter) {
context->AddInitialMetadata(ToString(iter->first),
ToString(iter->second));
}
}
context->AddTrailingMetadata("trailing_key", "trailing_value");
response->set_message(request->message());
return Status::OK;
}
};
} // namespace
class GrpcToolTest : public ::testing::Test {
protected:
GrpcToolTest() {}
// SetUpServer cannot be used with EXPECT_EXIT. grpc_pick_unused_port_or_die()
// uses atexit() to free chosen ports, and it will spawn a new thread in
// resolve_address_posix.c:192 at exit time.
const grpc::string SetUpServer() {
std::ostringstream server_address;
int port = grpc_pick_unused_port_or_die();
server_address << "localhost:" << port;
// Setup server
ServerBuilder builder;
builder.AddListeningPort(server_address.str(), InsecureServerCredentials());
builder.RegisterService(&service_);
server_ = builder.BuildAndStart();
return server_address.str();
}
void ShutdownServer() { server_->Shutdown(); }
void ExitWhenError(int argc, const char** argv, const CliCredentials& cred,
GrpcToolOutputCallback callback) {
int result = GrpcToolMainLib(argc, argv, cred, callback);
if (result) {
exit(result);
}
}
std::unique_ptr<Server> server_;
TestServiceImpl service_;
reflection::ProtoServerReflectionPlugin plugin_;
};
TEST_F(GrpcToolTest, NoCommand) {
// Test input "grpc_cli"
std::stringstream output_stream;
const char* argv[] = {"grpc_cli"};
// Exit with 1, print usage instruction in stderr
EXPECT_EXIT(
GrpcToolMainLib(
ArraySize(argv), argv, TestCliCredentials(),
std::bind(PrintStream, &output_stream, std::placeholders::_1)),
::testing::ExitedWithCode(1), "No command specified\n" USAGE_REGEX);
// No output
EXPECT_TRUE(0 == output_stream.tellp());
}
TEST_F(GrpcToolTest, InvalidCommand) {
// Test input "grpc_cli"
std::stringstream output_stream;
const char* argv[] = {"grpc_cli", "abc"};
// Exit with 1, print usage instruction in stderr
EXPECT_EXIT(
GrpcToolMainLib(
ArraySize(argv), argv, TestCliCredentials(),
std::bind(PrintStream, &output_stream, std::placeholders::_1)),
::testing::ExitedWithCode(1), "Invalid command 'abc'\n" USAGE_REGEX);
// No output
EXPECT_TRUE(0 == output_stream.tellp());
}
TEST_F(GrpcToolTest, HelpCommand) {
// Test input "grpc_cli help"
std::stringstream output_stream;
const char* argv[] = {"grpc_cli", "help"};
// Exit with 1, print usage instruction in stderr
EXPECT_EXIT(GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(),
std::bind(PrintStream, &output_stream,
std::placeholders::_1)),
::testing::ExitedWithCode(1), USAGE_REGEX);
// No output
EXPECT_TRUE(0 == output_stream.tellp());
}
TEST_F(GrpcToolTest, ListCommand) {
// Test input "grpc_cli list localhost:<port>"
std::stringstream output_stream;
const grpc::string server_address = SetUpServer();
const char* argv[] = {"grpc_cli", "ls", server_address.c_str()};
FLAGS_l = false;
EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(),
std::bind(PrintStream, &output_stream,
std::placeholders::_1)));
EXPECT_TRUE(0 == strcmp(output_stream.str().c_str(),
"grpc.testing.EchoTestService\n"
"grpc.reflection.v1alpha.ServerReflection\n"));
ShutdownServer();
}
TEST_F(GrpcToolTest, ListOneService) {
// Test input "grpc_cli list localhost:<port> grpc.testing.EchoTestService"
std::stringstream output_stream;
const grpc::string server_address = SetUpServer();
const char* argv[] = {"grpc_cli", "ls", server_address.c_str(),
"grpc.testing.EchoTestService"};
// without -l flag
FLAGS_l = false;
EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(),
std::bind(PrintStream, &output_stream,
std::placeholders::_1)));
// Expected output: ECHO_TEST_SERVICE_SUMMARY
EXPECT_TRUE(0 ==
strcmp(output_stream.str().c_str(), ECHO_TEST_SERVICE_SUMMARY));
// with -l flag
output_stream.str(grpc::string());
output_stream.clear();
FLAGS_l = true;
EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(),
std::bind(PrintStream, &output_stream,
std::placeholders::_1)));
// Expected output: ECHO_TEST_SERVICE_DESCRIPTION
EXPECT_TRUE(
0 == strcmp(output_stream.str().c_str(), ECHO_TEST_SERVICE_DESCRIPTION));
ShutdownServer();
}
TEST_F(GrpcToolTest, TypeCommand) {
// Test input "grpc_cli type localhost:<port> grpc.testing.EchoRequest"
std::stringstream output_stream;
const grpc::string server_address = SetUpServer();
const char* argv[] = {"grpc_cli", "type", server_address.c_str(),
"grpc.testing.EchoRequest"};
EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(),
std::bind(PrintStream, &output_stream,
std::placeholders::_1)));
const grpc::protobuf::Descriptor* desc =
grpc::protobuf::DescriptorPool::generated_pool()->FindMessageTypeByName(
"grpc.testing.EchoRequest");
// Expected output: the DebugString of grpc.testing.EchoRequest
EXPECT_TRUE(0 ==
strcmp(output_stream.str().c_str(), desc->DebugString().c_str()));
ShutdownServer();
}
TEST_F(GrpcToolTest, ListOneMethod) {
// Test input "grpc_cli list localhost:<port> grpc.testing.EchoTestService"
std::stringstream output_stream;
const grpc::string server_address = SetUpServer();
const char* argv[] = {"grpc_cli", "ls", server_address.c_str(),
"grpc.testing.EchoTestService.Echo"};
// without -l flag
FLAGS_l = false;
EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(),
std::bind(PrintStream, &output_stream,
std::placeholders::_1)));
// Expected output: "Echo"
EXPECT_TRUE(0 == strcmp(output_stream.str().c_str(), "Echo\n"));
// with -l flag
output_stream.str(grpc::string());
output_stream.clear();
FLAGS_l = true;
EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(),
std::bind(PrintStream, &output_stream,
std::placeholders::_1)));
// Expected output: ECHO_METHOD_DESCRIPTION
EXPECT_TRUE(0 ==
strcmp(output_stream.str().c_str(), ECHO_METHOD_DESCRIPTION));
ShutdownServer();
}
TEST_F(GrpcToolTest, TypeNotFound) {
// Test input "grpc_cli type localhost:<port> grpc.testing.DummyRequest"
std::stringstream output_stream;
const grpc::string server_address = SetUpServer();
const char* argv[] = {"grpc_cli", "type", server_address.c_str(),
"grpc.testing.DummyRequest"};
EXPECT_DEATH(ExitWhenError(ArraySize(argv), argv, TestCliCredentials(),
std::bind(PrintStream, &output_stream,
std::placeholders::_1)),
".*Type grpc.testing.DummyRequest not found.*");
ShutdownServer();
}
TEST_F(GrpcToolTest, CallCommand) {
// Test input "grpc_cli call localhost:<port> Echo "message: 'Hello'"
std::stringstream output_stream;
const grpc::string server_address = SetUpServer();
const char* argv[] = {"grpc_cli", "call", server_address.c_str(), "Echo",
"message: 'Hello'"};
EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(),
std::bind(PrintStream, &output_stream,
std::placeholders::_1)));
// Expected output: "message: \"Hello\""
EXPECT_TRUE(NULL !=
strstr(output_stream.str().c_str(), "message: \"Hello\""));
ShutdownServer();
}
TEST_F(GrpcToolTest, TooFewArguments) {
// Test input "grpc_cli call Echo"
std::stringstream output_stream;
const char* argv[] = {"grpc_cli", "call", "Echo"};
// Exit with 1
EXPECT_EXIT(
GrpcToolMainLib(
ArraySize(argv), argv, TestCliCredentials(),
std::bind(PrintStream, &output_stream, std::placeholders::_1)),
::testing::ExitedWithCode(1), ".*Wrong number of arguments for call.*");
// No output
EXPECT_TRUE(0 == output_stream.tellp());
}
TEST_F(GrpcToolTest, TooManyArguments) {
// Test input "grpc_cli call localhost:<port> Echo Echo "message: 'Hello'"
std::stringstream output_stream;
const char* argv[] = {"grpc_cli", "call", "localhost:10000",
"Echo", "Echo", "message: 'Hello'"};
// Exit with 1
EXPECT_EXIT(
GrpcToolMainLib(
ArraySize(argv), argv, TestCliCredentials(),
std::bind(PrintStream, &output_stream, std::placeholders::_1)),
::testing::ExitedWithCode(1), ".*Wrong number of arguments for call.*");
// No output
EXPECT_TRUE(0 == output_stream.tellp());
}
} // namespace testing
} // namespace grpc
int main(int argc, char** argv) {
grpc_test_init(argc, argv);
::testing::InitGoogleTest(&argc, argv);
::testing::FLAGS_gtest_death_test_style = "threadsafe";
return RUN_ALL_TESTS();
}
<|endoftext|>
|
<commit_before>#include <QCoreApplication>
#include <QObject>
#include <QTcpServer>
#include <QTcpSocket>
#include <QHostAddress>
#include <QStringBuilder>
#include <QVector>
#include <functional>
#include "request.hpp"
#include "response.hpp"
#include "context.hpp"
//!
//! \brief The HttpServer class
//! Http (unsecure) server class
//!
class HttpServer : public QObject
{
Q_OBJECT
public:
HttpServer(QObject *parent = NULL);
~HttpServer();
bool compose(quint64 port, QHostAddress address = QHostAddress::Any);
private:
QTcpServer m_tcp_server;
quint64 m_port;
QHostAddress m_address;
QObject *m_parent;
signals:
void createContext();
};
inline HttpServer::HttpServer(QObject *parent)
{
m_parent = parent;
};
inline HttpServer::~HttpServer()
{
};
inline bool HttpServer::compose(quint64 port, QHostAddress address)
{
m_port = port;
m_address = address;
if (!m_tcp_server.listen(address, port)) {
qDebug() << "failed to start listening";
return false;
}
connect(&m_tcp_server, &QTcpServer::newConnection, [this] {
qDebug() << "client connected";
emit createContext();
// TODO: create ctx (need parent's ref here?)
});
return true;
};
//!
//! \brief The Recurse class
//! main class of the app
//!
class Recurse : public QObject
{
Q_OBJECT
using void_f = std::function<void()>;
using void_ff = std::function<void(void_f prev)>;
using next_prev_f = std::function<void(Context &ctx, void_ff next, void_f prev)>;
using next_f = std::function<void(Context &ctx, void_f next)>;
using final_f = std::function<void(Context &ctx)>;
public:
Recurse(int & argc, char ** argv, QObject *parent = NULL);
~Recurse();
bool listen(quint64 port, QHostAddress address = QHostAddress::Any);
bool listen(HttpServer *server);
public slots:
bool createContext();
private:
QCoreApplication app;
HttpServer *http;
};
inline Recurse::Recurse(int & argc, char ** argv, QObject *parent) : app(argc, argv)
{
Q_UNUSED(parent);
};
inline Recurse::~Recurse()
{
delete http;
};
//!
//! \brief Recurse::createContext
//! creates new recurse context for a tcp session
//!
//! \return true on success
//!
inline bool Recurse::createContext()
{
qDebug() << "creating new context";
return true;
};
//!
//! \brief Recurse::listen
//! listen for tcp requests
//!
//! \param port tcp server port
//! \param address tcp server listening address
//!
//! \return true on success
//!
inline bool Recurse::listen(quint64 port, QHostAddress address)
{
// set HttpServer instance, send reference to this object and prepare http connection
http = new HttpServer(this);
http->compose(port, address);
// connect HttpServer signal 'createContext' to this class' 'createContext' slot
connect(http, &HttpServer::createContext, this, &Recurse::createContext);
return app.exec();
};
//!
//! \brief Recurse::listen
//! listen for tcp requests
//!
//! overloaded function
//!
//! \param server pointer to the HttpServer instance
//!
//! \return true on success
//!
inline bool Recurse::listen(HttpServer *server)
{
http = server;
// connect HttpServer signal 'createContext' to this class' 'createContext' slot
connect(http, &HttpServer::createContext, this, &Recurse::createContext);
return app.exec();
};
<commit_msg>return ready socket to Recurse<commit_after>#include <QCoreApplication>
#include <QObject>
#include <QTcpServer>
#include <QTcpSocket>
#include <QHostAddress>
#include <QStringBuilder>
#include <QVector>
#include <functional>
#include "request.hpp"
#include "response.hpp"
#include "context.hpp"
//!
//! \brief The HttpServer class
//! Http (unsecure) server class
//!
class HttpServer : public QObject
{
Q_OBJECT
public:
HttpServer(QObject *parent = NULL);
~HttpServer();
bool compose(quint64 port, QHostAddress address = QHostAddress::Any);
private:
QTcpServer m_tcp_server;
quint64 m_port;
QHostAddress m_address;
QObject *m_parent;
signals:
void socketReady(QTcpSocket *socket);
};
inline HttpServer::HttpServer(QObject *parent)
{
m_parent = parent;
};
inline HttpServer::~HttpServer()
{
};
inline bool HttpServer::compose(quint64 port, QHostAddress address)
{
m_port = port;
m_address = address;
if (!m_tcp_server.listen(address, port)) {
qDebug() << "failed to start listening";
return false;
}
connect(&m_tcp_server, &QTcpServer::newConnection, [this] {
qDebug() << "client connected";
QTcpSocket *socket = m_tcp_server.nextPendingConnection();
if (socket == 0) {
qDebug() << "no connection?";
delete socket;
return;
}
emit socketReady(socket);
});
return true;
};
//!
//! \brief The Recurse class
//! main class of the app
//!
class Recurse : public QObject
{
Q_OBJECT
using void_f = std::function<void()>;
using void_ff = std::function<void(void_f prev)>;
using next_prev_f = std::function<void(Context &ctx, void_ff next, void_f prev)>;
using next_f = std::function<void(Context &ctx, void_f next)>;
using final_f = std::function<void(Context &ctx)>;
public:
Recurse(int & argc, char ** argv, QObject *parent = NULL);
~Recurse();
bool listen(quint64 port, QHostAddress address = QHostAddress::Any);
bool listen(HttpServer *server);
public slots:
bool handleConnection(QTcpSocket *socket);
private:
QCoreApplication app;
HttpServer *http;
};
inline Recurse::Recurse(int & argc, char ** argv, QObject *parent) : app(argc, argv)
{
Q_UNUSED(parent);
};
inline Recurse::~Recurse()
{
delete http;
};
//!
//! \brief Recurse::handleConnection
//! creates new recurse context for a tcp session
//!
//! \return true on success
//!
inline bool Recurse::handleConnection(QTcpSocket *socket)
{
qDebug() << "handling new connection";
connect(socket, &QTcpSocket::readyRead, [this, socket] {
QString data(socket->readAll());
qDebug() << "got data:" << data;
});
return true;
};
//!
//! \brief Recurse::listen
//! listen for tcp requests
//!
//! \param port tcp server port
//! \param address tcp server listening address
//!
//! \return true on success
//!
inline bool Recurse::listen(quint64 port, QHostAddress address)
{
// set HttpServer instance, send reference to this object and prepare http connection
http = new HttpServer(this);
http->compose(port, address);
// connect HttpServer signal 'socketReady' to this class' 'handleConnection' slot
connect(http, &HttpServer::socketReady, this, &Recurse::handleConnection);
return app.exec();
};
//!
//! \brief Recurse::listen
//! listen for tcp requests
//!
//! overloaded function
//!
//! \param server pointer to the HttpServer instance
//!
//! \return true on success
//!
inline bool Recurse::listen(HttpServer *server)
{
http = server;
// connect HttpServer signal 'socketReady' to this class' 'handleConnection' slot
connect(http, &HttpServer::socketReady, this, &Recurse::handleConnection);
return app.exec();
};
<|endoftext|>
|
<commit_before>//
// Copyright 2014, 2015 Razer Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#include "OSVRPrivatePCH.h"
#if OSVR_DEPRECATED_BLUEPRINT_API_ENABLED
#include "OSVRInterfaceCollection.h"
#endif
#include "OSVREntryPoint.h"
#include <osvr/ClientKit/ServerAutoStartC.h>
#include "Runtime/Core/Public/Misc/DateTime.h"
DEFINE_LOG_CATEGORY(OSVREntryPointLog);
OSVREntryPoint::OSVREntryPoint()
{
// avoid BuildCookRun hangs
if (IsRunningCommandlet() || IsRunningDedicatedServer())
{
UE_LOG(OSVREntryPointLog, Display, TEXT("OSVREntryPoint::OSVREntryPoint(): running as commandlet or dedicated server - skipping client context startup."));
return;
}
osvrClientAttemptServerAutoStart();
osvrClientContext = osvrClientInit("com.osvr.unreal.plugin");
{
bool bClientContextOK = false;
bool bFailure = false;
auto begin = FDateTime::Now().GetSecond();
auto end = begin + 3;
while (FDateTime::Now().GetSecond() < end && !bClientContextOK && !bFailure)
{
bClientContextOK = osvrClientCheckStatus(osvrClientContext) == OSVR_RETURN_SUCCESS;
if (!bClientContextOK)
{
bFailure = osvrClientUpdate(osvrClientContext) == OSVR_RETURN_FAILURE;
if (bFailure)
{
UE_LOG(OSVREntryPointLog, Warning, TEXT("osvrClientUpdate failed during startup. Treating this as \"HMD not connected\""));
break;
}
FPlatformProcess::Sleep(0.2f);
}
}
if (!bClientContextOK)
{
UE_LOG(OSVREntryPointLog, Warning, TEXT("OSVR client context did not initialize correctly. Most likely the server isn't running. Treating this as if the HMD is not connected."));
}
}
#if OSVR_DEPRECATED_BLUEPRINT_API_ENABLED
InterfaceCollection = MakeShareable(new OSVRInterfaceCollection(osvrClientContext));
#endif
}
OSVREntryPoint::~OSVREntryPoint()
{
FScopeLock lock(this->GetClientContextMutex());
#if OSVR_DEPRECATED_BLUEPRINT_API_ENABLED
InterfaceCollection = nullptr;
#endif
if (osvrClientContext)
{
osvrClientShutdown(osvrClientContext);
}
osvrClientReleaseAutoStartedServer();
}
void OSVREntryPoint::Tick(float DeltaTime)
{
FScopeLock lock(this->GetClientContextMutex());
osvrClientUpdate(osvrClientContext);
}
bool OSVREntryPoint::IsOSVRConnected()
{
return osvrClientContext && osvrClientCheckStatus(osvrClientContext) == OSVR_RETURN_SUCCESS;
}
#if OSVR_DEPRECATED_BLUEPRINT_API_ENABLED
OSVRInterfaceCollection* OSVREntryPoint::GetInterfaceCollection()
{
return InterfaceCollection.Get();
}
#endif
<commit_msg>Added longer timeout to OSVREntryPoint's context creation, immediately after server auto-start.<commit_after>//
// Copyright 2014, 2015 Razer Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#include "OSVRPrivatePCH.h"
#if OSVR_DEPRECATED_BLUEPRINT_API_ENABLED
#include "OSVRInterfaceCollection.h"
#endif
#include "OSVREntryPoint.h"
#include <osvr/ClientKit/ServerAutoStartC.h>
#include "Runtime/Core/Public/Misc/DateTime.h"
DEFINE_LOG_CATEGORY(OSVREntryPointLog);
OSVREntryPoint::OSVREntryPoint()
{
// avoid BuildCookRun hangs
if (IsRunningCommandlet() || IsRunningDedicatedServer())
{
UE_LOG(OSVREntryPointLog, Display, TEXT("OSVREntryPoint::OSVREntryPoint(): running as commandlet or dedicated server - skipping client context startup."));
return;
}
osvrClientAttemptServerAutoStart();
osvrClientContext = osvrClientInit("com.osvr.unreal.plugin");
{
bool bClientContextOK = false;
bool bFailure = false;
auto begin = FDateTime::Now().GetSecond();
auto end = begin + 10;
while (FDateTime::Now().GetSecond() < end && !bClientContextOK && !bFailure)
{
bClientContextOK = osvrClientCheckStatus(osvrClientContext) == OSVR_RETURN_SUCCESS;
if (!bClientContextOK)
{
bFailure = osvrClientUpdate(osvrClientContext) == OSVR_RETURN_FAILURE;
if (bFailure)
{
UE_LOG(OSVREntryPointLog, Warning, TEXT("osvrClientUpdate failed during startup. Treating this as \"HMD not connected\""));
break;
}
FPlatformProcess::Sleep(0.2f);
}
}
if (!bClientContextOK)
{
UE_LOG(OSVREntryPointLog, Warning, TEXT("OSVR client context did not initialize correctly. Most likely the server isn't running. Treating this as if the HMD is not connected."));
}
}
#if OSVR_DEPRECATED_BLUEPRINT_API_ENABLED
InterfaceCollection = MakeShareable(new OSVRInterfaceCollection(osvrClientContext));
#endif
}
OSVREntryPoint::~OSVREntryPoint()
{
FScopeLock lock(this->GetClientContextMutex());
#if OSVR_DEPRECATED_BLUEPRINT_API_ENABLED
InterfaceCollection = nullptr;
#endif
if (osvrClientContext)
{
osvrClientShutdown(osvrClientContext);
}
osvrClientReleaseAutoStartedServer();
}
void OSVREntryPoint::Tick(float DeltaTime)
{
FScopeLock lock(this->GetClientContextMutex());
osvrClientUpdate(osvrClientContext);
}
bool OSVREntryPoint::IsOSVRConnected()
{
return osvrClientContext && osvrClientCheckStatus(osvrClientContext) == OSVR_RETURN_SUCCESS;
}
#if OSVR_DEPRECATED_BLUEPRINT_API_ENABLED
OSVRInterfaceCollection* OSVREntryPoint::GetInterfaceCollection()
{
return InterfaceCollection.Get();
}
#endif
<|endoftext|>
|
<commit_before>/*
* Wintermute is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* Wintermute is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with Wintermute; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
#include "test_suite.hpp"
#include <chrono>
#include <wintermute-core/util/serializable.hpp>
#include <wintermute-core/message.hpp>
#include <cxxtest/TestSuite.h>
using Wintermute::Util::Serializable;
using Wintermute::Message;
using Wintermute::Module;
using std::make_pair;
class MessageTestSuite : public CxxTest::TestSuite
{
public:
string getCurrentTimeString() const
{
const time_t curTime = time(nullptr);
string strTime = asctime(std::gmtime(&curTime));
strTime.pop_back();
strTime += " UTC";
return strTime;
}
void testClone(void)
{
Message::HashType data;
data.insert(std::make_pair("foo", "bar"));
Message message;
message.setPayload(data);
TS_ASSERT_EQUALS( message.payload().at("foo"), Message::HashValue("bar") );
Message clonedMessage(message.clone());
TS_ASSERT_EQUALS( clonedMessage.payload().at("foo"), Message::HashValue("bar") );
}
void testEmpty(void)
{
Message aMessage;
TS_ASSERT_EQUALS( aMessage.isEmpty(), true );
}
void testSchemaCheck(void)
{
const string timestampString = getCurrentTimeString();
Module::Designation sender("input", "in.wintermute.test");
Module::Designation receiver("output", "in.wintermute.test");
Message::HashType data;
data.insert(std::make_pair("foo", std::to_string(100)));
Serializable::Map messageMap;
messageMap.insert(make_pair("sender", sender));
messageMap.insert(make_pair("receiver", receiver));
messageMap.insert(make_pair("payload", Serializable::toString(data)));
messageMap.insert(make_pair("timestamp", timestampString));
Message message;
message = messageMap;
TS_ASSERT_EQUALS ( message.sender() , sender );
TS_ASSERT_EQUALS ( message.receiver() , receiver );
TS_ASSERT_EQUALS ( message.payload() , data );
TS_ASSERT_EQUALS ( message.timestamp(), timestampString );
}
void testEnsureThatTimestampIsUtc()
{
Message message = craftRandomMessage();
const string obtainedTimestring = message.timestamp();
TS_ASSERT ( obtainedTimestring.find("UTC") != 0 );
}
};
<commit_msg>test: made message test a bit more strict.<commit_after>/*
* Wintermute is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* Wintermute is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with Wintermute; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
#include "test_suite.hpp"
#include <chrono>
#include <wintermute-core/util/serializable.hpp>
#include <wintermute-core/message.hpp>
#include <cxxtest/TestSuite.h>
using Wintermute::Util::Serializable;
using Wintermute::Message;
using Wintermute::Module;
using std::make_pair;
class MessageTestSuite : public CxxTest::TestSuite
{
public:
string getCurrentTimeString() const
{
const time_t curTime = time(nullptr);
string strTime = asctime(std::gmtime(&curTime));
strTime.pop_back();
strTime += " UTC";
return strTime;
}
void testClone(void)
{
Message::HashType data;
data.insert(std::make_pair("foo", "bar"));
Message message;
message.setPayload(data);
TS_ASSERT_EQUALS( message.payload().at("foo"), Message::HashValue("bar") );
Message clonedMessage(message.clone());
TS_ASSERT_EQUALS( clonedMessage.payload().at("foo"), Message::HashValue("bar") );
}
void testEmpty(void)
{
Message aMessage;
TS_ASSERT_EQUALS( aMessage.isEmpty(), true );
}
void testSchemaCheck(void)
{
const string timestampString = getCurrentTimeString();
Module::Designation sender("input", "in.wintermute.test");
Module::Designation receiver("output", "in.wintermute.test");
Message::HashType data;
data.insert(std::make_pair("foo", std::to_string(100)));
Serializable::Map messageMap;
messageMap.insert(make_pair("sender", sender));
messageMap.insert(make_pair("receiver", receiver));
messageMap.insert(make_pair("payload", Serializable::toString(data)));
messageMap.insert(make_pair("timestamp", timestampString));
Message message;
message = messageMap;
TS_ASSERT_EQUALS ( message.sender() , sender );
TS_ASSERT_EQUALS ( message.receiver() , receiver );
TS_ASSERT_EQUALS ( message.payload() , data );
TS_ASSERT_EQUALS ( message.timestamp(), timestampString );
}
void testEnsureThatTimestampIsUtc()
{
Message message = craftRandomMessage();
const string obtainedTimestring = message.timestamp();
TS_ASSERT ( obtainedTimestring.find("UTC") != 0 );
TS_ASSERT_EQUALS ( obtainedTimestring.find("UTC"),
obtainedTimestring.length() - 3 );
}
};
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* REALM CONFIDENTIAL
* __________________
*
* [2011] - [2012] Realm Inc
* All Rights Reserved.
*
* NOTICE: All information contained herein is, and remains
* the property of Realm Incorporated and its suppliers,
* if any. The intellectual and technical concepts contained
* herein are proprietary to Realm Incorporated
* and its suppliers and may be covered by U.S. and Foreign Patents,
* patents in process, and are protected by trade secret or copyright law.
* Dissemination of this information or reproduction of this material
* is strictly forbidden unless prior written permission is obtained
* from Realm Incorporated.
*
**************************************************************************/
#ifndef REALM_TEST_UTIL_RANDOM_HPP
#define REALM_TEST_UTIL_RANDOM_HPP
#include <limits>
#include <iterator>
#include <utility>
#include <algorithm>
#include <realm/util/features.h>
#include <realm/util/assert.hpp>
#include <realm/util/type_traits.hpp>
#include <realm/util/safe_int_ops.hpp>
#include <realm/util/thread.hpp>
namespace realm {
namespace test_util {
/// Draw a uniformly distributed integer from the specified range using the
/// global pseudorandom number generator. This global generator is based on an
/// instance of `Random` and is therefore independent of other generators such
/// as the one availble via std::rand(). This function is thread safe.
///
/// The thread-safety of this function means that it is relatively slow, so if
/// you need to draw many random numbers efficiently, consider creating your own
/// instance of `Random`.
template<class T> T random_int(T min, T max) REALM_NOEXCEPT;
/// Same as `random_int(lim::min(), lim::max())` where `lim` is
/// `std::numeric_limits<T>`.
template<class T> T random_int() REALM_NOEXCEPT;
/// Reseed the global pseudorandom number generator that is used by
/// random_int().
///
/// This function is thread safe.
void random_seed(unsigned long) REALM_NOEXCEPT;
/// To the extent possible, produce a nondeterministic value for seeding a
/// pseudorandom number genrator.
///
/// This function is thread safe.
unsigned long produce_nondeterministic_random_seed();
/// Mersenne Twister by Matsumoto and Nishimura, 1998 (MT19937).
///
/// http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/MT2002/emt19937ar.html
///
/// \tparam w Word size, the number of bits in each element of the state vector.
///
/// \tparam n, m Shift values.
///
/// \tparam r, a Twist value and conditional xor-mask.
///
/// \tparam u, d, s, b, t, c, l Bit-scrambling matrix.
///
/// \tparam f Initialization multiplier.
template<class UIntType, int w, int n, int m, int r, UIntType a,
int u, UIntType d, int s, UIntType b, int t, UIntType c, int l,
UIntType f>
class MersenneTwisterEngine {
public:
typedef UIntType result_type;
static const int word_size = w;
static const int state_size = n;
static const int shift_size = m;
static const int mask_bits = r;
static const result_type xor_mask = a;
static const int tempering_u = u;
static const result_type tempering_d = d;
static const int tempering_s = s;
static const result_type tempering_b = b;
static const int tempering_t = t;
static const result_type tempering_c = c;
static const int tempering_l = l;
static const result_type initialization_multiplier = f;
static const result_type default_seed = 5489U;
MersenneTwisterEngine(result_type value = default_seed) REALM_NOEXCEPT;
void seed(result_type) REALM_NOEXCEPT;
result_type operator()() REALM_NOEXCEPT;
static result_type min() REALM_NOEXCEPT;
static result_type max() REALM_NOEXCEPT;
private:
UIntType m_x[state_size];
int m_p;
void gen_rand() REALM_NOEXCEPT;
};
/// 32-bit Mersenne Twister.
typedef MersenneTwisterEngine<util::FastestUnsigned<32>::type,
32, 624, 397, 31, 0x9908B0DFUL,
11, 0xFFFFFFFFUL,
7, 0x9D2C5680UL,
15, 0xEFC60000UL,
18, 1812433253UL> MT19937;
template<class T> class UniformIntDistribution {
public:
UniformIntDistribution(T min = 0, T max = std::numeric_limits<T>::max()) REALM_NOEXCEPT;
template<class G> T operator()(G& generator) const REALM_NOEXCEPT;
private:
T m_min, m_max;
// Requires that `min` < `max`
template<class G> static T draw(G& generator, T min, T max) REALM_NOEXCEPT;
};
/// Simple pseudorandom number generator.
class Random {
public:
Random() REALM_NOEXCEPT;
Random(unsigned long seed) REALM_NOEXCEPT;
/// Reseed this pseudorandom number generator.
void seed(unsigned long) REALM_NOEXCEPT;
/// Draw a uniformly distributed integer from the specified range. It is an
/// error if `min` is greater than `max`.
template<class T> T draw_int(T min, T max) REALM_NOEXCEPT;
/// Same as `draw_int(lim::min(), lim::max())` where `lim` is
/// `std::numeric_limits<T>`.
template<class T> T draw_int() REALM_NOEXCEPT;
/// Same as `draw_int<T>(0, max)`. It is an error to specify a `max` less
/// than 0.
template<class T> T draw_int_max(T max) REALM_NOEXCEPT;
/// Same as `draw_int_max(module_size-1)`. It is an error to specify a
/// module size less than 1.
template<class T> T draw_int_mod(T module_size) REALM_NOEXCEPT;
/// Same as `draw_int<T>(max)` where `max` is one less than 2 to the power
/// of `bits`. It is an error to specify a number of bits less than zero, or
/// greater than `lim::digits` where `lim` is `std::numeric_limits<T>`.
template<class T> T draw_int_bits(int bits) REALM_NOEXCEPT;
/// Draw true `n` out of `m` times. It is an error if `n` is less than 1, or
/// if `m` is less than `n`.
bool chance(int n, int m) REALM_NOEXCEPT;
/// Same as `chance(1,2)`.
bool draw_bool() REALM_NOEXCEPT;
/// Reorder the specified elements such that each possible permutation has
/// an equal probability of appearing.
template<class RandomIt> void shuffle(RandomIt begin, RandomIt end);
private:
MT19937 m_engine;
};
// Implementation
template<class UIntType, int w, int n, int m, int r, UIntType a,
int u, UIntType d, int s, UIntType b, int t, UIntType c, int l,
UIntType f>
inline MersenneTwisterEngine<UIntType, w, n, m, r, a, u, d, s, b, t, c, l, f>::
MersenneTwisterEngine(result_type value) REALM_NOEXCEPT
{
seed(value);
}
template<class UIntType, int w, int n, int m, int r, UIntType a,
int u, UIntType d, int s, UIntType b, int t, UIntType c, int l,
UIntType f>
inline void MersenneTwisterEngine<UIntType, w, n, m, r, a, u, d, s, b, t, c, l, f>::
seed(result_type sd) REALM_NOEXCEPT
{
int excess_bits = std::numeric_limits<UIntType>::digits - word_size;
UIntType mask = ~UIntType() >> excess_bits;
m_x[0] = sd & mask;
for (int i = 1; i != state_size; ++i) {
UIntType x = m_x[i - 1];
x ^= x >> (word_size - 2);
x *= initialization_multiplier;
x += i;
m_x[i] = x & mask;
}
m_p = state_size;
}
template<class UIntType, int w, int n, int m, int r, UIntType a,
int u, UIntType d, int s, UIntType b, int t, UIntType c, int l,
UIntType f>
inline UIntType MersenneTwisterEngine<UIntType, w, n, m, r, a, u, d, s, b, t, c, l, f>::
operator()() REALM_NOEXCEPT
{
if (m_p >= state_size)
gen_rand();
UIntType z = m_x[m_p++];
z ^= (z >> tempering_u) & tempering_d;
z ^= (z << tempering_s) & tempering_b;
z ^= (z << tempering_t) & tempering_c;
z ^= (z >> tempering_l);
return z;
}
template<class UIntType, int w, int n, int m, int r, UIntType a,
int u, UIntType d, int s, UIntType b, int t, UIntType c, int l,
UIntType f>
inline UIntType MersenneTwisterEngine<UIntType, w, n, m, r, a, u, d, s, b, t, c, l, f>::
min() REALM_NOEXCEPT
{
return 0;
}
template<class UIntType, int w, int n, int m, int r, UIntType a,
int u, UIntType d, int s, UIntType b, int t, UIntType c, int l,
UIntType f>
inline UIntType MersenneTwisterEngine<UIntType, w, n, m, r, a, u, d, s, b, t, c, l, f>::
max() REALM_NOEXCEPT
{
int excess_bits = std::numeric_limits<UIntType>::digits - word_size;
return ~result_type() >> excess_bits;
}
template<class UIntType, int w, int n, int m, int r, UIntType a,
int u, UIntType d, int s, UIntType b, int t, UIntType c, int l,
UIntType f>
inline void MersenneTwisterEngine<UIntType, w, n, m, r, a, u, d, s, b, t, c, l, f>::
gen_rand() REALM_NOEXCEPT
{
UIntType upper_mask = (~UIntType()) << mask_bits;
UIntType lower_mask = ~upper_mask;
for (int i = 0; i != (state_size - shift_size); ++i) {
UIntType x = ((m_x[i] & upper_mask) | (m_x[i + 1] & lower_mask));
m_x[i] = (m_x[i + shift_size] ^ (x >> 1) ^ ((x & 0x01) ? xor_mask : 0));
}
for (int i = (state_size - shift_size); i != (state_size - 1); ++i) {
UIntType x = ((m_x[i] & upper_mask) | (m_x[i + 1] & lower_mask));
m_x[i] = (m_x[i + (shift_size - state_size)] ^ (x >> 1) ^ ((x & 0x01) ? xor_mask : 0));
}
UIntType x = ((m_x[state_size - 1] & upper_mask) | (m_x[0] & lower_mask));
m_x[state_size - 1] = (m_x[shift_size - 1] ^ (x >> 1) ^ ((x & 0x01) ? xor_mask : 0));
m_p = 0;
}
template<class T>
inline UniformIntDistribution<T>::UniformIntDistribution(T min, T max) REALM_NOEXCEPT:
m_min(min),
m_max(max)
{
}
template<class T> template<class G>
inline T UniformIntDistribution<T>::operator()(G& generator) const REALM_NOEXCEPT
{
if (m_min >= m_max)
return m_min;
return draw(generator, m_min, m_max);
}
template<class T> template<class G>
inline T UniformIntDistribution<T>::draw(G& generator, T min, T max) REALM_NOEXCEPT
{
// FIXME: This implementation assumes that if `T` is signed then there
// exists an unsigned type with at least one more value bit than `T`
// has. While this is typically the case, it is not guaranteed by the
// standard, not even when `T` is a standard integer type.
typedef std::numeric_limits<typename G::result_type> lim_g;
typedef std::numeric_limits<T> lim_t;
const int uint_bits_g = lim_g::is_signed ? lim_g::digits + 1 : lim_g::digits;
const int uint_bits_t = lim_t::is_signed ? lim_t::digits + 1 : lim_t::digits;
const int uint_bits = uint_bits_g >= uint_bits_t ? uint_bits_g : uint_bits_t;
typedef typename util::FastestUnsigned<uint_bits>::type uint_type;
uint_type gen_max = uint_type(G::max()) - uint_type(G::min());
uint_type val_max = uint_type(max) - uint_type(min);
uint_type value = uint_type(generator()) - uint_type(G::min());
if (val_max < gen_max) {
// Reduction
uint_type num_values = val_max + 1;
uint_type num_modules = 1 + (gen_max - val_max) / num_values;
uint_type compound_size = num_modules * num_values;
if (compound_size > 0) {
// `(gen_max+1) / num_values` has remainder
while (REALM_UNLIKELY(value >= compound_size))
value = uint_type(generator()) - uint_type(G::min());
}
value /= num_modules;
}
else if (val_max > gen_max) {
// Expansion
uint_type num_gen_values = gen_max + 1;
uint_type val_max_2 = val_max / (num_gen_values ? num_gen_values : 1); // removed div by 0 warning by vs2013 (todo, investigate)
for (;;) {
uint_type v = num_gen_values * draw(generator, 0, T(val_max_2));
value += v;
// Previous addition may have overflowed, so we have to test for
// that too
if (value <= val_max && value >= v)
break;
value = uint_type(generator()) - uint_type(G::min());
}
}
return util::from_twos_compl<T>(uint_type(min) + value);
}
inline Random::Random() REALM_NOEXCEPT:
m_engine(MT19937::default_seed)
{
}
inline Random::Random(unsigned long seed) REALM_NOEXCEPT:
m_engine(MT19937::result_type(seed))
{
}
inline void Random::seed(unsigned long seed) REALM_NOEXCEPT
{
m_engine.seed(MT19937::result_type(seed));
}
template<class T> inline T Random::draw_int(T min, T max) REALM_NOEXCEPT
{
return UniformIntDistribution<T>(min, max)(m_engine);
}
template<class T> inline T Random::draw_int() REALM_NOEXCEPT
{
typedef std::numeric_limits<T> lim;
return draw_int(lim::min(), lim::max());
}
template<class T> inline T Random::draw_int_max(T max) REALM_NOEXCEPT
{
return draw_int(T(), max);
}
template<class T> inline T Random::draw_int_mod(T module_size) REALM_NOEXCEPT
{
return draw_int_max(T(module_size-1));
}
template<class T> inline T Random::draw_int_bits(int bits) REALM_NOEXCEPT
{
if (bits <= 0)
return T();
T bit = T(1) << (bits-1);
T max = bit + (bit-1);
return draw_int_max(max);
}
inline bool Random::chance(int n, int m) REALM_NOEXCEPT
{
return draw_int_mod(m) < n;
}
inline bool Random::draw_bool() REALM_NOEXCEPT
{
return draw_int(0,1) == 1;
}
template<class RandomIt> inline void Random::shuffle(RandomIt begin, RandomIt end)
{
typedef typename std::iterator_traits<RandomIt>::difference_type diff_type;
diff_type n = end - begin;
for (diff_type i = n-1; i > 0; --i) {
using std::swap;
swap(begin[i], begin[draw_int_max(i)]);
}
}
} // namespace test_util
namespace _impl {
struct GlobalRandom {
util::Mutex m_mutex;
test_util::Random m_random;
static GlobalRandom& get() REALM_NOEXCEPT;
};
} // namespace _impl
namespace test_util {
template<class T> inline T random_int(T min, T max) REALM_NOEXCEPT
{
_impl::GlobalRandom& r = _impl::GlobalRandom::get();
util::LockGuard lock(r.m_mutex);
return r.m_random.draw_int(min, max);
}
template<class T> inline T random_int() REALM_NOEXCEPT
{
typedef std::numeric_limits<T> lim;
return random_int(lim::min(), lim::max());
}
inline void random_seed(unsigned long seed) REALM_NOEXCEPT
{
_impl::GlobalRandom& r = _impl::GlobalRandom::get();
util::LockGuard lock(r.m_mutex);
return r.m_random.seed(seed);
}
} // namespace test_util
} // namespace realm
#endif // REALM_TEST_UTIL_RANDOM_HPP
<commit_msg>Remove custom MT19937 implementation<commit_after>/*************************************************************************
*
* REALM CONFIDENTIAL
* __________________
*
* [2011] - [2012] Realm Inc
* All Rights Reserved.
*
* NOTICE: All information contained herein is, and remains
* the property of Realm Incorporated and its suppliers,
* if any. The intellectual and technical concepts contained
* herein are proprietary to Realm Incorporated
* and its suppliers and may be covered by U.S. and Foreign Patents,
* patents in process, and are protected by trade secret or copyright law.
* Dissemination of this information or reproduction of this material
* is strictly forbidden unless prior written permission is obtained
* from Realm Incorporated.
*
**************************************************************************/
#ifndef REALM_TEST_UTIL_RANDOM_HPP
#define REALM_TEST_UTIL_RANDOM_HPP
#include <limits>
#include <iterator>
#include <utility>
#include <algorithm>
#include <random>
#include <realm/util/features.h>
#include <realm/util/assert.hpp>
#include <realm/util/type_traits.hpp>
#include <realm/util/safe_int_ops.hpp>
#include <realm/util/thread.hpp>
namespace realm {
namespace test_util {
/// Draw a uniformly distributed integer from the specified range using the
/// global pseudorandom number generator. This global generator is based on an
/// instance of `Random` and is therefore independent of other generators such
/// as the one availble via std::rand(). This function is thread safe.
///
/// The thread-safety of this function means that it is relatively slow, so if
/// you need to draw many random numbers efficiently, consider creating your own
/// instance of `Random`.
template<class T> T random_int(T min, T max) REALM_NOEXCEPT;
/// Same as `random_int(lim::min(), lim::max())` where `lim` is
/// `std::numeric_limits<T>`.
template<class T> T random_int() REALM_NOEXCEPT;
/// Reseed the global pseudorandom number generator that is used by
/// random_int().
///
/// This function is thread safe.
void random_seed(unsigned long) REALM_NOEXCEPT;
/// To the extent possible, produce a nondeterministic value for seeding a
/// pseudorandom number genrator.
///
/// This function is thread safe.
unsigned long produce_nondeterministic_random_seed();
/// Simple pseudorandom number generator.
class Random {
public:
Random() REALM_NOEXCEPT;
Random(unsigned long seed) REALM_NOEXCEPT;
/// Reseed this pseudorandom number generator.
void seed(unsigned long) REALM_NOEXCEPT;
/// Draw a uniformly distributed integer from the specified range. It is an
/// error if `min` is greater than `max`.
template<class T> T draw_int(T min, T max) REALM_NOEXCEPT;
/// Same as `draw_int(lim::min(), lim::max())` where `lim` is
/// `std::numeric_limits<T>`.
template<class T> T draw_int() REALM_NOEXCEPT;
/// Same as `draw_int<T>(0, max)`. It is an error to specify a `max` less
/// than 0.
template<class T> T draw_int_max(T max) REALM_NOEXCEPT;
/// Same as `draw_int_max(module_size-1)`. It is an error to specify a
/// module size less than 1.
template<class T> T draw_int_mod(T module_size) REALM_NOEXCEPT;
/// Same as `draw_int<T>(max)` where `max` is one less than 2 to the power
/// of `bits`. It is an error to specify a number of bits less than zero, or
/// greater than `lim::digits` where `lim` is `std::numeric_limits<T>`.
template<class T> T draw_int_bits(int bits) REALM_NOEXCEPT;
/// Draw true `n` out of `m` times. It is an error if `n` is less than 1, or
/// if `m` is less than `n`.
bool chance(int n, int m) REALM_NOEXCEPT;
/// Same as `chance(1,2)`.
bool draw_bool() REALM_NOEXCEPT;
/// Reorder the specified elements such that each possible permutation has
/// an equal probability of appearing.
template<class RandomIt> void shuffle(RandomIt begin, RandomIt end);
private:
std::mt19937 m_engine;
};
// Implementation
inline Random::Random() REALM_NOEXCEPT:
m_engine(std::mt19937::default_seed)
{
}
inline Random::Random(unsigned long seed) REALM_NOEXCEPT:
m_engine(std::mt19937::result_type(seed))
{
}
inline void Random::seed(unsigned long seed) REALM_NOEXCEPT
{
m_engine.seed(std::mt19937::result_type(seed));
}
template<class T> inline T Random::draw_int(T min, T max) REALM_NOEXCEPT
{
return std::uniform_int_distribution<T>(min, max)(m_engine);
}
template<class T> inline T Random::draw_int() REALM_NOEXCEPT
{
typedef std::numeric_limits<T> lim;
return draw_int(lim::min(), lim::max());
}
template<class T> inline T Random::draw_int_max(T max) REALM_NOEXCEPT
{
return draw_int(T(), max);
}
template<class T> inline T Random::draw_int_mod(T module_size) REALM_NOEXCEPT
{
return draw_int_max(T(module_size-1));
}
template<class T> inline T Random::draw_int_bits(int bits) REALM_NOEXCEPT
{
if (bits <= 0)
return T();
T bit = T(1) << (bits-1);
T max = bit + (bit-1);
return draw_int_max(max);
}
inline bool Random::chance(int n, int m) REALM_NOEXCEPT
{
return draw_int_mod(m) < n;
}
inline bool Random::draw_bool() REALM_NOEXCEPT
{
return draw_int(0,1) == 1;
}
template<class RandomIt> inline void Random::shuffle(RandomIt begin, RandomIt end)
{
typedef typename std::iterator_traits<RandomIt>::difference_type diff_type;
diff_type n = end - begin;
for (diff_type i = n-1; i > 0; --i) {
using std::swap;
swap(begin[i], begin[draw_int_max(i)]);
}
}
} // namespace test_util
namespace _impl {
struct GlobalRandom {
util::Mutex m_mutex;
test_util::Random m_random;
static GlobalRandom& get() REALM_NOEXCEPT;
};
} // namespace _impl
namespace test_util {
template<class T> inline T random_int(T min, T max) REALM_NOEXCEPT
{
_impl::GlobalRandom& r = _impl::GlobalRandom::get();
util::LockGuard lock(r.m_mutex);
return r.m_random.draw_int(min, max);
}
template<class T> inline T random_int() REALM_NOEXCEPT
{
typedef std::numeric_limits<T> lim;
return random_int(lim::min(), lim::max());
}
inline void random_seed(unsigned long seed) REALM_NOEXCEPT
{
_impl::GlobalRandom& r = _impl::GlobalRandom::get();
util::LockGuard lock(r.m_mutex);
return r.m_random.seed(seed);
}
} // namespace test_util
} // namespace realm
#endif // REALM_TEST_UTIL_RANDOM_HPP
<|endoftext|>
|
<commit_before>/***********************************************************************
filename: OpenGL3Shader.cpp
created: Wed, 8th Feb 2012
author: Lukas E Meindl
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
***************************************************************************/
#include <GL/glew.h>
#include "CEGUI/RendererModules/OpenGL/Shader.h"
#include "CEGUI/RendererModules/OpenGL/StateChangeWrapper.h"
#include "CEGUI/Logger.h"
#include "CEGUI/Exceptions.h"
#include <sstream>
#include <iostream>
namespace CEGUI
{
//----------------------------------------------------------------------------//
static const size_t LOG_BUFFER_SIZE = 8096;
//----------------------------------------------------------------------------//
OpenGL3Shader::OpenGL3Shader(const std::string& vertex_shader_source,
const std::string& fragment_shader_source,
OpenGL3StateChangeWrapper* glStateChanger) :
d_glStateChanger(glStateChanger),
d_createdSucessfully(false),
d_vertexShader(0),
d_fragmentShader(0),
d_geometryShader(0),
d_program(0)
{
// Compile the shaders
d_vertexShader = compile(GL_VERTEX_SHADER, vertex_shader_source);
if (d_vertexShader == 0)
return;
checkGLErrors();
if(fragment_shader_source.length() > 0)
{
d_fragmentShader = compile(GL_FRAGMENT_SHADER, fragment_shader_source);
if (d_fragmentShader == 0)
return;
}
checkGLErrors();
d_program = glCreateProgram();
}
//----------------------------------------------------------------------------//
OpenGL3Shader::~OpenGL3Shader()
{
if(d_program != 0)
glDeleteProgram(d_program);
if(d_vertexShader != 0)
glDeleteShader(d_vertexShader);
if(d_fragmentShader != 0)
glDeleteShader(d_fragmentShader);
if(d_geometryShader != 0)
glDeleteShader(d_geometryShader);
}
//----------------------------------------------------------------------------//
void OpenGL3Shader::bind() const
{
d_glStateChanger->useProgram(d_program);
}
//----------------------------------------------------------------------------//
GLint OpenGL3Shader::getAttribLocation(const std::string &name) const
{
return glGetAttribLocation(d_program, name.c_str());
}
//----------------------------------------------------------------------------//
GLint OpenGL3Shader::getUniformLocation(const std::string &name) const
{
return glGetUniformLocation(d_program, name.c_str());
}
//----------------------------------------------------------------------------//
void OpenGL3Shader::bindFragDataLocation(const std::string &name)
{
if(d_program > 0)
{
glBindFragDataLocation(d_program, 0, name.c_str() );
link();
}
}
//----------------------------------------------------------------------------//
bool OpenGL3Shader::isCreatedSuccessfully()
{
return d_createdSucessfully;
}
//----------------------------------------------------------------------------//
GLuint OpenGL3Shader::compile(GLuint type, const std::string &source)
{
// Create shader object
checkGLErrors();
GLuint shader = glCreateShader(type);
if (shader == 0)
{
std::stringstream stringStream;
stringStream << "Critical Error - Could not create shader object of type:" << type << ".";
CEGUI_THROW(RendererException(stringStream.str().c_str()));
return 0;
}
checkGLErrors();
// Define shader source and compile
const char* src = source.data();
int len = source.size();
glShaderSource(shader, 1, &src, &len);
glCompileShader(shader);
// Check for errors
GLint status;
glGetShaderiv(shader, GL_COMPILE_STATUS, &status);
if (status != GL_TRUE)
{
outputShaderLog(shader);
return 0;
}
checkGLErrors();
return shader;
}
//----------------------------------------------------------------------------//
void OpenGL3Shader::link()
{
// Attach shaders and link
glAttachShader(d_program, d_vertexShader);
if(d_geometryShader != 0)
glAttachShader(d_program, d_geometryShader);
if(d_fragmentShader !=0)
glAttachShader(d_program, d_fragmentShader);
glLinkProgram(d_program);
// Check for problems
GLint status;
glGetProgramiv(d_program, GL_LINK_STATUS, &status);
if (status != GL_TRUE)
{
outputProgramLog(d_program);
glDeleteProgram(d_program);
d_program = 0;
}
checkGLErrors();
if (d_program == 0)
return;
d_createdSucessfully = true;
checkGLErrors();
glBindFragDataLocation(d_program, 0, "out0"); // GL_COLOR_ATTACHMENT0
glBindFragDataLocation(d_program, 1, "out1"); // GL_COLOR_ATTACHMENT1
glBindFragDataLocation(d_program, 2, "out2"); // ...
glBindFragDataLocation(d_program, 3, "out3");
glBindFragDataLocation(d_program, 4, "out4");
glBindFragDataLocation(d_program, 5, "out5");
glBindFragDataLocation(d_program, 6, "out6");
glBindFragDataLocation(d_program, 7, "out7");
checkGLErrors();
}
//----------------------------------------------------------------------------//
void OpenGL3Shader::outputProgramLog(GLuint program)
{
char logBuffer[LOG_BUFFER_SIZE];
GLsizei length;
logBuffer[0] = '\0';
glGetProgramInfoLog(program, LOG_BUFFER_SIZE, &length, logBuffer);
if (length > 0)
{
std::stringstream sstream;
sstream << "OpenGL3Shader linking has failed.\n" << logBuffer;
CEGUI_THROW(RendererException(sstream.str().c_str()));
}
};
//----------------------------------------------------------------------------//
void OpenGL3Shader::outputShaderLog(GLuint shader)
{
char logBuffer[LOG_BUFFER_SIZE];
GLsizei length;
logBuffer[0] = '\0';
glGetShaderInfoLog(shader, LOG_BUFFER_SIZE, &length, logBuffer);
if (length > 0)
{
std::stringstream ss;
ss << "OpenGL3Shader compilation has failed.\n" << logBuffer;
CEGUI_THROW(RendererException(ss.str().c_str()));
}
};
//----------------------------------------------------------------------------//
void getGLErrors(const char *location)
{
GLenum error = glGetError();
if (error != GL_NO_ERROR)
{
std::stringstream stringStream;
stringStream << "OpenGL3Renderer: Notification - OpenGL error at " << location << ": " << std::endl;
switch (error)
{
case GL_INVALID_ENUM:
stringStream << "GL_INVALID_ENUM: enum argument out of range." << std::endl;
break;
case GL_INVALID_VALUE:
stringStream << "GL_INVALID_VALUE: Numeric argument out of range." << std::endl;
break;
case GL_INVALID_OPERATION:
stringStream << "GL_INVALID_OPERATION: Operation illegal in current state." << std::endl;
break;
case GL_INVALID_FRAMEBUFFER_OPERATION:
stringStream << "GL_INVALID_FRAMEBUFFER_OPERATION: Framebuffer object is not complete." << std::endl;
break;
case GL_OUT_OF_MEMORY:
stringStream << "GL_OUT_OF_MEMORY: Not enough memory left to execute command." << std::endl;
break;
default:
stringStream << "GL_ERROR: Unknown error." << std::endl;
}
if (CEGUI::Logger* logger = CEGUI::Logger::getSingletonPtr())
logger->logEvent(stringStream.str().c_str());
else
std::cerr << stringStream.str() << std::endl;
}
}
//----------------------------------------------------------------------------//
}
<commit_msg>MOD: variable name typo fix<commit_after>/***********************************************************************
filename: OpenGL3Shader.cpp
created: Wed, 8th Feb 2012
author: Lukas E Meindl
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
***************************************************************************/
#include <GL/glew.h>
#include "CEGUI/RendererModules/OpenGL/Shader.h"
#include "CEGUI/RendererModules/OpenGL/StateChangeWrapper.h"
#include "CEGUI/Logger.h"
#include "CEGUI/Exceptions.h"
#include <sstream>
#include <iostream>
namespace CEGUI
{
//----------------------------------------------------------------------------//
static const size_t LOG_BUFFER_SIZE = 8096;
//----------------------------------------------------------------------------//
OpenGL3Shader::OpenGL3Shader(const std::string& vertex_shader_source,
const std::string& fragment_shader_source,
OpenGL3StateChangeWrapper* glStateChanger) :
d_glStateChanger(glStateChanger),
d_createdSuccessfully(false),
d_vertexShader(0),
d_fragmentShader(0),
d_geometryShader(0),
d_program(0)
{
// Compile the shaders
d_vertexShader = compile(GL_VERTEX_SHADER, vertex_shader_source);
if (d_vertexShader == 0)
return;
checkGLErrors();
if(fragment_shader_source.length() > 0)
{
d_fragmentShader = compile(GL_FRAGMENT_SHADER, fragment_shader_source);
if (d_fragmentShader == 0)
return;
}
checkGLErrors();
d_program = glCreateProgram();
}
//----------------------------------------------------------------------------//
OpenGL3Shader::~OpenGL3Shader()
{
if(d_program != 0)
glDeleteProgram(d_program);
if(d_vertexShader != 0)
glDeleteShader(d_vertexShader);
if(d_fragmentShader != 0)
glDeleteShader(d_fragmentShader);
if(d_geometryShader != 0)
glDeleteShader(d_geometryShader);
}
//----------------------------------------------------------------------------//
void OpenGL3Shader::bind() const
{
d_glStateChanger->useProgram(d_program);
}
//----------------------------------------------------------------------------//
GLint OpenGL3Shader::getAttribLocation(const std::string &name) const
{
return glGetAttribLocation(d_program, name.c_str());
}
//----------------------------------------------------------------------------//
GLint OpenGL3Shader::getUniformLocation(const std::string &name) const
{
return glGetUniformLocation(d_program, name.c_str());
}
//----------------------------------------------------------------------------//
void OpenGL3Shader::bindFragDataLocation(const std::string &name)
{
if(d_program > 0)
{
glBindFragDataLocation(d_program, 0, name.c_str() );
link();
}
}
//----------------------------------------------------------------------------//
bool OpenGL3Shader::isCreatedSuccessfully()
{
return d_createdSuccessfully;
}
//----------------------------------------------------------------------------//
GLuint OpenGL3Shader::compile(GLuint type, const std::string &source)
{
// Create shader object
checkGLErrors();
GLuint shader = glCreateShader(type);
if (shader == 0)
{
std::stringstream stringStream;
stringStream << "Critical Error - Could not create shader object of type:" << type << ".";
CEGUI_THROW(RendererException(stringStream.str().c_str()));
return 0;
}
checkGLErrors();
// Define shader source and compile
const char* src = source.data();
int len = source.size();
glShaderSource(shader, 1, &src, &len);
glCompileShader(shader);
// Check for errors
GLint status;
glGetShaderiv(shader, GL_COMPILE_STATUS, &status);
if (status != GL_TRUE)
{
outputShaderLog(shader);
return 0;
}
checkGLErrors();
return shader;
}
//----------------------------------------------------------------------------//
void OpenGL3Shader::link()
{
// Attach shaders and link
glAttachShader(d_program, d_vertexShader);
if(d_geometryShader != 0)
glAttachShader(d_program, d_geometryShader);
if(d_fragmentShader !=0)
glAttachShader(d_program, d_fragmentShader);
glLinkProgram(d_program);
// Check for problems
GLint status;
glGetProgramiv(d_program, GL_LINK_STATUS, &status);
if (status != GL_TRUE)
{
outputProgramLog(d_program);
glDeleteProgram(d_program);
d_program = 0;
}
checkGLErrors();
if (d_program == 0)
return;
d_createdSuccessfully = true;
checkGLErrors();
glBindFragDataLocation(d_program, 0, "out0"); // GL_COLOR_ATTACHMENT0
glBindFragDataLocation(d_program, 1, "out1"); // GL_COLOR_ATTACHMENT1
glBindFragDataLocation(d_program, 2, "out2"); // ...
glBindFragDataLocation(d_program, 3, "out3");
glBindFragDataLocation(d_program, 4, "out4");
glBindFragDataLocation(d_program, 5, "out5");
glBindFragDataLocation(d_program, 6, "out6");
glBindFragDataLocation(d_program, 7, "out7");
checkGLErrors();
}
//----------------------------------------------------------------------------//
void OpenGL3Shader::outputProgramLog(GLuint program)
{
char logBuffer[LOG_BUFFER_SIZE];
GLsizei length;
logBuffer[0] = '\0';
glGetProgramInfoLog(program, LOG_BUFFER_SIZE, &length, logBuffer);
if (length > 0)
{
std::stringstream sstream;
sstream << "OpenGL3Shader linking has failed.\n" << logBuffer;
CEGUI_THROW(RendererException(sstream.str().c_str()));
}
};
//----------------------------------------------------------------------------//
void OpenGL3Shader::outputShaderLog(GLuint shader)
{
char logBuffer[LOG_BUFFER_SIZE];
GLsizei length;
logBuffer[0] = '\0';
glGetShaderInfoLog(shader, LOG_BUFFER_SIZE, &length, logBuffer);
if (length > 0)
{
std::stringstream ss;
ss << "OpenGL3Shader compilation has failed.\n" << logBuffer;
CEGUI_THROW(RendererException(ss.str().c_str()));
}
};
//----------------------------------------------------------------------------//
void getGLErrors(const char *location)
{
GLenum error = glGetError();
if (error != GL_NO_ERROR)
{
std::stringstream stringStream;
stringStream << "OpenGL3Renderer: Notification - OpenGL error at " << location << ": " << std::endl;
switch (error)
{
case GL_INVALID_ENUM:
stringStream << "GL_INVALID_ENUM: enum argument out of range." << std::endl;
break;
case GL_INVALID_VALUE:
stringStream << "GL_INVALID_VALUE: Numeric argument out of range." << std::endl;
break;
case GL_INVALID_OPERATION:
stringStream << "GL_INVALID_OPERATION: Operation illegal in current state." << std::endl;
break;
case GL_INVALID_FRAMEBUFFER_OPERATION:
stringStream << "GL_INVALID_FRAMEBUFFER_OPERATION: Framebuffer object is not complete." << std::endl;
break;
case GL_OUT_OF_MEMORY:
stringStream << "GL_OUT_OF_MEMORY: Not enough memory left to execute command." << std::endl;
break;
default:
stringStream << "GL_ERROR: Unknown error." << std::endl;
}
if (CEGUI::Logger* logger = CEGUI::Logger::getSingletonPtr())
logger->logEvent(stringStream.str().c_str());
else
std::cerr << stringStream.str() << std::endl;
}
}
//----------------------------------------------------------------------------//
}
<|endoftext|>
|
<commit_before>/* Copyright 2015 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/core/kernels/sendrecv_ops.h"
#include "tensorflow/core/framework/op.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/lib/strings/numbers.h"
#include "tensorflow/core/lib/strings/strcat.h"
#include "tensorflow/core/platform/logging.h"
namespace tensorflow {
static string GetRendezvousKeyPrefix(const string& send_device,
const string& recv_device,
const uint64 send_device_incarnation,
const string& tensor_name) {
return strings::StrCat(send_device, ";",
strings::FpToString(send_device_incarnation), ";",
recv_device, ";", tensor_name);
}
static void GetRendezvousKey(const string& key_prefix,
const FrameAndIter& frame_iter, string* key) {
key->clear();
strings::StrAppend(key, key_prefix, ";", frame_iter.frame_id, ":",
frame_iter.iter_id);
}
SendOp::SendOp(OpKernelConstruction* ctx) : OpKernel(ctx) {
string send_device;
OP_REQUIRES_OK(ctx, ctx->GetAttr("send_device", &send_device));
string recv_device;
OP_REQUIRES_OK(ctx, ctx->GetAttr("recv_device", &recv_device));
uint64 send_device_incarnation;
OP_REQUIRES_OK(
ctx, ctx->GetAttr("send_device_incarnation",
reinterpret_cast<int64*>(&send_device_incarnation)));
string tensor_name;
OP_REQUIRES_OK(ctx, ctx->GetAttr("tensor_name", &tensor_name));
key_prefix_ = GetRendezvousKeyPrefix(send_device, recv_device,
send_device_incarnation, tensor_name);
}
void SendOp::Compute(OpKernelContext* ctx) {
OP_REQUIRES(
ctx, ctx->rendezvous() != nullptr,
errors::Internal("Op kernel context needs to provide a rendezvous."));
Rendezvous::ParsedKey parsed;
GetRendezvousKey(key_prefix_, ctx->frame_iter(), &parsed.buf_);
VLOG(2) << "Send " << parsed.buf_;
OP_REQUIRES_OK(ctx, Rendezvous::ParseKey(parsed.buf_, &parsed));
// The device context may be passed between the Send/Recv
// boundary, so that the device context used to produce the Tensor
// is used when performing the copy on the recv side (which may be
// a different device).
Rendezvous::Args args;
args.device_context = ctx->op_device_context();
args.alloc_attrs = ctx->input_alloc_attr(0);
OP_REQUIRES_OK(ctx, ctx->rendezvous()->Send(parsed, args, ctx->input(0),
ctx->is_input_dead()));
}
REGISTER_KERNEL_BUILDER(Name("_Send").Device(DEVICE_CPU), SendOp);
REGISTER_KERNEL_BUILDER(Name("_Send").Device(DEVICE_GPU), SendOp);
REGISTER_KERNEL_BUILDER(Name("_HostSend").Device(DEVICE_CPU), SendOp);
REGISTER_KERNEL_BUILDER(
Name("_HostSend").Device(DEVICE_GPU).HostMemory("tensor"), SendOp);
RecvOp::RecvOp(OpKernelConstruction* ctx) : AsyncOpKernel(ctx) {
string send_device;
OP_REQUIRES_OK(ctx, ctx->GetAttr("send_device", &send_device));
string recv_device;
OP_REQUIRES_OK(ctx, ctx->GetAttr("recv_device", &recv_device));
uint64 send_device_incarnation;
OP_REQUIRES_OK(
ctx, ctx->GetAttr("send_device_incarnation",
reinterpret_cast<int64*>(&send_device_incarnation)));
string tensor_name;
OP_REQUIRES_OK(ctx, ctx->GetAttr("tensor_name", &tensor_name));
key_prefix_ = GetRendezvousKeyPrefix(send_device, recv_device,
send_device_incarnation, tensor_name);
}
void RecvOp::ComputeAsync(OpKernelContext* ctx, DoneCallback done) {
OP_REQUIRES(
ctx, ctx->rendezvous() != nullptr,
errors::Internal("Op kernel context needs to provide a rendezvous."));
Rendezvous::ParsedKey parsed;
GetRendezvousKey(key_prefix_, ctx->frame_iter(), &parsed.buf_);
VLOG(2) << "Recv " << parsed.buf_;
OP_REQUIRES_OK_ASYNC(ctx, Rendezvous::ParseKey(parsed.buf_, &parsed), done);
Rendezvous::Args args;
args.device_context = ctx->op_device_context();
args.alloc_attrs = ctx->output_alloc_attr(0);
using namespace std::placeholders;
Rendezvous::DoneCallback done_cb = std::bind(
[ctx](DoneCallback done,
// Begin unbound arguments.
const Status& s, const Rendezvous::Args& send_args,
const Rendezvous::Args& recv_args, const Tensor& val,
bool is_dead) {
ctx->SetStatus(s);
if (s.ok()) {
// 'ctx' allocates the output tensor of the expected type.
// The runtime checks whether the tensor received here is
// the same type.
if (!is_dead) {
ctx->set_output(0, val);
}
*ctx->is_output_dead() = is_dead;
}
done();
},
std::move(done), _1, _2, _3, _4, _5);
ctx->rendezvous()->RecvAsync(parsed, args, std::move(done_cb));
}
REGISTER_KERNEL_BUILDER(Name("_Recv").Device(DEVICE_CPU), RecvOp);
REGISTER_KERNEL_BUILDER(Name("_Recv").Device(DEVICE_GPU), RecvOp);
REGISTER_KERNEL_BUILDER(Name("_HostRecv").Device(DEVICE_CPU), RecvOp);
REGISTER_KERNEL_BUILDER(
Name("_HostRecv").Device(DEVICE_GPU).HostMemory("tensor"), RecvOp);
} // end namespace tensorflow
<commit_msg>_Send and _Recv Ops has been registered for SYCL device.<commit_after>/* Copyright 2015 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/core/kernels/sendrecv_ops.h"
#include "tensorflow/core/framework/op.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/lib/strings/numbers.h"
#include "tensorflow/core/lib/strings/strcat.h"
#include "tensorflow/core/platform/logging.h"
namespace tensorflow {
static string GetRendezvousKeyPrefix(const string& send_device,
const string& recv_device,
const uint64 send_device_incarnation,
const string& tensor_name) {
return strings::StrCat(send_device, ";",
strings::FpToString(send_device_incarnation), ";",
recv_device, ";", tensor_name);
}
static void GetRendezvousKey(const string& key_prefix,
const FrameAndIter& frame_iter, string* key) {
key->clear();
strings::StrAppend(key, key_prefix, ";", frame_iter.frame_id, ":",
frame_iter.iter_id);
}
SendOp::SendOp(OpKernelConstruction* ctx) : OpKernel(ctx) {
string send_device;
OP_REQUIRES_OK(ctx, ctx->GetAttr("send_device", &send_device));
string recv_device;
OP_REQUIRES_OK(ctx, ctx->GetAttr("recv_device", &recv_device));
uint64 send_device_incarnation;
OP_REQUIRES_OK(
ctx, ctx->GetAttr("send_device_incarnation",
reinterpret_cast<int64*>(&send_device_incarnation)));
string tensor_name;
OP_REQUIRES_OK(ctx, ctx->GetAttr("tensor_name", &tensor_name));
key_prefix_ = GetRendezvousKeyPrefix(send_device, recv_device,
send_device_incarnation, tensor_name);
}
void SendOp::Compute(OpKernelContext* ctx) {
OP_REQUIRES(
ctx, ctx->rendezvous() != nullptr,
errors::Internal("Op kernel context needs to provide a rendezvous."));
Rendezvous::ParsedKey parsed;
GetRendezvousKey(key_prefix_, ctx->frame_iter(), &parsed.buf_);
VLOG(2) << "Send " << parsed.buf_;
OP_REQUIRES_OK(ctx, Rendezvous::ParseKey(parsed.buf_, &parsed));
// The device context may be passed between the Send/Recv
// boundary, so that the device context used to produce the Tensor
// is used when performing the copy on the recv side (which may be
// a different device).
Rendezvous::Args args;
args.device_context = ctx->op_device_context();
args.alloc_attrs = ctx->input_alloc_attr(0);
OP_REQUIRES_OK(ctx, ctx->rendezvous()->Send(parsed, args, ctx->input(0),
ctx->is_input_dead()));
}
REGISTER_KERNEL_BUILDER(Name("_Send").Device(DEVICE_CPU), SendOp);
REGISTER_KERNEL_BUILDER(Name("_Send").Device(DEVICE_GPU), SendOp);
REGISTER_KERNEL_BUILDER(Name("_Send").Device(DEVICE_SYCL), SendOp);
REGISTER_KERNEL_BUILDER(Name("_HostSend").Device(DEVICE_CPU), SendOp);
REGISTER_KERNEL_BUILDER(
Name("_HostSend").Device(DEVICE_GPU).HostMemory("tensor"), SendOp);
RecvOp::RecvOp(OpKernelConstruction* ctx) : AsyncOpKernel(ctx) {
string send_device;
OP_REQUIRES_OK(ctx, ctx->GetAttr("send_device", &send_device));
string recv_device;
OP_REQUIRES_OK(ctx, ctx->GetAttr("recv_device", &recv_device));
uint64 send_device_incarnation;
OP_REQUIRES_OK(
ctx, ctx->GetAttr("send_device_incarnation",
reinterpret_cast<int64*>(&send_device_incarnation)));
string tensor_name;
OP_REQUIRES_OK(ctx, ctx->GetAttr("tensor_name", &tensor_name));
key_prefix_ = GetRendezvousKeyPrefix(send_device, recv_device,
send_device_incarnation, tensor_name);
}
void RecvOp::ComputeAsync(OpKernelContext* ctx, DoneCallback done) {
OP_REQUIRES(
ctx, ctx->rendezvous() != nullptr,
errors::Internal("Op kernel context needs to provide a rendezvous."));
Rendezvous::ParsedKey parsed;
GetRendezvousKey(key_prefix_, ctx->frame_iter(), &parsed.buf_);
VLOG(2) << "Recv " << parsed.buf_;
OP_REQUIRES_OK_ASYNC(ctx, Rendezvous::ParseKey(parsed.buf_, &parsed), done);
Rendezvous::Args args;
args.device_context = ctx->op_device_context();
args.alloc_attrs = ctx->output_alloc_attr(0);
using namespace std::placeholders;
Rendezvous::DoneCallback done_cb = std::bind(
[ctx](DoneCallback done,
// Begin unbound arguments.
const Status& s, const Rendezvous::Args& send_args,
const Rendezvous::Args& recv_args, const Tensor& val,
bool is_dead) {
ctx->SetStatus(s);
if (s.ok()) {
// 'ctx' allocates the output tensor of the expected type.
// The runtime checks whether the tensor received here is
// the same type.
if (!is_dead) {
ctx->set_output(0, val);
}
*ctx->is_output_dead() = is_dead;
}
done();
},
std::move(done), _1, _2, _3, _4, _5);
ctx->rendezvous()->RecvAsync(parsed, args, std::move(done_cb));
}
REGISTER_KERNEL_BUILDER(Name("_Recv").Device(DEVICE_CPU), RecvOp);
REGISTER_KERNEL_BUILDER(Name("_Recv").Device(DEVICE_GPU), RecvOp);
REGISTER_KERNEL_BUILDER(Name("_Recv").Device(DEVICE_SYCL), RecvOp);
REGISTER_KERNEL_BUILDER(Name("_HostRecv").Device(DEVICE_CPU), RecvOp);
REGISTER_KERNEL_BUILDER(
Name("_HostRecv").Device(DEVICE_GPU).HostMemory("tensor"), RecvOp);
} // end namespace tensorflow
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: ImplChartModel.hxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: rt $ $Date: 2005-09-08 01:01:02 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef CHART_IMPLCHARTMODEL_HXX
#define CHART_IMPLCHARTMODEL_HXX
#ifndef _COM_SUN_STAR_CHART2_XDATASOURCE_HPP_
#include <com/sun/star/chart2/XDataSource.hpp>
#endif
#ifndef _COM_SUN_STAR_CHART2_XDATASERIES_HPP_
#include <com/sun/star/chart2/XDataSeries.hpp>
#endif
#ifndef _COM_SUN_STAR_CHART2_XDIAGRAM_HPP_
#include <com/sun/star/chart2/XDiagram.hpp>
#endif
#ifndef _COM_SUN_STAR_CHART2_XDATAPROVIDER_HPP_
#include <com/sun/star/chart2/XDataProvider.hpp>
#endif
#ifndef _COM_SUN_STAR_CHART2_XCHARTTYPEMANAGER_HPP_
#include <com/sun/star/chart2/XChartTypeManager.hpp>
#endif
#ifndef _COM_SUN_STAR_CHART2_XCHARTTYPETEMPLATE_HPP_
#include <com/sun/star/chart2/XChartTypeTemplate.hpp>
#endif
#ifndef _COM_SUN_STAR_CHART2_XTITLE_HPP_
#include <com/sun/star/chart2/XTitle.hpp>
#endif
#ifndef _COM_SUN_STAR_CHART2_XCHARTDOCUMENT_HPP_
#include <com/sun/star/chart2/XChartDocument.hpp>
#endif
// #ifndef _COM_SUN_STAR_LAYOUT_XSPLITLAYOUTCONTAINER_HPP_
// #include <com/sun/star/layout/XSplitLayoutContainer.hpp>
// #endif
#ifndef _COM_SUN_STAR_CONTAINER_NOSUCHELEMENTEXCEPTION_HPP_
#include <com/sun/star/container/NoSuchElementException.hpp>
#endif
#ifndef _CPPUHELPER_WEAKREF_HXX_
#include <cppuhelper/weakref.hxx>
#endif
#include <vector>
namespace com { namespace sun { namespace star {
namespace container {
class XNameAccess;
}
namespace uno {
class XComponentContext;
}
namespace sheet {
class XSpreadsheetDocument;
}
}}}
namespace chart
{
namespace impl
{
class ImplChartModel
{
public:
ImplChartModel( ::com::sun::star::uno::Reference<
::com::sun::star::uno::XComponentContext > const & xContext );
// ::com::sun::star::uno::Sequence<
// ::com::sun::star::uno::Reference<
// ::com::sun::star::chart2::XDataSeries > >
// GetDataSeries() const;
::com::sun::star::uno::Reference<
::com::sun::star::container::XNameAccess >
GetStyleFamilies();
// Diagram Access
void RemoveAllDiagrams();
/** @return true, if the chart was found and removed, false otherwise.
*/
bool RemoveDiagram( const ::com::sun::star::uno::Reference<
::com::sun::star::chart2::XDiagram > & xDiagram );
void AppendDiagram( const ::com::sun::star::uno::Reference<
::com::sun::star::chart2::XDiagram > & xDiagram );
::com::sun::star::uno::Reference<
::com::sun::star::chart2::XDiagram >
GetDiagram( size_t nIndex ) const
throw( ::com::sun::star::container::NoSuchElementException );
void SetDataProvider( const ::com::sun::star::uno::Reference<
::com::sun::star::chart2::XDataProvider > & xProvider );
void SAL_CALL SetRangeRepresentation( const ::rtl::OUString& aRangeRepresentation )
throw (::com::sun::star::lang::IllegalArgumentException);
void SetChartTypeManager(
const ::com::sun::star::uno::Reference<
::com::sun::star::chart2::XChartTypeManager > & xManager );
::com::sun::star::uno::Reference<
::com::sun::star::chart2::XChartTypeManager >
GetChartTypeManager();
void SetChartTypeTemplate(
const ::com::sun::star::uno::Reference<
::com::sun::star::chart2::XChartTypeTemplate > & xTemplate );
::com::sun::star::uno::Reference<
::com::sun::star::chart2::XChartTypeTemplate >
GetChartTypeTemplate();
// void SetSplitLayoutContainer(
// const ::com::sun::star::uno::Reference<
// ::com::sun::star::layout::XSplitLayoutContainer > & xLayoutCnt );
// ::com::sun::star::uno::Reference<
// ::com::sun::star::layout::XSplitLayoutContainer > GetSplitLayoutContainer();
::com::sun::star::uno::Reference< ::com::sun::star::chart2::XTitle >
GetTitle();
void SetTitle( const ::com::sun::star::uno::Reference<
::com::sun::star::chart2::XTitle >& rTitle );
/** Is called by the ChartModel's XComponent::dispose() to notify the
impl-class to release resources
*/
void dispose();
::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >
GetPageBackground();
void CloneData( const ::com::sun::star::uno::Reference<
::com::sun::star::sheet::XSpreadsheetDocument > & xCalcDoc );
void CreateDefaultData( const ::com::sun::star::uno::Reference<
::com::sun::star::sheet::XSpreadsheetDocument > & xCalcDoc );
private:
void ReadData( const ::rtl::OUString & rRangeRepresentation );
void CreateDefaultChart();
void InterpretData();
// void CreateDefaultLayout();
::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > m_xContext;
::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess > m_xFamilies;
// Data Access (deprecated, temporary solution)
::com::sun::star::uno::Reference< ::com::sun::star::chart2::XDataSource > m_xChartData;
::com::sun::star::uno::Reference< ::com::sun::star::chart2::XDataProvider > m_xDataProvider;
::std::vector< ::com::sun::star::uno::Reference<
::com::sun::star::chart2::XDataSeries > > m_aInterpretedData;
::com::sun::star::uno::Reference< ::com::sun::star::chart2::XChartTypeManager >
m_xChartTypeManager;
::com::sun::star::uno::Reference< ::com::sun::star::chart2::XChartTypeTemplate >
m_xChartTypeTemplate;
// Diagram Access
typedef ::std::vector< ::com::sun::star::uno::Reference<
::com::sun::star::chart2::XDiagram > >
tDiagramContainer;
tDiagramContainer m_aDiagrams;
// ::com::sun::star::uno::Reference< ::com::sun::star::layout::XSplitLayoutContainer >
// m_xLayoutContainer;
::com::sun::star::uno::Reference< ::com::sun::star::chart2::XTitle >
m_xTitle;
bool m_bIsDisposed;
::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >
m_xPageBackground;
};
} // namespace impl
} // namespace chart
// CHART_IMPLCHARTMODEL_HXX
#endif
<commit_msg>INTEGRATION: CWS chart2mst3 (1.5.4); FILE MERGED 2007/02/09 17:29:20 bm 1.5.4.27: XChartDocument::createInternalDataProvider() works like expected now 2005/11/11 15:02:51 bm 1.5.4.26: notify changes 2005/10/14 16:58:44 bm 1.5.4.25: model listener mechanism 2005/10/07 11:55:30 bm 1.5.4.24: RESYNC: (1.5-1.6); FILE MERGED 2005/09/08 11:40:34 iha 1.5.4.23: set data provider and number formatter in the filter and not in the model load methods thus binary loading also gets the correct dataprovider and numberformatter 2005/09/07 14:43:16 bm 1.5.4.22: XChartDocument: +hasInternalDataProvider, -getDataEditorForInternalData 2005/09/05 16:52:54 iha 1.5.4.21: hold own numberformatter by reference only (don't delete it as it is offered as reference to the outside) 2005/08/15 14:02:18 bm 1.5.4.20: SetRangeRepresentation: transport string as const ref to allow temporaries 2005/08/15 13:03:13 bm 1.5.4.19: internal methods for setting data (ImplChartModel) changed 2005/08/11 16:05:40 bm 1.5.4.18: change internal data to a new class that does not need Calc 2005/07/21 14:47:08 bm 1.5.4.17: support for number formats from data provider 2005/07/08 16:46:19 bm 1.5.4.16: marker table removed 2005/06/08 14:49:12 bm 1.5.4.15: createInternalData needs the parent storage from ChartModel 2005/06/08 09:13:27 bm 1.5.4.14: all load/save/modify functionality put in a separate file for clarity 2005/06/07 15:35:04 iha 1.5.4.13: offer SvNumberformatter via unotunnel 2005/05/31 18:51:27 iha 1.5.4.12: keep gradient table etc. in model 2005/05/09 09:51:17 bm 1.5.4.11: moved parts of API to data namespace 2005/04/01 16:25:39 bm 1.5.4.10: shared data for different chart models 2005/03/24 17:04:29 bm 1.5.4.9: Cloneable implementation 2004/09/09 15:12:36 bm 1.5.4.8: fixing loading of series: newly interpreted series have to be attached to the tree correctly 2004/09/08 15:36:42 bm 1.5.4.7: enable loading data series. There is one Diagram deletion too much which results in lost properties 2004/06/30 11:53:31 bm 1.5.4.6: delete Diagram when setting new DataProvider create new Diagram in SetNewData if necessary 2004/05/10 14:38:03 bm 1.5.4.5: +SetNewData to set only a new m_xChartData at the current tree 2004/05/10 11:06:22 bm 1.5.4.4: make CreateDefaultData public for calling from ChartModel::initNew 2004/03/19 14:32:55 bm 1.5.4.3: XDataSource now contains XLabeledDataSources 2004/03/02 09:42:13 bm 1.5.4.2: +GetDataProvider (interface XChartDocument changed) 2004/02/13 16:51:32 bm 1.5.4.1: join from changes on branch bm_post_chart01<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: ImplChartModel.hxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: vg $ $Date: 2007-05-22 18:38:21 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef CHART_IMPLCHARTMODEL_HXX
#define CHART_IMPLCHARTMODEL_HXX
#ifndef _COM_SUN_STAR_CHART2_DATA_XDATASOURCE_HPP_
#include <com/sun/star/chart2/data/XDataSource.hpp>
#endif
#ifndef _COM_SUN_STAR_CHART2_XDATASERIES_HPP_
#include <com/sun/star/chart2/XDataSeries.hpp>
#endif
#ifndef _COM_SUN_STAR_CHART2_DATA_XLABELEDDATASEQUENCE_HPP_
#include <com/sun/star/chart2/data/XLabeledDataSequence.hpp>
#endif
#ifndef _COM_SUN_STAR_CHART2_XDIAGRAM_HPP_
#include <com/sun/star/chart2/XDiagram.hpp>
#endif
#ifndef _COM_SUN_STAR_CHART2_DATA_XDATAPROVIDER_HPP_
#include <com/sun/star/chart2/data/XDataProvider.hpp>
#endif
#ifndef _COM_SUN_STAR_CHART2_XCHARTTYPEMANAGER_HPP_
#include <com/sun/star/chart2/XChartTypeManager.hpp>
#endif
#ifndef _COM_SUN_STAR_CHART2_XCHARTTYPETEMPLATE_HPP_
#include <com/sun/star/chart2/XChartTypeTemplate.hpp>
#endif
#ifndef _COM_SUN_STAR_CHART2_XTITLE_HPP_
#include <com/sun/star/chart2/XTitle.hpp>
#endif
#ifndef _COM_SUN_STAR_CHART2_XCHARTDOCUMENT_HPP_
#include <com/sun/star/chart2/XChartDocument.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMECONTAINER_HPP_
#include <com/sun/star/container/XNameContainer.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_NOSUCHELEMENTEXCEPTION_HPP_
#include <com/sun/star/container/NoSuchElementException.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_IOEXCEPTION_HPP_
#include <com/sun/star/io/IOException.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_XNUMBERFORMATSSUPPLIER_HPP_
#include <com/sun/star/util/XNumberFormatsSupplier.hpp>
#endif
#ifndef _CPPUHELPER_WEAKREF_HXX_
#include <cppuhelper/weakref.hxx>
#endif
#include "ChartData.hxx"
#include <vector>
#include <memory>
#include <boost/shared_ptr.hpp>
namespace com { namespace sun { namespace star {
namespace container {
class XNameAccess;
}
namespace uno {
class XComponentContext;
}
namespace embed {
class XStorage;
}
namespace document {
class XFilter;
}
namespace util {
class XModifyListener;
}
}}}
class SvNumberFormatter;
namespace chart
{
namespace impl
{
class ImplChartModel
{
typedef ::com::sun::star::uno::Reference< ::com::sun::star::chart2::data::XDataSource > tDataSourceType;
public:
ImplChartModel( ::com::sun::star::uno::Reference<
::com::sun::star::uno::XComponentContext > const & xContext,
const ::com::sun::star::uno::Reference<
::com::sun::star::util::XModifyListener > & xListener );
explicit ImplChartModel( const ImplChartModel & rOther,
const ::com::sun::star::uno::Reference<
::com::sun::star::util::XModifyListener > & xListener );
~ImplChartModel();
// ::com::sun::star::uno::Sequence<
// ::com::sun::star::uno::Reference<
// ::com::sun::star::chart2::XDataSeries > >
// GetDataSeries() const;
::com::sun::star::uno::Reference<
::com::sun::star::container::XNameAccess >
GetStyleFamilies();
// Diagram Access
void RemoveAllDiagrams();
/** @return true, if the chart was found and removed, false otherwise.
*/
bool RemoveDiagram( const ::com::sun::star::uno::Reference<
::com::sun::star::chart2::XDiagram > & xDiagram );
void AppendDiagram( const ::com::sun::star::uno::Reference<
::com::sun::star::chart2::XDiagram > & xDiagram );
::com::sun::star::uno::Reference<
::com::sun::star::chart2::XDiagram >
GetDiagram( size_t nIndex ) const
throw( ::com::sun::star::container::NoSuchElementException );
void SetDataProvider( const ::com::sun::star::uno::Reference<
::com::sun::star::chart2::data::XDataProvider > & xProvider );
::com::sun::star::uno::Reference<
::com::sun::star::chart2::data::XDataProvider > GetDataProvider() const;
void CreateInternalDataProvider(
bool bCloneExistingData,
const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XChartDocument > & xChartDoc );
bool HasInternalDataProvider() const;
::com::sun::star::uno::Reference<
::com::sun::star::chart2::data::XDataSource > SAL_CALL SetArguments(
const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > & rArgs,
bool bSetData )
throw (::com::sun::star::lang::IllegalArgumentException);
void SetChartTypeManager(
const ::com::sun::star::uno::Reference<
::com::sun::star::chart2::XChartTypeManager > & xManager );
::com::sun::star::uno::Reference<
::com::sun::star::chart2::XChartTypeManager >
GetChartTypeManager();
void SetChartTypeTemplate(
const ::com::sun::star::uno::Reference<
::com::sun::star::chart2::XChartTypeTemplate > & xTemplate );
::com::sun::star::uno::Reference<
::com::sun::star::chart2::XChartTypeTemplate >
GetChartTypeTemplate();
::com::sun::star::uno::Reference< ::com::sun::star::chart2::XTitle >
GetTitle();
void SetTitle( const ::com::sun::star::uno::Reference<
::com::sun::star::chart2::XTitle >& rTitle );
/** Is called by the ChartModel's XComponent::dispose() to notify the
impl-class to release resources
*/
void dispose();
::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >
GetPageBackground();
::std::vector< ::com::sun::star::uno::Reference<
::com::sun::star::chart2::data::XLabeledDataSequence > > GetData();
void CreateDefaultChart();
::com::sun::star::uno::Reference<
::com::sun::star::uno::XInterface > GetDashTable();
::com::sun::star::uno::Reference<
::com::sun::star::uno::XInterface > GetGradientTable();
::com::sun::star::uno::Reference<
::com::sun::star::uno::XInterface > GetHatchTable();
::com::sun::star::uno::Reference<
::com::sun::star::uno::XInterface > GetBitmapTable();
::com::sun::star::uno::Reference<
::com::sun::star::uno::XInterface > GetTransparencyGradientTable();
::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatsSupplier >
GetNumberFormatsSupplier();
void SetNumberFormatsSupplier(
const ::com::sun::star::uno::Reference<
::com::sun::star::util::XNumberFormatsSupplier > & xNumberFormatsSupplier );
private:
void CreateDefaultChartTypeTemplate();
::com::sun::star::uno::Reference<
::com::sun::star::chart2::data::XDataSource > CreateDefaultData();
void SetNewData( const ::com::sun::star::uno::Reference<
::com::sun::star::chart2::data::XDataSource > & xDataSource,
const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > & rArgs );
::com::sun::star::uno::Reference<
::com::sun::star::chart2::data::XDataSource > SAL_CALL SetRangeRepresentation(
const ::rtl::OUString & rRangeRepresentation, bool bSetData )
throw (::com::sun::star::lang::IllegalArgumentException);
// void CreateDefaultLayout();
::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > m_xContext;
::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess > m_xFamilies;
::boost::shared_ptr< ChartData > m_spChartData;
// Data Access (deprecated, temporary solution)
// ::com::sun::star::uno::Reference< ::com::sun::star::chart2::data::XDataSource > m_xChartData;
// ::com::sun::star::uno::Reference< ::com::sun::star::chart2::data::XDataProvider > m_xDataProvider;
// ::std::vector< ::com::sun::star::uno::Reference<
// ::com::sun::star::chart2::XDataSeries > > m_aInterpretedData;
::com::sun::star::uno::Reference< com::sun::star::util::XNumberFormatsSupplier >
m_xOwnNumberFormatsSupplier;
::com::sun::star::uno::Reference< com::sun::star::util::XNumberFormatsSupplier >
m_xNumberFormatsSupplier;
::com::sun::star::uno::Reference< ::com::sun::star::chart2::XChartTypeManager >
m_xChartTypeManager;
::com::sun::star::uno::Reference< ::com::sun::star::chart2::XChartTypeTemplate >
m_xChartTypeTemplate;
// Diagram Access
typedef ::std::vector< ::com::sun::star::uno::Reference<
::com::sun::star::chart2::XDiagram > >
tDiagramContainer;
tDiagramContainer m_aDiagrams;
::com::sun::star::uno::Reference< ::com::sun::star::chart2::XTitle >
m_xTitle;
bool m_bIsDisposed;
::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >
m_xPageBackground;
::com::sun::star::uno::Reference< ::com::sun::star::container::XNameContainer > m_xDashTable;
::com::sun::star::uno::Reference< ::com::sun::star::container::XNameContainer > m_xGradientTable;
::com::sun::star::uno::Reference< ::com::sun::star::container::XNameContainer > m_xHatchTable;
::com::sun::star::uno::Reference< ::com::sun::star::container::XNameContainer > m_xBitmapTable;
::com::sun::star::uno::Reference< ::com::sun::star::container::XNameContainer > m_xTransparencyGradientTable;
::com::sun::star::uno::Reference< ::com::sun::star::util::XModifyListener > m_xModifyListener;
};
} // namespace impl
} // namespace chart
// CHART_IMPLCHARTMODEL_HXX
#endif
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: LabeledDataSequence.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: ihi $ $Date: 2008-01-14 14:03:56 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_chart2.hxx"
#include "LabeledDataSequence.hxx"
#include "ModifyListenerHelper.hxx"
#include "macros.hxx"
using namespace ::com::sun::star;
using ::com::sun::star::uno::Reference;
using ::com::sun::star::uno::Sequence;
using ::rtl::OUString;
namespace chart
{
LabeledDataSequence::LabeledDataSequence( const Reference< uno::XComponentContext > & xContext ) :
m_xContext( xContext ),
m_xModifyEventForwarder( new ModifyListenerHelper::ModifyEventForwarder())
{}
LabeledDataSequence::LabeledDataSequence(
const uno::Reference< chart2::data::XDataSequence > & rValues ) :
m_xData( rValues ),
m_xModifyEventForwarder( new ModifyListenerHelper::ModifyEventForwarder())
{
ModifyListenerHelper::addListener( m_xData, m_xModifyEventForwarder );
}
LabeledDataSequence::LabeledDataSequence(
const uno::Reference< chart2::data::XDataSequence > & rValues,
const uno::Reference< chart2::data::XDataSequence > & rLabel ) :
m_xData( rValues ),
m_xLabel( rLabel ),
m_xModifyEventForwarder( new ModifyListenerHelper::ModifyEventForwarder())
{
ModifyListenerHelper::addListener( m_xData, m_xModifyEventForwarder );
ModifyListenerHelper::addListener( m_xLabel, m_xModifyEventForwarder );
}
LabeledDataSequence::~LabeledDataSequence()
{
if( m_xModifyEventForwarder.is())
{
if( m_xData.is())
ModifyListenerHelper::removeListener( m_xData, m_xModifyEventForwarder );
if( m_xLabel.is())
ModifyListenerHelper::removeListener( m_xLabel, m_xModifyEventForwarder );
}
}
// ____ XLabeledDataSequence ____
uno::Reference< chart2::data::XDataSequence > SAL_CALL LabeledDataSequence::getValues()
throw (uno::RuntimeException)
{
return m_xData;
}
void SAL_CALL LabeledDataSequence::setValues(
const uno::Reference< chart2::data::XDataSequence >& xSequence )
throw (uno::RuntimeException)
{
if( m_xData != xSequence )
{
ModifyListenerHelper::removeListener( m_xData, m_xModifyEventForwarder );
m_xData = xSequence;
ModifyListenerHelper::addListener( m_xData, m_xModifyEventForwarder );
}
}
uno::Reference< chart2::data::XDataSequence > SAL_CALL LabeledDataSequence::getLabel()
throw (uno::RuntimeException)
{
return m_xLabel;
}
void SAL_CALL LabeledDataSequence::setLabel(
const uno::Reference< chart2::data::XDataSequence >& xSequence )
throw (uno::RuntimeException)
{
if( m_xLabel != xSequence )
{
ModifyListenerHelper::removeListener( m_xLabel, m_xModifyEventForwarder );
m_xLabel = xSequence;
ModifyListenerHelper::addListener( m_xLabel, m_xModifyEventForwarder );
}
}
// ____ XCloneable ____
uno::Reference< util::XCloneable > SAL_CALL LabeledDataSequence::createClone()
throw (uno::RuntimeException)
{
uno::Reference< chart2::data::XDataSequence > xNewValues( m_xData );
uno::Reference< chart2::data::XDataSequence > xNewLabel( m_xLabel );
uno::Reference< util::XCloneable > xLabelCloneable( m_xLabel, uno::UNO_QUERY );
if( xLabelCloneable.is())
xNewLabel.set( xLabelCloneable->createClone(), uno::UNO_QUERY );
uno::Reference< util::XCloneable > xValuesCloneable( m_xData, uno::UNO_QUERY );
if( xValuesCloneable.is())
xNewValues.set( xValuesCloneable->createClone(), uno::UNO_QUERY );
return uno::Reference< util::XCloneable >(
new LabeledDataSequence( xNewValues, xNewLabel ) );
}
// ____ XModifyBroadcaster ____
void SAL_CALL LabeledDataSequence::addModifyListener( const Reference< util::XModifyListener >& aListener )
throw (uno::RuntimeException)
{
try
{
Reference< util::XModifyBroadcaster > xBroadcaster( m_xModifyEventForwarder, uno::UNO_QUERY_THROW );
xBroadcaster->addModifyListener( aListener );
}
catch( const uno::Exception & ex )
{
ASSERT_EXCEPTION( ex );
}
}
void SAL_CALL LabeledDataSequence::removeModifyListener( const Reference< util::XModifyListener >& aListener )
throw (uno::RuntimeException)
{
try
{
Reference< util::XModifyBroadcaster > xBroadcaster( m_xModifyEventForwarder, uno::UNO_QUERY_THROW );
xBroadcaster->removeModifyListener( aListener );
}
catch( const uno::Exception & ex )
{
ASSERT_EXCEPTION( ex );
}
}
void LabeledDataSequence::fireModifyEvent()
{
m_xModifyEventForwarder->modified( lang::EventObject( static_cast< uno::XWeak* >( this )));
}
// ================================================================================
Sequence< OUString > LabeledDataSequence::getSupportedServiceNames_Static()
{
Sequence< OUString > aServices( 1 );
aServices[ 0 ] = C2U( "com.sun.star.chart2.data.LabeledDataSequence" );
return aServices;
}
// implement XServiceInfo methods basing upon getSupportedServiceNames_Static
APPHELPER_XSERVICEINFO_IMPL( LabeledDataSequence,
C2U( "com.sun.star.comp.chart2.LabeledDataSequence" ))
// ================================================================================
} // namespace chart
<commit_msg>INTEGRATION: CWS changefileheader (1.3.44); FILE MERGED 2008/03/28 16:44:22 rt 1.3.44.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: LabeledDataSequence.cxx,v $
* $Revision: 1.4 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_chart2.hxx"
#include "LabeledDataSequence.hxx"
#include "ModifyListenerHelper.hxx"
#include "macros.hxx"
using namespace ::com::sun::star;
using ::com::sun::star::uno::Reference;
using ::com::sun::star::uno::Sequence;
using ::rtl::OUString;
namespace chart
{
LabeledDataSequence::LabeledDataSequence( const Reference< uno::XComponentContext > & xContext ) :
m_xContext( xContext ),
m_xModifyEventForwarder( new ModifyListenerHelper::ModifyEventForwarder())
{}
LabeledDataSequence::LabeledDataSequence(
const uno::Reference< chart2::data::XDataSequence > & rValues ) :
m_xData( rValues ),
m_xModifyEventForwarder( new ModifyListenerHelper::ModifyEventForwarder())
{
ModifyListenerHelper::addListener( m_xData, m_xModifyEventForwarder );
}
LabeledDataSequence::LabeledDataSequence(
const uno::Reference< chart2::data::XDataSequence > & rValues,
const uno::Reference< chart2::data::XDataSequence > & rLabel ) :
m_xData( rValues ),
m_xLabel( rLabel ),
m_xModifyEventForwarder( new ModifyListenerHelper::ModifyEventForwarder())
{
ModifyListenerHelper::addListener( m_xData, m_xModifyEventForwarder );
ModifyListenerHelper::addListener( m_xLabel, m_xModifyEventForwarder );
}
LabeledDataSequence::~LabeledDataSequence()
{
if( m_xModifyEventForwarder.is())
{
if( m_xData.is())
ModifyListenerHelper::removeListener( m_xData, m_xModifyEventForwarder );
if( m_xLabel.is())
ModifyListenerHelper::removeListener( m_xLabel, m_xModifyEventForwarder );
}
}
// ____ XLabeledDataSequence ____
uno::Reference< chart2::data::XDataSequence > SAL_CALL LabeledDataSequence::getValues()
throw (uno::RuntimeException)
{
return m_xData;
}
void SAL_CALL LabeledDataSequence::setValues(
const uno::Reference< chart2::data::XDataSequence >& xSequence )
throw (uno::RuntimeException)
{
if( m_xData != xSequence )
{
ModifyListenerHelper::removeListener( m_xData, m_xModifyEventForwarder );
m_xData = xSequence;
ModifyListenerHelper::addListener( m_xData, m_xModifyEventForwarder );
}
}
uno::Reference< chart2::data::XDataSequence > SAL_CALL LabeledDataSequence::getLabel()
throw (uno::RuntimeException)
{
return m_xLabel;
}
void SAL_CALL LabeledDataSequence::setLabel(
const uno::Reference< chart2::data::XDataSequence >& xSequence )
throw (uno::RuntimeException)
{
if( m_xLabel != xSequence )
{
ModifyListenerHelper::removeListener( m_xLabel, m_xModifyEventForwarder );
m_xLabel = xSequence;
ModifyListenerHelper::addListener( m_xLabel, m_xModifyEventForwarder );
}
}
// ____ XCloneable ____
uno::Reference< util::XCloneable > SAL_CALL LabeledDataSequence::createClone()
throw (uno::RuntimeException)
{
uno::Reference< chart2::data::XDataSequence > xNewValues( m_xData );
uno::Reference< chart2::data::XDataSequence > xNewLabel( m_xLabel );
uno::Reference< util::XCloneable > xLabelCloneable( m_xLabel, uno::UNO_QUERY );
if( xLabelCloneable.is())
xNewLabel.set( xLabelCloneable->createClone(), uno::UNO_QUERY );
uno::Reference< util::XCloneable > xValuesCloneable( m_xData, uno::UNO_QUERY );
if( xValuesCloneable.is())
xNewValues.set( xValuesCloneable->createClone(), uno::UNO_QUERY );
return uno::Reference< util::XCloneable >(
new LabeledDataSequence( xNewValues, xNewLabel ) );
}
// ____ XModifyBroadcaster ____
void SAL_CALL LabeledDataSequence::addModifyListener( const Reference< util::XModifyListener >& aListener )
throw (uno::RuntimeException)
{
try
{
Reference< util::XModifyBroadcaster > xBroadcaster( m_xModifyEventForwarder, uno::UNO_QUERY_THROW );
xBroadcaster->addModifyListener( aListener );
}
catch( const uno::Exception & ex )
{
ASSERT_EXCEPTION( ex );
}
}
void SAL_CALL LabeledDataSequence::removeModifyListener( const Reference< util::XModifyListener >& aListener )
throw (uno::RuntimeException)
{
try
{
Reference< util::XModifyBroadcaster > xBroadcaster( m_xModifyEventForwarder, uno::UNO_QUERY_THROW );
xBroadcaster->removeModifyListener( aListener );
}
catch( const uno::Exception & ex )
{
ASSERT_EXCEPTION( ex );
}
}
void LabeledDataSequence::fireModifyEvent()
{
m_xModifyEventForwarder->modified( lang::EventObject( static_cast< uno::XWeak* >( this )));
}
// ================================================================================
Sequence< OUString > LabeledDataSequence::getSupportedServiceNames_Static()
{
Sequence< OUString > aServices( 1 );
aServices[ 0 ] = C2U( "com.sun.star.chart2.data.LabeledDataSequence" );
return aServices;
}
// implement XServiceInfo methods basing upon getSupportedServiceNames_Static
APPHELPER_XSERVICEINFO_IMPL( LabeledDataSequence,
C2U( "com.sun.star.comp.chart2.LabeledDataSequence" ))
// ================================================================================
} // namespace chart
<|endoftext|>
|
<commit_before>// -*- C++ -*-
// The MIT License (MIT)
//
// Copyright (c) 2021 Alexander Samoilov
//
// 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 <gtest/gtest.h>
#include "math.hpp"
template<unsigned N>
void sysslv(double a[N][N], double b[N])
{
constexpr unsigned n = N;
double biga,save;
int i,j,k,imax;
for (j=0;j<n;j++) {
biga=0.0;
for(i=j;i<n;i++)
if (std::fabs(biga) < std::fabs(a[i][j])) {
biga=a[i][j];
imax=i;
}
if (std::fabs(biga) == 0.0) {
throw std::logic_error("Very singular matrix...");
}
for (k=j;k<n;k++) {
save=a[imax][k];
a[imax][k]=a[j][k];
a[j][k]=save/biga;
}
save=b[imax];
b[imax]=b[j];
b[j]=save/biga;
for (i=j+1;i<n;i++) {
for(k=j+1;k<n;k++)
a[i][k] -= a[i][j]*a[j][k];
b[i] -= b[j]*a[i][j];
}
}
for (k=n-2;k>=0;k--)
for(j=n-1;j>k;j--)
b[k] -= a[k][j]*b[j];
}
TEST(cftSuite, test_cosfft1)
{
RowVectorXd x(3), x_inv(3);
x << 1., 2., 3.;
x_inv << 6., -2., 2.;
cosfft1(x, 2);
EXPECT_DOUBLE_EQ((x - x_inv).norm(), 0.0);
}
TEST(cftSuite, test_cf2)
{
RowMatrixXd m(3, 3), m_inv(3, 3);
m << 1., 2., 3.,
4., 5., 6.,
7., 8., 9.;
m_inv << 6., 4., 10.,
18., 10., 22.,
30., 16., 34.;
cft2(m, 2);
EXPECT_DOUBLE_EQ((m - m_inv).norm(), 0.0);
}
TEST(bsSuite, test_gauss_elim)
{
// https://mxncalc.com/gaussian-elimination-calculator
double A[4][4] = {{1., 2., 3., 4.},
{5., 6., 8., 5.},
{4., 15., 2., 12.},
{3., 2., 5., 6.},};
double b[4] = {11., 12., 3., 7.,};
double x[4] = { -7.127'853'881'278'5,
1.237'442'922'374'4,
4.858'447'488'584'5,
0.269'406'392'694'06,
};
Eigen::Vector4d bb(b), xx(x);
Eigen::Matrix4d AA(reinterpret_cast<double*>(A));
AA.transposeInPlace();
// std::cout << "AA: " << AA << std::endl;
sysslv(A, b);
Eigen::Vector4d b2(b);
//EXPECT_DOUBLE_EQ((b2 - xx).norm(), 0.0);
// Expected equality of these values:
// (b2 - xx).norm()
// Which is: 5.3413613165043815e-14
// 0.0
// Which is: 0
EXPECT_NEAR((b2 - xx).norm(), 0.0, 1e-12);
Eigen::Vector4d x2 = AA.lu().solve(bb);
// std::cout << "x2: " << x2 << std::endl;
// std::cout << "xx: " << xx << std::endl;
EXPECT_NEAR((x2 - xx).norm(), 0.0, 1e-12);
}
<commit_msg>EPS symbolic constant.<commit_after>// -*- C++ -*-
// The MIT License (MIT)
//
// Copyright (c) 2021 Alexander Samoilov
//
// 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 <gtest/gtest.h>
#include "math.hpp"
template<unsigned N>
void sysslv(double a[N][N], double b[N])
{
constexpr unsigned n = N;
double biga,save;
int i,j,k,imax;
for (j=0;j<n;j++) {
biga=0.0;
for(i=j;i<n;i++)
if (std::fabs(biga) < std::fabs(a[i][j])) {
biga=a[i][j];
imax=i;
}
if (std::fabs(biga) == 0.0) {
throw std::logic_error("Very singular matrix...");
}
for (k=j;k<n;k++) {
save=a[imax][k];
a[imax][k]=a[j][k];
a[j][k]=save/biga;
}
save=b[imax];
b[imax]=b[j];
b[j]=save/biga;
for (i=j+1;i<n;i++) {
for(k=j+1;k<n;k++)
a[i][k] -= a[i][j]*a[j][k];
b[i] -= b[j]*a[i][j];
}
}
for (k=n-2;k>=0;k--)
for(j=n-1;j>k;j--)
b[k] -= a[k][j]*b[j];
}
TEST(cftSuite, test_cosfft1)
{
RowVectorXd x(3), x_inv(3);
x << 1., 2., 3.;
x_inv << 6., -2., 2.;
cosfft1(x, 2);
EXPECT_DOUBLE_EQ((x - x_inv).norm(), 0.0);
}
TEST(cftSuite, test_cf2)
{
RowMatrixXd m(3, 3), m_inv(3, 3);
m << 1., 2., 3.,
4., 5., 6.,
7., 8., 9.;
m_inv << 6., 4., 10.,
18., 10., 22.,
30., 16., 34.;
cft2(m, 2);
EXPECT_DOUBLE_EQ((m - m_inv).norm(), 0.0);
}
TEST(bsSuite, test_gauss_elim)
{
constexpr double EPS = 1e-12;
// https://mxncalc.com/gaussian-elimination-calculator
double A[4][4] = {{1., 2., 3., 4.},
{5., 6., 8., 5.},
{4., 15., 2., 12.},
{3., 2., 5., 6.},};
double b[4] = {11., 12., 3., 7.,};
double x[4] = { -7.127'853'881'278'5,
1.237'442'922'374'4,
4.858'447'488'584'5,
0.269'406'392'694'06,
};
Eigen::Vector4d bb(b), xx(x);
Eigen::Matrix4d AA(reinterpret_cast<double*>(A));
AA.transposeInPlace();
// std::cout << "AA: " << AA << std::endl;
sysslv(A, b);
Eigen::Vector4d b2(b);
//EXPECT_DOUBLE_EQ((b2 - xx).norm(), 0.0);
// Expected equality of these values:
// (b2 - xx).norm()
// Which is: 5.3413613165043815e-14
// 0.0
// Which is: 0
EXPECT_NEAR((b2 - xx).norm(), 0.0, EPS);
Eigen::Vector4d x2 = AA.lu().solve(bb);
// std::cout << "x2: " << x2 << std::endl;
// std::cout << "xx: " << xx << std::endl;
EXPECT_NEAR((x2 - xx).norm(), 0.0, EPS);
}
<|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/autofill/autofill_manager.h"
#include <string>
#include "base/command_line.h"
#include "chrome/browser/autofill/autofill_dialog.h"
#include "chrome/browser/autofill/autofill_infobar_delegate.h"
#include "chrome/browser/autofill/form_structure.h"
#include "chrome/browser/pref_service.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/pref_names.h"
#include "webkit/glue/form_data.h"
#include "webkit/glue/form_field.h"
#include "webkit/glue/form_field_values.h"
AutoFillManager::AutoFillManager(TabContents* tab_contents)
: tab_contents_(tab_contents),
infobar_(NULL) {
personal_data_ = tab_contents_->profile()->GetPersonalDataManager();
}
AutoFillManager::~AutoFillManager() {
if (personal_data_)
personal_data_->RemoveObserver(this);
}
// static
void AutoFillManager::RegisterBrowserPrefs(PrefService* prefs) {
prefs->RegisterDictionaryPref(prefs::kAutoFillDialogPlacement);
}
// static
void AutoFillManager::RegisterUserPrefs(PrefService* prefs) {
prefs->RegisterBooleanPref(prefs::kAutoFillInfoBarShown, false);
prefs->RegisterBooleanPref(prefs::kAutoFillEnabled, false);
}
void AutoFillManager::FormFieldValuesSubmitted(
const webkit_glue::FormFieldValues& form) {
// Grab a copy of the form data.
upload_form_structure_.reset(new FormStructure(form));
if (!upload_form_structure_->IsAutoFillable())
return;
// Determine the possible field types.
DeterminePossibleFieldTypes(upload_form_structure_.get());
PrefService* prefs = tab_contents_->profile()->GetPrefs();
bool autofill_enabled = prefs->GetBoolean(prefs::kAutoFillEnabled);
bool infobar_shown = prefs->GetBoolean(prefs::kAutoFillInfoBarShown);
if (!infobar_shown && personal_data_) {
// Ask the user for permission to save form information.
infobar_.reset(new AutoFillInfoBarDelegate(tab_contents_, this));
} else if (autofill_enabled) {
HandleSubmit();
}
}
void AutoFillManager::FormsSeen(
const std::vector<webkit_glue::FormFieldValues>& forms) {
form_structures_.reset();
for (std::vector<webkit_glue::FormFieldValues>::const_iterator iter =
forms.begin();
iter != forms.end(); ++iter) {
FormStructure* form_structure = new FormStructure(*iter);
DeterminePossibleFieldTypes(form_structure);
form_structures_.push_back(form_structure);
}
}
bool AutoFillManager::GetAutoFillSuggestions(
int query_id, const webkit_glue::FormField& field) {
if (!IsAutoFillEnabled())
return false;
RenderViewHost* host = tab_contents_->render_view_host();
if (!host)
return false;
const std::vector<AutoFillProfile*>& profiles = personal_data_->profiles();
if (profiles.empty())
return false;
AutoFillFieldType type = UNKNOWN_TYPE;
for (std::vector<FormStructure*>::iterator form = form_structures_.begin();
form != form_structures_.end(); ++form) {
for (std::vector<AutoFillField*>::const_iterator iter = (*form)->begin();
iter != (*form)->end(); ++iter) {
// The field list is terminated with a NULL AutoFillField, so don't try to
// dereference it.
if (!*iter)
break;
AutoFillField* form_field = *iter;
if (*form_field != field)
continue;
if (form_field->possible_types().find(NAME_FIRST) !=
form_field->possible_types().end() ||
form_field->heuristic_type() == NAME_FIRST) {
type = NAME_FIRST;
break;
}
if (form_field->possible_types().find(NAME_FULL) !=
form_field->possible_types().end() ||
form_field->heuristic_type() == NAME_FULL) {
type = NAME_FULL;
break;
}
}
}
if (type == UNKNOWN_TYPE)
return false;
std::vector<string16> names;
std::vector<string16> labels;
for (std::vector<AutoFillProfile*>::const_iterator iter = profiles.begin();
iter != profiles.end(); ++iter) {
string16 name = (*iter)->GetFieldText(AutoFillType(type));
string16 label = (*iter)->Label();
// TODO(jhawkins): What if name.length() == 0?
if (StartsWith(name, field.value(), false)) {
names.push_back(name);
labels.push_back(label);
}
}
// No suggestions.
if (names.empty())
return false;
// TODO(jhawkins): If the default profile is in this list, set it as the
// default suggestion index.
host->AutoFillSuggestionsReturned(query_id, names, labels, -1);
return true;
}
bool AutoFillManager::FillAutoFillFormData(int query_id,
const FormData& form,
const string16& name,
const string16& label) {
if (!IsAutoFillEnabled())
return false;
RenderViewHost* host = tab_contents_->render_view_host();
if (!host)
return false;
const std::vector<AutoFillProfile*>& profiles = personal_data_->profiles();
if (profiles.empty())
return false;
const AutoFillProfile* profile = NULL;
for (std::vector<AutoFillProfile*>::const_iterator iter = profiles.begin();
iter != profiles.end(); ++iter) {
if ((*iter)->Label() != label)
continue;
if ((*iter)->GetFieldText(AutoFillType(NAME_FIRST)) != name &&
(*iter)->GetFieldText(AutoFillType(NAME_FULL)) != name)
continue;
profile = *iter;
break;
}
if (!profile)
return false;
FormData result = form;
for (std::vector<FormStructure*>::const_iterator iter =
form_structures_.begin();
iter != form_structures_.end(); ++iter) {
const FormStructure* form_structure = *iter;
if (*form_structure != form)
continue;
for (size_t i = 0; i < form_structure->field_count(); ++i) {
const AutoFillField* field = form_structure->field(i);
for (size_t j = 0; j < result.values.size(); ++j) {
if (field->name() == result.elements[j]) {
result.values[j] =
profile->GetFieldText(AutoFillType(field->heuristic_type()));
break;
}
}
}
}
host->AutoFillFormDataFilled(query_id, result);
return true;
}
void AutoFillManager::OnAutoFillDialogApply(
std::vector<AutoFillProfile>* profiles,
std::vector<CreditCard>* credit_cards) {
// Save the personal data.
personal_data_->SetProfiles(profiles);
personal_data_->SetCreditCards(credit_cards);
HandleSubmit();
}
void AutoFillManager::OnPersonalDataLoaded() {
// We might have been alerted that the PersonalDataManager has loaded, so
// remove ourselves as observer.
personal_data_->RemoveObserver(this);
ShowAutoFillDialog(
this, personal_data_->profiles(), personal_data_->credit_cards());
}
void AutoFillManager::DeterminePossibleFieldTypes(
FormStructure* form_structure) {
// TODO(jhawkins): Update field text.
form_structure->GetHeuristicAutoFillTypes();
// OTR: We can't use the PersonalDataManager to help determine field types.
if (!personal_data_)
return;
for (size_t i = 0; i < form_structure->field_count(); i++) {
const AutoFillField* field = form_structure->field(i);
FieldTypeSet field_types;
personal_data_->GetPossibleFieldTypes(field->value(), &field_types);
form_structure->set_possible_types(i, field_types);
}
}
void AutoFillManager::HandleSubmit() {
// If there wasn't enough data to import then we don't want to send an upload
// to the server.
if (personal_data_ &&
!personal_data_->ImportFormData(form_structures_.get(), this))
return;
UploadFormData();
}
void AutoFillManager::OnInfoBarAccepted() {
PrefService* prefs = tab_contents_->profile()->GetPrefs();
prefs->SetBoolean(prefs::kAutoFillEnabled, true);
// If the personal data manager has not loaded the data yet, set ourselves as
// its observer so that we can listen for the OnPersonalDataLoaded signal.
if (!personal_data_->IsDataLoaded())
personal_data_->SetObserver(this);
else
OnPersonalDataLoaded();
}
void AutoFillManager::UploadFormData() {
std::string xml;
bool ok = upload_form_structure_->EncodeUploadRequest(false, &xml);
DCHECK(ok);
// TODO(jhawkins): Initiate the upload request thread.
}
void AutoFillManager::Reset() {
upload_form_structure_.reset();
}
bool AutoFillManager::IsAutoFillEnabled() {
PrefService* prefs = tab_contents_->profile()->GetPrefs();
// Migrate obsolete autofill pref.
if (prefs->HasPrefPath(prefs::kFormAutofillEnabled)) {
bool enabled = prefs->GetBoolean(prefs::kFormAutofillEnabled);
prefs->ClearPref(prefs::kFormAutofillEnabled);
prefs->SetBoolean(prefs::kAutoFillEnabled, enabled);
return enabled;
}
return prefs->GetBoolean(prefs::kAutoFillEnabled);
}
<commit_msg>Check for a non-NULL PersonalDataManager when determining if AutoFill is enabled. The PersonalDataManager is NULL when OTR.<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/autofill/autofill_manager.h"
#include <string>
#include "base/command_line.h"
#include "chrome/browser/autofill/autofill_dialog.h"
#include "chrome/browser/autofill/autofill_infobar_delegate.h"
#include "chrome/browser/autofill/form_structure.h"
#include "chrome/browser/pref_service.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/pref_names.h"
#include "webkit/glue/form_data.h"
#include "webkit/glue/form_field.h"
#include "webkit/glue/form_field_values.h"
AutoFillManager::AutoFillManager(TabContents* tab_contents)
: tab_contents_(tab_contents),
infobar_(NULL) {
personal_data_ = tab_contents_->profile()->GetPersonalDataManager();
}
AutoFillManager::~AutoFillManager() {
if (personal_data_)
personal_data_->RemoveObserver(this);
}
// static
void AutoFillManager::RegisterBrowserPrefs(PrefService* prefs) {
prefs->RegisterDictionaryPref(prefs::kAutoFillDialogPlacement);
}
// static
void AutoFillManager::RegisterUserPrefs(PrefService* prefs) {
prefs->RegisterBooleanPref(prefs::kAutoFillInfoBarShown, false);
prefs->RegisterBooleanPref(prefs::kAutoFillEnabled, false);
}
void AutoFillManager::FormFieldValuesSubmitted(
const webkit_glue::FormFieldValues& form) {
if (!IsAutoFillEnabled())
return;
// Grab a copy of the form data.
upload_form_structure_.reset(new FormStructure(form));
if (!upload_form_structure_->IsAutoFillable())
return;
// Determine the possible field types.
DeterminePossibleFieldTypes(upload_form_structure_.get());
PrefService* prefs = tab_contents_->profile()->GetPrefs();
bool infobar_shown = prefs->GetBoolean(prefs::kAutoFillInfoBarShown);
if (!infobar_shown) {
// Ask the user for permission to save form information.
infobar_.reset(new AutoFillInfoBarDelegate(tab_contents_, this));
} else {
HandleSubmit();
}
}
void AutoFillManager::FormsSeen(
const std::vector<webkit_glue::FormFieldValues>& forms) {
if (!IsAutoFillEnabled())
return;
form_structures_.reset();
for (std::vector<webkit_glue::FormFieldValues>::const_iterator iter =
forms.begin();
iter != forms.end(); ++iter) {
FormStructure* form_structure = new FormStructure(*iter);
DeterminePossibleFieldTypes(form_structure);
form_structures_.push_back(form_structure);
}
}
bool AutoFillManager::GetAutoFillSuggestions(
int query_id, const webkit_glue::FormField& field) {
if (!IsAutoFillEnabled())
return false;
RenderViewHost* host = tab_contents_->render_view_host();
if (!host)
return false;
const std::vector<AutoFillProfile*>& profiles = personal_data_->profiles();
if (profiles.empty())
return false;
AutoFillFieldType type = UNKNOWN_TYPE;
for (std::vector<FormStructure*>::iterator form = form_structures_.begin();
form != form_structures_.end(); ++form) {
for (std::vector<AutoFillField*>::const_iterator iter = (*form)->begin();
iter != (*form)->end(); ++iter) {
// The field list is terminated with a NULL AutoFillField, so don't try to
// dereference it.
if (!*iter)
break;
AutoFillField* form_field = *iter;
if (*form_field != field)
continue;
if (form_field->possible_types().find(NAME_FIRST) !=
form_field->possible_types().end() ||
form_field->heuristic_type() == NAME_FIRST) {
type = NAME_FIRST;
break;
}
if (form_field->possible_types().find(NAME_FULL) !=
form_field->possible_types().end() ||
form_field->heuristic_type() == NAME_FULL) {
type = NAME_FULL;
break;
}
}
}
if (type == UNKNOWN_TYPE)
return false;
std::vector<string16> names;
std::vector<string16> labels;
for (std::vector<AutoFillProfile*>::const_iterator iter = profiles.begin();
iter != profiles.end(); ++iter) {
string16 name = (*iter)->GetFieldText(AutoFillType(type));
string16 label = (*iter)->Label();
// TODO(jhawkins): What if name.length() == 0?
if (StartsWith(name, field.value(), false)) {
names.push_back(name);
labels.push_back(label);
}
}
// No suggestions.
if (names.empty())
return false;
// TODO(jhawkins): If the default profile is in this list, set it as the
// default suggestion index.
host->AutoFillSuggestionsReturned(query_id, names, labels, -1);
return true;
}
bool AutoFillManager::FillAutoFillFormData(int query_id,
const FormData& form,
const string16& name,
const string16& label) {
if (!IsAutoFillEnabled())
return false;
RenderViewHost* host = tab_contents_->render_view_host();
if (!host)
return false;
const std::vector<AutoFillProfile*>& profiles = personal_data_->profiles();
if (profiles.empty())
return false;
const AutoFillProfile* profile = NULL;
for (std::vector<AutoFillProfile*>::const_iterator iter = profiles.begin();
iter != profiles.end(); ++iter) {
if ((*iter)->Label() != label)
continue;
if ((*iter)->GetFieldText(AutoFillType(NAME_FIRST)) != name &&
(*iter)->GetFieldText(AutoFillType(NAME_FULL)) != name)
continue;
profile = *iter;
break;
}
if (!profile)
return false;
FormData result = form;
for (std::vector<FormStructure*>::const_iterator iter =
form_structures_.begin();
iter != form_structures_.end(); ++iter) {
const FormStructure* form_structure = *iter;
if (*form_structure != form)
continue;
for (size_t i = 0; i < form_structure->field_count(); ++i) {
const AutoFillField* field = form_structure->field(i);
for (size_t j = 0; j < result.values.size(); ++j) {
if (field->name() == result.elements[j]) {
result.values[j] =
profile->GetFieldText(AutoFillType(field->heuristic_type()));
break;
}
}
}
}
host->AutoFillFormDataFilled(query_id, result);
return true;
}
void AutoFillManager::OnAutoFillDialogApply(
std::vector<AutoFillProfile>* profiles,
std::vector<CreditCard>* credit_cards) {
DCHECK(personal_data_);
// Save the personal data.
personal_data_->SetProfiles(profiles);
personal_data_->SetCreditCards(credit_cards);
HandleSubmit();
}
void AutoFillManager::OnPersonalDataLoaded() {
DCHECK(personal_data_);
// We might have been alerted that the PersonalDataManager has loaded, so
// remove ourselves as observer.
personal_data_->RemoveObserver(this);
ShowAutoFillDialog(
this, personal_data_->profiles(), personal_data_->credit_cards());
}
void AutoFillManager::DeterminePossibleFieldTypes(
FormStructure* form_structure) {
// TODO(jhawkins): Update field text.
form_structure->GetHeuristicAutoFillTypes();
for (size_t i = 0; i < form_structure->field_count(); i++) {
const AutoFillField* field = form_structure->field(i);
FieldTypeSet field_types;
personal_data_->GetPossibleFieldTypes(field->value(), &field_types);
form_structure->set_possible_types(i, field_types);
}
}
void AutoFillManager::HandleSubmit() {
// If there wasn't enough data to import then we don't want to send an upload
// to the server.
if (!personal_data_->ImportFormData(form_structures_.get(), this))
return;
UploadFormData();
}
void AutoFillManager::OnInfoBarAccepted() {
DCHECK(personal_data_);
PrefService* prefs = tab_contents_->profile()->GetPrefs();
prefs->SetBoolean(prefs::kAutoFillEnabled, true);
// If the personal data manager has not loaded the data yet, set ourselves as
// its observer so that we can listen for the OnPersonalDataLoaded signal.
if (!personal_data_->IsDataLoaded())
personal_data_->SetObserver(this);
else
OnPersonalDataLoaded();
}
void AutoFillManager::UploadFormData() {
std::string xml;
bool ok = upload_form_structure_->EncodeUploadRequest(false, &xml);
DCHECK(ok);
// TODO(jhawkins): Initiate the upload request thread.
}
void AutoFillManager::Reset() {
upload_form_structure_.reset();
}
bool AutoFillManager::IsAutoFillEnabled() {
// The PersonalDataManager is NULL in OTR.
if (!personal_data_)
return false;
PrefService* prefs = tab_contents_->profile()->GetPrefs();
// Migrate obsolete autofill pref.
if (prefs->HasPrefPath(prefs::kFormAutofillEnabled)) {
bool enabled = prefs->GetBoolean(prefs::kFormAutofillEnabled);
prefs->ClearPref(prefs::kFormAutofillEnabled);
prefs->SetBoolean(prefs::kAutoFillEnabled, enabled);
return enabled;
}
return prefs->GetBoolean(prefs::kAutoFillEnabled);
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/process_info_snapshot.h"
#include <iostream>
#include <sstream>
#include "base/string_util.h"
#include "base/thread.h"
// Implementation for the Mac; calls '/bin/ps' for information when
// |Sample()| is called.
// Default constructor.
ProcessInfoSnapshot::ProcessInfoSnapshot() { }
// Destructor: just call |Reset()| to release everything.
ProcessInfoSnapshot::~ProcessInfoSnapshot() {
Reset();
}
// Capture the information by calling '/bin/ps'.
// Note: we ignore the "tsiz" (text size) display option of ps because it's
// always zero (tested on 10.5 and 10.6).
bool ProcessInfoSnapshot::Sample(std::vector<base::ProcessId> pid_list) {
Reset();
std::vector<std::string> argv;
argv.push_back("/bin/ps");
// Get PID, PPID, (real) UID, effective UID, resident set size, virtual memory
// size, and command.
argv.push_back("-o");
argv.push_back("pid=,ppid=,ruid=,uid=,rss=,vsz=,comm=");
// Only display the specified PIDs.
for (std::vector<base::ProcessId>::iterator it = pid_list.begin();
it != pid_list.end(); ++it) {
argv.push_back("-p");
argv.push_back(Int64ToString(static_cast<int64>(*it)));
}
std::string output;
CommandLine command_line(argv);
if (!base::GetAppOutputRestricted(command_line,
&output, (pid_list.size() + 10) * 100)) {
LOG(ERROR) << "Failure running /bin/ps to acquire data.";
return false;
}
std::istringstream in(output, std::istringstream::in);
std::string line;
// Process lines until done.
while (true) {
ProcInfoEntry proc_info;
// The format is as specified above to ps (see ps(1)):
// "-o pid=,ppid=,ruid=,uid=,rss=,vsz=,comm=".
// Try to read the PID; if we get it, we should be able to get the rest of
// the line.
in >> proc_info.pid;
if (in.eof())
break;
in >> proc_info.ppid;
in >> proc_info.uid;
in >> proc_info.euid;
in >> proc_info.rss;
in >> proc_info.vsize;
in.ignore(1, ' '); // Eat the space.
std::getline(in, proc_info.command); // Get the rest of the line.
if (!in.good()) {
LOG(ERROR) << "Error parsing output from /usr/bin/top.";
return false;
}
// Make sure the new PID isn't already in our list.
if (proc_info_entries_.find(proc_info.pid) != proc_info_entries_.end()) {
LOG(ERROR) << "Duplicate PID in output from /bin/ps.";
return false;
}
if (!proc_info.pid || ! proc_info.vsize) {
LOG(WARNING) << "Invalid data from /bin/ps.";
return false;
}
// Record the process information.
proc_info_entries_[proc_info.pid] = proc_info;
}
return true;
}
// Clear all the stored information.
void ProcessInfoSnapshot::Reset() {
proc_info_entries_.clear();
}
bool ProcessInfoSnapshot::GetProcInfo(int pid,
ProcInfoEntry* proc_info) const {
std::map<int,ProcInfoEntry>::const_iterator it = proc_info_entries_.find(pid);
if (it == proc_info_entries_.end())
return false;
*proc_info = it->second;
return true;
}
bool ProcessInfoSnapshot::GetCommittedKBytesOfPID(
int pid,
base::CommittedKBytes* usage) const {
// Try to avoid crashing on a bug; stats aren't usually so crucial.
if (!usage) {
NOTREACHED();
return false;
}
// Failure of |GetProcInfo()| is "normal", due to racing.
ProcInfoEntry proc_info;
if (!GetProcInfo(pid, &proc_info)) {
usage->priv = 0;
usage->mapped = 0;
usage->image = 0;
return false;
}
usage->priv = proc_info.vsize;
usage->mapped = 0;
usage->image = 0;
return true;
}
bool ProcessInfoSnapshot::GetWorkingSetKBytesOfPID(
int pid,
base::WorkingSetKBytes* ws_usage) const {
// Try to avoid crashing on a bug; stats aren't usually so crucial.
if (!ws_usage) {
NOTREACHED();
return false;
}
// Failure of |GetProcInfo()| is "normal", due to racing.
ProcInfoEntry proc_info;
if (!GetProcInfo(pid, &proc_info)) {
ws_usage->priv = 0;
ws_usage->shareable = 0;
ws_usage->shared = 0;
return false;
}
ws_usage->priv = 0;
ws_usage->shareable = proc_info.rss;
ws_usage->shared = 0;
return true;
}
<commit_msg>Mac: fix error message which mentions top instead of ps.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/process_info_snapshot.h"
#include <iostream>
#include <sstream>
#include "base/string_util.h"
#include "base/thread.h"
// Implementation for the Mac; calls '/bin/ps' for information when
// |Sample()| is called.
// Default constructor.
ProcessInfoSnapshot::ProcessInfoSnapshot() { }
// Destructor: just call |Reset()| to release everything.
ProcessInfoSnapshot::~ProcessInfoSnapshot() {
Reset();
}
// Capture the information by calling '/bin/ps'.
// Note: we ignore the "tsiz" (text size) display option of ps because it's
// always zero (tested on 10.5 and 10.6).
bool ProcessInfoSnapshot::Sample(std::vector<base::ProcessId> pid_list) {
const char* kPsPathName = "/bin/ps";
Reset();
std::vector<std::string> argv;
argv.push_back(kPsPathName);
// Get PID, PPID, (real) UID, effective UID, resident set size, virtual memory
// size, and command.
argv.push_back("-o");
argv.push_back("pid=,ppid=,ruid=,uid=,rss=,vsz=,comm=");
// Only display the specified PIDs.
for (std::vector<base::ProcessId>::iterator it = pid_list.begin();
it != pid_list.end(); ++it) {
argv.push_back("-p");
argv.push_back(Int64ToString(static_cast<int64>(*it)));
}
std::string output;
CommandLine command_line(argv);
if (!base::GetAppOutputRestricted(command_line,
&output, (pid_list.size() + 10) * 100)) {
LOG(ERROR) << "Failure running " << kPsPathName << " to acquire data.";
return false;
}
std::istringstream in(output, std::istringstream::in);
std::string line;
// Process lines until done.
while (true) {
ProcInfoEntry proc_info;
// The format is as specified above to ps (see ps(1)):
// "-o pid=,ppid=,ruid=,uid=,rss=,vsz=,comm=".
// Try to read the PID; if we get it, we should be able to get the rest of
// the line.
in >> proc_info.pid;
if (in.eof())
break;
in >> proc_info.ppid;
in >> proc_info.uid;
in >> proc_info.euid;
in >> proc_info.rss;
in >> proc_info.vsize;
in.ignore(1, ' '); // Eat the space.
std::getline(in, proc_info.command); // Get the rest of the line.
if (!in.good()) {
LOG(ERROR) << "Error parsing output from " << kPsPathName << ".";
return false;
}
// Make sure the new PID isn't already in our list.
if (proc_info_entries_.find(proc_info.pid) != proc_info_entries_.end()) {
LOG(ERROR) << "Duplicate PID in output from " << kPsPathName << ".";
return false;
}
if (!proc_info.pid || ! proc_info.vsize) {
LOG(WARNING) << "Invalid data from " << kPsPathName << ".";
return false;
}
// Record the process information.
proc_info_entries_[proc_info.pid] = proc_info;
}
return true;
}
// Clear all the stored information.
void ProcessInfoSnapshot::Reset() {
proc_info_entries_.clear();
}
bool ProcessInfoSnapshot::GetProcInfo(int pid,
ProcInfoEntry* proc_info) const {
std::map<int,ProcInfoEntry>::const_iterator it = proc_info_entries_.find(pid);
if (it == proc_info_entries_.end())
return false;
*proc_info = it->second;
return true;
}
bool ProcessInfoSnapshot::GetCommittedKBytesOfPID(
int pid,
base::CommittedKBytes* usage) const {
// Try to avoid crashing on a bug; stats aren't usually so crucial.
if (!usage) {
NOTREACHED();
return false;
}
// Failure of |GetProcInfo()| is "normal", due to racing.
ProcInfoEntry proc_info;
if (!GetProcInfo(pid, &proc_info)) {
usage->priv = 0;
usage->mapped = 0;
usage->image = 0;
return false;
}
usage->priv = proc_info.vsize;
usage->mapped = 0;
usage->image = 0;
return true;
}
bool ProcessInfoSnapshot::GetWorkingSetKBytesOfPID(
int pid,
base::WorkingSetKBytes* ws_usage) const {
// Try to avoid crashing on a bug; stats aren't usually so crucial.
if (!ws_usage) {
NOTREACHED();
return false;
}
// Failure of |GetProcInfo()| is "normal", due to racing.
ProcInfoEntry proc_info;
if (!GetProcInfo(pid, &proc_info)) {
ws_usage->priv = 0;
ws_usage->shareable = 0;
ws_usage->shared = 0;
return false;
}
ws_usage->priv = 0;
ws_usage->shareable = proc_info.rss;
ws_usage->shared = 0;
return true;
}
<|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/views/keyword_editor_view.h"
#include <vector>
#include "app/l10n_util.h"
#include "base/stl_util-inl.h"
#include "base/string_util.h"
#include "chrome/browser/pref_service.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/search_engines/template_url.h"
#include "chrome/browser/search_engines/template_url_model.h"
#include "chrome/browser/search_engines/template_url_table_model.h"
#include "chrome/browser/views/browser_dialogs.h"
#include "chrome/browser/views/first_run_search_engine_view.h"
#include "chrome/common/pref_names.h"
#include "gfx/point.h"
#include "googleurl/src/gurl.h"
#include "grit/generated_resources.h"
#include "grit/locale_settings.h"
#include "grit/theme_resources.h"
#include "views/background.h"
#include "views/grid_layout.h"
#include "views/controls/button/native_button.h"
#include "views/controls/table/table_view.h"
#include "views/controls/textfield/textfield.h"
#include "views/standard_layout.h"
#include "views/widget/widget.h"
#include "views/window/dialog_delegate.h"
#include "views/window/window.h"
using views::GridLayout;
using views::NativeButton;
namespace browser {
// Declared in browser_dialogs.h so others don't have to depend on our header.
void ShowKeywordEditorView(Profile* profile) {
KeywordEditorView::Show(profile);
}
} // namespace browser
// KeywordEditorView ----------------------------------------------------------
// If non-null, there is an open editor and this is the window it is contained
// in.
static views::Window* open_window = NULL;
// static
// The typical case for showing a KeywordEditorView does not involve an
// observer, so use this function signature generally.
void KeywordEditorView::Show(Profile* profile) {
KeywordEditorView::ShowAndObserve(profile, NULL);
}
// static
void KeywordEditorView::ShowAndObserve(Profile* profile,
SearchEngineSelectionObserver* observer) {
// If this panel is opened from an Incognito window, closing that window can
// leave this with a stale pointer. Use the original profile instead.
// See http://crbug.com/23359.
profile = profile ->GetOriginalProfile();
if (!profile->GetTemplateURLModel())
return;
if (open_window != NULL)
open_window->Close();
DCHECK(!open_window);
// Both of these will be deleted when the dialog closes.
KeywordEditorView* keyword_editor = new KeywordEditorView(profile, observer);
// Initialize the UI. By passing in an empty rect KeywordEditorView is
// queried for its preferred size.
open_window = views::Window::CreateChromeWindow(NULL, gfx::Rect(),
keyword_editor);
open_window->Show();
}
KeywordEditorView::KeywordEditorView(Profile* profile,
SearchEngineSelectionObserver* observer)
: profile_(profile),
observer_(observer),
controller_(new KeywordEditorController(profile)),
default_chosen_(false) {
DCHECK(controller_->url_model());
controller_->url_model()->AddObserver(this);
Init();
}
KeywordEditorView::~KeywordEditorView() {
table_view_->SetModel(NULL);
controller_->url_model()->RemoveObserver(this);
}
void KeywordEditorView::OnEditedKeyword(const TemplateURL* template_url,
const std::wstring& title,
const std::wstring& keyword,
const std::wstring& url) {
if (template_url) {
controller_->ModifyTemplateURL(template_url, title, keyword, url);
// Force the make default button to update.
OnSelectionChanged();
} else {
table_view_->Select(controller_->AddTemplateURL(title, keyword, url));
}
}
gfx::Size KeywordEditorView::GetPreferredSize() {
return gfx::Size(views::Window::GetLocalizedContentsSize(
IDS_SEARCHENGINES_DIALOG_WIDTH_CHARS,
IDS_SEARCHENGINES_DIALOG_HEIGHT_LINES));
}
bool KeywordEditorView::CanResize() const {
return true;
}
std::wstring KeywordEditorView::GetWindowTitle() const {
return l10n_util::GetString(IDS_SEARCH_ENGINES_EDITOR_WINDOW_TITLE);
}
std::wstring KeywordEditorView::GetWindowName() const {
return prefs::kKeywordEditorWindowPlacement;
}
int KeywordEditorView::GetDialogButtons() const {
return MessageBoxFlags::DIALOGBUTTON_CANCEL;
}
bool KeywordEditorView::Accept() {
if (observer_)
observer_->SearchEngineChosen(
profile_->GetTemplateURLModel()->GetDefaultSearchProvider());
open_window = NULL;
return true;
}
bool KeywordEditorView::Cancel() {
if (observer_)
observer_->SearchEngineChosen(
profile_->GetTemplateURLModel()->GetDefaultSearchProvider());
open_window = NULL;
return true;
}
views::View* KeywordEditorView::GetContentsView() {
return this;
}
void KeywordEditorView::Init() {
std::vector<TableColumn> columns;
columns.push_back(
TableColumn(IDS_SEARCH_ENGINES_EDITOR_DESCRIPTION_COLUMN,
TableColumn::LEFT, -1, .75));
columns.back().sortable = true;
columns.push_back(
TableColumn(IDS_SEARCH_ENGINES_EDITOR_KEYWORD_COLUMN,
TableColumn::LEFT, -1, .25));
columns.back().sortable = true;
table_view_ = new views::TableView(controller_->table_model(), columns,
views::ICON_AND_TEXT, false, true, true);
table_view_->SetObserver(this);
add_button_ = new views::NativeButton(
this, l10n_util::GetString(IDS_SEARCH_ENGINES_EDITOR_NEW_BUTTON));
add_button_->SetEnabled(controller_->loaded());
add_button_->AddAccelerator(
views::Accelerator(base::VKEY_A, false, false, true));
add_button_->SetAccessibleKeyboardShortcut(L"A");
edit_button_ = new views::NativeButton(
this, l10n_util::GetString(IDS_SEARCH_ENGINES_EDITOR_EDIT_BUTTON));
edit_button_->SetEnabled(false);
remove_button_ = new views::NativeButton(
this, l10n_util::GetString(IDS_SEARCH_ENGINES_EDITOR_REMOVE_BUTTON));
remove_button_->SetEnabled(false);
remove_button_->AddAccelerator(
views::Accelerator(base::VKEY_R, false, false, true));
remove_button_->SetAccessibleKeyboardShortcut(L"R");
make_default_button_ = new views::NativeButton(
this,
l10n_util::GetString(IDS_SEARCH_ENGINES_EDITOR_MAKE_DEFAULT_BUTTON));
make_default_button_->SetEnabled(false);
InitLayoutManager();
}
void KeywordEditorView::InitLayoutManager() {
const int related_x = kRelatedControlHorizontalSpacing;
const int related_y = kRelatedControlVerticalSpacing;
const int unrelated_y = kUnrelatedControlVerticalSpacing;
GridLayout* contents_layout = CreatePanelGridLayout(this);
SetLayoutManager(contents_layout);
// For the table and buttons.
views::ColumnSet* column_set = contents_layout->AddColumnSet(0);
column_set->AddColumn(GridLayout::FILL, GridLayout::FILL, 1,
GridLayout::USE_PREF, 0, 0);
column_set->AddPaddingColumn(0, related_x);
column_set->AddColumn(GridLayout::FILL, GridLayout::CENTER, 0,
GridLayout::USE_PREF, 0, 0);
contents_layout->StartRow(0, 0);
contents_layout->AddView(table_view_, 1, 8, GridLayout::FILL,
GridLayout::FILL);
contents_layout->AddView(add_button_);
contents_layout->StartRowWithPadding(0, 0, 0, related_y);
contents_layout->SkipColumns(2);
contents_layout->AddView(edit_button_);
contents_layout->StartRowWithPadding(0, 0, 0, related_y);
contents_layout->SkipColumns(2);
contents_layout->AddView(remove_button_);
contents_layout->StartRowWithPadding(0, 0, 0, related_y);
contents_layout->SkipColumns(2);
contents_layout->AddView(make_default_button_);
contents_layout->AddPaddingRow(1, 0);
}
void KeywordEditorView::OnSelectionChanged() {
bool only_one_url_left =
controller_->url_model()->GetTemplateURLs().size() == 1;
if (table_view_->SelectedRowCount() == 1) {
edit_button_->SetEnabled(true);
const TemplateURL* selected_url =
controller_->GetTemplateURL(table_view_->FirstSelectedRow());
make_default_button_->SetEnabled(controller_->CanMakeDefault(selected_url));
remove_button_->SetEnabled(!only_one_url_left &&
controller_->CanRemove(selected_url));
} else {
make_default_button_->SetEnabled(false);
for (views::TableView::iterator i = table_view_->SelectionBegin();
i != table_view_->SelectionEnd(); ++i) {
const TemplateURL* selected_url = controller_->GetTemplateURL(*i);
if (!controller_->CanRemove(selected_url)) {
remove_button_->SetEnabled(false);
return;
}
}
remove_button_->SetEnabled(!only_one_url_left);
}
}
void KeywordEditorView::OnDoubleClick() {
if (edit_button_->IsEnabled()) {
DWORD pos = GetMessagePos();
gfx::Point cursor_point(pos);
views::MouseEvent event(views::Event::ET_MOUSE_RELEASED,
cursor_point.x(), cursor_point.y(),
views::Event::EF_LEFT_BUTTON_DOWN);
ButtonPressed(edit_button_, event);
}
}
void KeywordEditorView::ButtonPressed(
views::Button* sender, const views::Event& event) {
if (sender == add_button_) {
browser::EditSearchEngine(GetWindow()->GetNativeWindow(), NULL, this,
profile_);
} else if (sender == remove_button_) {
DCHECK_GT(table_view_->SelectedRowCount(), 0);
int last_view_row = -1;
for (views::TableView::iterator i = table_view_->SelectionBegin();
i != table_view_->SelectionEnd(); ++i) {
last_view_row = table_view_->model_to_view(*i);
controller_->RemoveTemplateURL(*i);
}
if (last_view_row >= controller_->table_model()->RowCount())
last_view_row = controller_->table_model()->RowCount() - 1;
if (last_view_row >= 0)
table_view_->Select(table_view_->view_to_model(last_view_row));
} else if (sender == edit_button_) {
const int selected_row = table_view_->FirstSelectedRow();
const TemplateURL* template_url =
controller_->GetTemplateURL(selected_row);
browser::EditSearchEngine(GetWindow()->GetNativeWindow(), template_url,
this, profile_);
} else if (sender == make_default_button_) {
MakeDefaultTemplateURL();
} else {
NOTREACHED();
}
}
void KeywordEditorView::OnTemplateURLModelChanged() {
add_button_->SetEnabled(controller_->loaded());
}
void KeywordEditorView::MakeDefaultTemplateURL() {
int new_index =
controller_->MakeDefaultTemplateURL(table_view_->FirstSelectedRow());
if (new_index >= 0)
table_view_->Select(new_index);
default_chosen_ = true;
}
<commit_msg>Fixes regression in keyword editor. If the selection became empty clicking the edit button would crash.<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/views/keyword_editor_view.h"
#include <vector>
#include "app/l10n_util.h"
#include "base/stl_util-inl.h"
#include "base/string_util.h"
#include "chrome/browser/pref_service.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/search_engines/template_url.h"
#include "chrome/browser/search_engines/template_url_model.h"
#include "chrome/browser/search_engines/template_url_table_model.h"
#include "chrome/browser/views/browser_dialogs.h"
#include "chrome/browser/views/first_run_search_engine_view.h"
#include "chrome/common/pref_names.h"
#include "gfx/point.h"
#include "googleurl/src/gurl.h"
#include "grit/generated_resources.h"
#include "grit/locale_settings.h"
#include "grit/theme_resources.h"
#include "views/background.h"
#include "views/grid_layout.h"
#include "views/controls/button/native_button.h"
#include "views/controls/table/table_view.h"
#include "views/controls/textfield/textfield.h"
#include "views/standard_layout.h"
#include "views/widget/widget.h"
#include "views/window/dialog_delegate.h"
#include "views/window/window.h"
using views::GridLayout;
using views::NativeButton;
namespace browser {
// Declared in browser_dialogs.h so others don't have to depend on our header.
void ShowKeywordEditorView(Profile* profile) {
KeywordEditorView::Show(profile);
}
} // namespace browser
// KeywordEditorView ----------------------------------------------------------
// If non-null, there is an open editor and this is the window it is contained
// in.
static views::Window* open_window = NULL;
// static
// The typical case for showing a KeywordEditorView does not involve an
// observer, so use this function signature generally.
void KeywordEditorView::Show(Profile* profile) {
KeywordEditorView::ShowAndObserve(profile, NULL);
}
// static
void KeywordEditorView::ShowAndObserve(Profile* profile,
SearchEngineSelectionObserver* observer) {
// If this panel is opened from an Incognito window, closing that window can
// leave this with a stale pointer. Use the original profile instead.
// See http://crbug.com/23359.
profile = profile ->GetOriginalProfile();
if (!profile->GetTemplateURLModel())
return;
if (open_window != NULL)
open_window->Close();
DCHECK(!open_window);
// Both of these will be deleted when the dialog closes.
KeywordEditorView* keyword_editor = new KeywordEditorView(profile, observer);
// Initialize the UI. By passing in an empty rect KeywordEditorView is
// queried for its preferred size.
open_window = views::Window::CreateChromeWindow(NULL, gfx::Rect(),
keyword_editor);
open_window->Show();
}
KeywordEditorView::KeywordEditorView(Profile* profile,
SearchEngineSelectionObserver* observer)
: profile_(profile),
observer_(observer),
controller_(new KeywordEditorController(profile)),
default_chosen_(false) {
DCHECK(controller_->url_model());
controller_->url_model()->AddObserver(this);
Init();
}
KeywordEditorView::~KeywordEditorView() {
table_view_->SetModel(NULL);
controller_->url_model()->RemoveObserver(this);
}
void KeywordEditorView::OnEditedKeyword(const TemplateURL* template_url,
const std::wstring& title,
const std::wstring& keyword,
const std::wstring& url) {
if (template_url) {
controller_->ModifyTemplateURL(template_url, title, keyword, url);
// Force the make default button to update.
OnSelectionChanged();
} else {
table_view_->Select(controller_->AddTemplateURL(title, keyword, url));
}
}
gfx::Size KeywordEditorView::GetPreferredSize() {
return gfx::Size(views::Window::GetLocalizedContentsSize(
IDS_SEARCHENGINES_DIALOG_WIDTH_CHARS,
IDS_SEARCHENGINES_DIALOG_HEIGHT_LINES));
}
bool KeywordEditorView::CanResize() const {
return true;
}
std::wstring KeywordEditorView::GetWindowTitle() const {
return l10n_util::GetString(IDS_SEARCH_ENGINES_EDITOR_WINDOW_TITLE);
}
std::wstring KeywordEditorView::GetWindowName() const {
return prefs::kKeywordEditorWindowPlacement;
}
int KeywordEditorView::GetDialogButtons() const {
return MessageBoxFlags::DIALOGBUTTON_CANCEL;
}
bool KeywordEditorView::Accept() {
if (observer_)
observer_->SearchEngineChosen(
profile_->GetTemplateURLModel()->GetDefaultSearchProvider());
open_window = NULL;
return true;
}
bool KeywordEditorView::Cancel() {
if (observer_)
observer_->SearchEngineChosen(
profile_->GetTemplateURLModel()->GetDefaultSearchProvider());
open_window = NULL;
return true;
}
views::View* KeywordEditorView::GetContentsView() {
return this;
}
void KeywordEditorView::Init() {
std::vector<TableColumn> columns;
columns.push_back(
TableColumn(IDS_SEARCH_ENGINES_EDITOR_DESCRIPTION_COLUMN,
TableColumn::LEFT, -1, .75));
columns.back().sortable = true;
columns.push_back(
TableColumn(IDS_SEARCH_ENGINES_EDITOR_KEYWORD_COLUMN,
TableColumn::LEFT, -1, .25));
columns.back().sortable = true;
table_view_ = new views::TableView(controller_->table_model(), columns,
views::ICON_AND_TEXT, false, true, true);
table_view_->SetObserver(this);
add_button_ = new views::NativeButton(
this, l10n_util::GetString(IDS_SEARCH_ENGINES_EDITOR_NEW_BUTTON));
add_button_->SetEnabled(controller_->loaded());
add_button_->AddAccelerator(
views::Accelerator(base::VKEY_A, false, false, true));
add_button_->SetAccessibleKeyboardShortcut(L"A");
edit_button_ = new views::NativeButton(
this, l10n_util::GetString(IDS_SEARCH_ENGINES_EDITOR_EDIT_BUTTON));
edit_button_->SetEnabled(false);
remove_button_ = new views::NativeButton(
this, l10n_util::GetString(IDS_SEARCH_ENGINES_EDITOR_REMOVE_BUTTON));
remove_button_->SetEnabled(false);
remove_button_->AddAccelerator(
views::Accelerator(base::VKEY_R, false, false, true));
remove_button_->SetAccessibleKeyboardShortcut(L"R");
make_default_button_ = new views::NativeButton(
this,
l10n_util::GetString(IDS_SEARCH_ENGINES_EDITOR_MAKE_DEFAULT_BUTTON));
make_default_button_->SetEnabled(false);
InitLayoutManager();
}
void KeywordEditorView::InitLayoutManager() {
const int related_x = kRelatedControlHorizontalSpacing;
const int related_y = kRelatedControlVerticalSpacing;
const int unrelated_y = kUnrelatedControlVerticalSpacing;
GridLayout* contents_layout = CreatePanelGridLayout(this);
SetLayoutManager(contents_layout);
// For the table and buttons.
views::ColumnSet* column_set = contents_layout->AddColumnSet(0);
column_set->AddColumn(GridLayout::FILL, GridLayout::FILL, 1,
GridLayout::USE_PREF, 0, 0);
column_set->AddPaddingColumn(0, related_x);
column_set->AddColumn(GridLayout::FILL, GridLayout::CENTER, 0,
GridLayout::USE_PREF, 0, 0);
contents_layout->StartRow(0, 0);
contents_layout->AddView(table_view_, 1, 8, GridLayout::FILL,
GridLayout::FILL);
contents_layout->AddView(add_button_);
contents_layout->StartRowWithPadding(0, 0, 0, related_y);
contents_layout->SkipColumns(2);
contents_layout->AddView(edit_button_);
contents_layout->StartRowWithPadding(0, 0, 0, related_y);
contents_layout->SkipColumns(2);
contents_layout->AddView(remove_button_);
contents_layout->StartRowWithPadding(0, 0, 0, related_y);
contents_layout->SkipColumns(2);
contents_layout->AddView(make_default_button_);
contents_layout->AddPaddingRow(1, 0);
}
void KeywordEditorView::OnSelectionChanged() {
bool only_one_url_left =
controller_->url_model()->GetTemplateURLs().size() == 1;
if (table_view_->SelectedRowCount() == 1) {
edit_button_->SetEnabled(true);
const TemplateURL* selected_url =
controller_->GetTemplateURL(table_view_->FirstSelectedRow());
make_default_button_->SetEnabled(controller_->CanMakeDefault(selected_url));
remove_button_->SetEnabled(!only_one_url_left &&
controller_->CanRemove(selected_url));
} else {
edit_button_->SetEnabled(false);
make_default_button_->SetEnabled(false);
for (views::TableView::iterator i = table_view_->SelectionBegin();
i != table_view_->SelectionEnd(); ++i) {
const TemplateURL* selected_url = controller_->GetTemplateURL(*i);
if (!controller_->CanRemove(selected_url)) {
remove_button_->SetEnabled(false);
return;
}
}
remove_button_->SetEnabled(!only_one_url_left);
}
}
void KeywordEditorView::OnDoubleClick() {
if (edit_button_->IsEnabled()) {
DWORD pos = GetMessagePos();
gfx::Point cursor_point(pos);
views::MouseEvent event(views::Event::ET_MOUSE_RELEASED,
cursor_point.x(), cursor_point.y(),
views::Event::EF_LEFT_BUTTON_DOWN);
ButtonPressed(edit_button_, event);
}
}
void KeywordEditorView::ButtonPressed(
views::Button* sender, const views::Event& event) {
if (sender == add_button_) {
browser::EditSearchEngine(GetWindow()->GetNativeWindow(), NULL, this,
profile_);
} else if (sender == remove_button_) {
DCHECK_GT(table_view_->SelectedRowCount(), 0);
int last_view_row = -1;
for (views::TableView::iterator i = table_view_->SelectionBegin();
i != table_view_->SelectionEnd(); ++i) {
last_view_row = table_view_->model_to_view(*i);
controller_->RemoveTemplateURL(*i);
}
if (last_view_row >= controller_->table_model()->RowCount())
last_view_row = controller_->table_model()->RowCount() - 1;
if (last_view_row >= 0)
table_view_->Select(table_view_->view_to_model(last_view_row));
} else if (sender == edit_button_) {
const int selected_row = table_view_->FirstSelectedRow();
const TemplateURL* template_url =
controller_->GetTemplateURL(selected_row);
browser::EditSearchEngine(GetWindow()->GetNativeWindow(), template_url,
this, profile_);
} else if (sender == make_default_button_) {
MakeDefaultTemplateURL();
} else {
NOTREACHED();
}
}
void KeywordEditorView::OnTemplateURLModelChanged() {
add_button_->SetEnabled(controller_->loaded());
}
void KeywordEditorView::MakeDefaultTemplateURL() {
int new_index =
controller_->MakeDefaultTemplateURL(table_view_->FirstSelectedRow());
if (new_index >= 0)
table_view_->Select(new_index);
default_chosen_ = true;
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/perftimer.h"
#include "base/string_util.h"
#include "base/time.h"
#include "chrome/app/chrome_command_ids.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/automation/window_proxy.h"
#include "chrome/test/ui/ui_perf_test.h"
#include "gfx/rect.h"
#include "net/base/net_util.h"
using base::TimeDelta;
namespace {
class NewTabUIStartupTest : public UIPerfTest {
public:
NewTabUIStartupTest() {
show_window_ = true;
}
void SetUp() {}
void TearDown() {}
static const int kNumCycles = 5;
void PrintTimings(const char* label, TimeDelta timings[kNumCycles],
bool important) {
std::string times;
for (int i = 0; i < kNumCycles; ++i)
base::StringAppendF(×, "%.2f,", timings[i].InMillisecondsF());
PrintResultList("new_tab", "", label, times, "ms", important);
}
void InitProfile(ProxyLauncher::ProfileType profile_type) {
profile_type_ = profile_type;
// Install the location of the test profile file.
set_template_user_data(UITest::ComputeTypicalUserDataSource(
profile_type));
// Disable the first run notification because it has an animation which
// masks any real performance regressions.
launch_arguments_.AppendSwitch(switches::kDisableNewTabFirstRun);
}
// Run the test, by bringing up a browser and timing the new tab startup.
// |want_warm| is true if we should output warm-disk timings, false if
// we should report cold timings.
void RunStartupTest(const char* label, bool want_warm, bool important,
ProxyLauncher::ProfileType profile_type) {
InitProfile(profile_type);
TimeDelta timings[kNumCycles];
for (int i = 0; i < kNumCycles; ++i) {
UITest::SetUp();
// Switch to the "new tab" tab, which should be any new tab after the
// first (the first is about:blank).
scoped_refptr<BrowserProxy> window(automation()->GetBrowserWindow(0));
ASSERT_TRUE(window.get());
// We resize the window so that we hit the normal layout of the NTP and
// not the small layout mode.
#if defined(OS_WIN)
// TODO(port): SetBounds returns false when not implemented.
// It is OK to comment out the resize since it will still be useful to
// test the default size of the window.
ASSERT_TRUE(window->GetWindow().get()->SetBounds(gfx::Rect(1000, 1000)));
#endif
int tab_count = -1;
ASSERT_TRUE(window->GetTabCount(&tab_count));
ASSERT_EQ(1, tab_count);
// Hit ctl-t and wait for the tab to load.
ASSERT_TRUE(window->RunCommand(IDC_NEW_TAB));
ASSERT_TRUE(window->GetTabCount(&tab_count));
ASSERT_EQ(2, tab_count);
int load_time;
ASSERT_TRUE(automation()->WaitForInitialNewTabUILoad(&load_time));
if (want_warm) {
// Bring up a second tab, now that we've already shown one tab.
ASSERT_TRUE(window->RunCommand(IDC_NEW_TAB));
ASSERT_TRUE(window->GetTabCount(&tab_count));
ASSERT_EQ(3, tab_count);
ASSERT_TRUE(automation()->WaitForInitialNewTabUILoad(&load_time));
}
timings[i] = TimeDelta::FromMilliseconds(load_time);
window = NULL;
UITest::TearDown();
}
PrintTimings(label, timings, important);
}
void RunNewTabTimingTest() {
InitProfile(ProxyLauncher::DEFAULT_THEME);
TimeDelta scriptstart_times[kNumCycles];
TimeDelta domcontentloaded_times[kNumCycles];
TimeDelta onload_times[kNumCycles];
for (int i = 0; i < kNumCycles; ++i) {
UITest::SetUp();
// Switch to the "new tab" tab, which should be any new tab after the
// first (the first is about:blank).
scoped_refptr<BrowserProxy> window(automation()->GetBrowserWindow(0));
ASSERT_TRUE(window.get());
// We resize the window so that we hit the normal layout of the NTP and
// not the small layout mode.
#if defined(OS_WIN)
// TODO(port): SetBounds returns false when not implemented.
// It is OK to comment out the resize since it will still be useful to
// test the default size of the window.
ASSERT_TRUE(window->GetWindow().get()->SetBounds(gfx::Rect(1000, 1000)));
#endif
int tab_count = -1;
ASSERT_TRUE(window->GetTabCount(&tab_count));
ASSERT_EQ(1, tab_count);
// Hit ctl-t and wait for the tab to load.
ASSERT_TRUE(window->RunCommand(IDC_NEW_TAB));
ASSERT_TRUE(window->GetTabCount(&tab_count));
ASSERT_EQ(2, tab_count);
int duration;
ASSERT_TRUE(automation()->WaitForInitialNewTabUILoad(&duration));
// Collect the timing information.
ASSERT_TRUE(automation()->GetMetricEventDuration("Tab.NewTabScriptStart",
&duration));
scriptstart_times[i] = TimeDelta::FromMilliseconds(duration);
ASSERT_TRUE(automation()->GetMetricEventDuration(
"Tab.NewTabDOMContentLoaded", &duration));
domcontentloaded_times[i] = TimeDelta::FromMilliseconds(duration);
ASSERT_TRUE(automation()->GetMetricEventDuration("Tab.NewTabOnload",
&duration));
onload_times[i] = TimeDelta::FromMilliseconds(duration);
window = NULL;
UITest::TearDown();
}
PrintTimings("script_start", scriptstart_times, false /* important */);
PrintTimings("domcontent_loaded", domcontentloaded_times,
false /* important */);
PrintTimings("onload", onload_times, false /* important */);
}
};
TEST_F(NewTabUIStartupTest, PerfRefCold) {
UseReferenceBuild();
RunStartupTest("tab_cold_ref", false /* cold */, true /* important */,
ProxyLauncher::DEFAULT_THEME);
}
TEST_F(NewTabUIStartupTest, PerfCold) {
RunStartupTest("tab_cold", false /* cold */, true /* important */,
ProxyLauncher::DEFAULT_THEME);
}
TEST_F(NewTabUIStartupTest, PerfRefWarm) {
UseReferenceBuild();
RunStartupTest("tab_warm_ref", true /* warm */, true /* not important */,
ProxyLauncher::DEFAULT_THEME);
}
TEST_F(NewTabUIStartupTest, PerfWarm) {
RunStartupTest("tab_warm", true /* warm */, true /* not important */,
ProxyLauncher::DEFAULT_THEME);
}
TEST_F(NewTabUIStartupTest, ComplexThemeCold) {
RunStartupTest("tab_complex_theme_cold", false /* cold */,
false /* not important */,
ProxyLauncher::COMPLEX_THEME);
}
TEST_F(NewTabUIStartupTest, NewTabTimingTestsCold) {
RunNewTabTimingTest();
}
#if defined(OS_LINUX)
TEST_F(NewTabUIStartupTest, GtkThemeCold) {
RunStartupTest("tab_gtk_theme_cold", false /* cold */,
false /* not important */,
ProxyLauncher::NATIVE_THEME);
}
TEST_F(NewTabUIStartupTest, NativeFrameCold) {
RunStartupTest("tab_custom_frame_cold", false /* cold */,
false /* not important */,
ProxyLauncher::CUSTOM_FRAME);
}
TEST_F(NewTabUIStartupTest, NativeFrameGtkThemeCold) {
RunStartupTest("tab_custom_frame_gtk_theme_cold", false /* cold */,
false /* not important */,
ProxyLauncher::CUSTOM_FRAME_NATIVE_THEME);
}
#endif
} // namespace
<commit_msg>Mark new tab tests as flaky.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/perftimer.h"
#include "base/string_util.h"
#include "base/time.h"
#include "chrome/app/chrome_command_ids.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/automation/window_proxy.h"
#include "chrome/test/ui/ui_perf_test.h"
#include "gfx/rect.h"
#include "net/base/net_util.h"
using base::TimeDelta;
namespace {
class NewTabUIStartupTest : public UIPerfTest {
public:
NewTabUIStartupTest() {
show_window_ = true;
}
void SetUp() {}
void TearDown() {}
static const int kNumCycles = 5;
void PrintTimings(const char* label, TimeDelta timings[kNumCycles],
bool important) {
std::string times;
for (int i = 0; i < kNumCycles; ++i)
base::StringAppendF(×, "%.2f,", timings[i].InMillisecondsF());
PrintResultList("new_tab", "", label, times, "ms", important);
}
void InitProfile(ProxyLauncher::ProfileType profile_type) {
profile_type_ = profile_type;
// Install the location of the test profile file.
set_template_user_data(UITest::ComputeTypicalUserDataSource(
profile_type));
// Disable the first run notification because it has an animation which
// masks any real performance regressions.
launch_arguments_.AppendSwitch(switches::kDisableNewTabFirstRun);
}
// Run the test, by bringing up a browser and timing the new tab startup.
// |want_warm| is true if we should output warm-disk timings, false if
// we should report cold timings.
void RunStartupTest(const char* label, bool want_warm, bool important,
ProxyLauncher::ProfileType profile_type) {
InitProfile(profile_type);
TimeDelta timings[kNumCycles];
for (int i = 0; i < kNumCycles; ++i) {
UITest::SetUp();
// Switch to the "new tab" tab, which should be any new tab after the
// first (the first is about:blank).
scoped_refptr<BrowserProxy> window(automation()->GetBrowserWindow(0));
ASSERT_TRUE(window.get());
// We resize the window so that we hit the normal layout of the NTP and
// not the small layout mode.
#if defined(OS_WIN)
// TODO(port): SetBounds returns false when not implemented.
// It is OK to comment out the resize since it will still be useful to
// test the default size of the window.
ASSERT_TRUE(window->GetWindow().get()->SetBounds(gfx::Rect(1000, 1000)));
#endif
int tab_count = -1;
ASSERT_TRUE(window->GetTabCount(&tab_count));
ASSERT_EQ(1, tab_count);
// Hit ctl-t and wait for the tab to load.
ASSERT_TRUE(window->RunCommand(IDC_NEW_TAB));
ASSERT_TRUE(window->GetTabCount(&tab_count));
ASSERT_EQ(2, tab_count);
int load_time;
ASSERT_TRUE(automation()->WaitForInitialNewTabUILoad(&load_time));
if (want_warm) {
// Bring up a second tab, now that we've already shown one tab.
ASSERT_TRUE(window->RunCommand(IDC_NEW_TAB));
ASSERT_TRUE(window->GetTabCount(&tab_count));
ASSERT_EQ(3, tab_count);
ASSERT_TRUE(automation()->WaitForInitialNewTabUILoad(&load_time));
}
timings[i] = TimeDelta::FromMilliseconds(load_time);
window = NULL;
UITest::TearDown();
}
PrintTimings(label, timings, important);
}
void RunNewTabTimingTest() {
InitProfile(ProxyLauncher::DEFAULT_THEME);
TimeDelta scriptstart_times[kNumCycles];
TimeDelta domcontentloaded_times[kNumCycles];
TimeDelta onload_times[kNumCycles];
for (int i = 0; i < kNumCycles; ++i) {
UITest::SetUp();
// Switch to the "new tab" tab, which should be any new tab after the
// first (the first is about:blank).
scoped_refptr<BrowserProxy> window(automation()->GetBrowserWindow(0));
ASSERT_TRUE(window.get());
// We resize the window so that we hit the normal layout of the NTP and
// not the small layout mode.
#if defined(OS_WIN)
// TODO(port): SetBounds returns false when not implemented.
// It is OK to comment out the resize since it will still be useful to
// test the default size of the window.
ASSERT_TRUE(window->GetWindow().get()->SetBounds(gfx::Rect(1000, 1000)));
#endif
int tab_count = -1;
ASSERT_TRUE(window->GetTabCount(&tab_count));
ASSERT_EQ(1, tab_count);
// Hit ctl-t and wait for the tab to load.
ASSERT_TRUE(window->RunCommand(IDC_NEW_TAB));
ASSERT_TRUE(window->GetTabCount(&tab_count));
ASSERT_EQ(2, tab_count);
int duration;
ASSERT_TRUE(automation()->WaitForInitialNewTabUILoad(&duration));
// Collect the timing information.
ASSERT_TRUE(automation()->GetMetricEventDuration("Tab.NewTabScriptStart",
&duration));
scriptstart_times[i] = TimeDelta::FromMilliseconds(duration);
ASSERT_TRUE(automation()->GetMetricEventDuration(
"Tab.NewTabDOMContentLoaded", &duration));
domcontentloaded_times[i] = TimeDelta::FromMilliseconds(duration);
ASSERT_TRUE(automation()->GetMetricEventDuration("Tab.NewTabOnload",
&duration));
onload_times[i] = TimeDelta::FromMilliseconds(duration);
window = NULL;
UITest::TearDown();
}
PrintTimings("script_start", scriptstart_times, false /* important */);
PrintTimings("domcontent_loaded", domcontentloaded_times,
false /* important */);
PrintTimings("onload", onload_times, false /* important */);
}
};
// FLAKY: http://crbug.com/69940
TEST_F(NewTabUIStartupTest, FLAKY_PerfRefCold) {
UseReferenceBuild();
RunStartupTest("tab_cold_ref", false /* cold */, true /* important */,
ProxyLauncher::DEFAULT_THEME);
}
// FLAKY: http://crbug.com/69940
TEST_F(NewTabUIStartupTest, FLAKY_PerfCold) {
RunStartupTest("tab_cold", false /* cold */, true /* important */,
ProxyLauncher::DEFAULT_THEME);
}
// FLAKY: http://crbug.com/69940
TEST_F(NewTabUIStartupTest, FLAKY_PerfRefWarm) {
UseReferenceBuild();
RunStartupTest("tab_warm_ref", true /* warm */, true /* not important */,
ProxyLauncher::DEFAULT_THEME);
}
// FLAKY: http://crbug.com/69940
TEST_F(NewTabUIStartupTest, FLAKY_PerfWarm) {
RunStartupTest("tab_warm", true /* warm */, true /* not important */,
ProxyLauncher::DEFAULT_THEME);
}
// FLAKY: http://crbug.com/69940
TEST_F(NewTabUIStartupTest, FLAKY_ComplexThemeCold) {
RunStartupTest("tab_complex_theme_cold", false /* cold */,
false /* not important */,
ProxyLauncher::COMPLEX_THEME);
}
// FLAKY: http://crbug.com/69940
TEST_F(NewTabUIStartupTest, FLAKY_NewTabTimingTestsCold) {
RunNewTabTimingTest();
}
#if defined(OS_LINUX)
TEST_F(NewTabUIStartupTest, GtkThemeCold) {
RunStartupTest("tab_gtk_theme_cold", false /* cold */,
false /* not important */,
ProxyLauncher::NATIVE_THEME);
}
TEST_F(NewTabUIStartupTest, NativeFrameCold) {
RunStartupTest("tab_custom_frame_cold", false /* cold */,
false /* not important */,
ProxyLauncher::CUSTOM_FRAME);
}
TEST_F(NewTabUIStartupTest, NativeFrameGtkThemeCold) {
RunStartupTest("tab_custom_frame_gtk_theme_cold", false /* cold */,
false /* not important */,
ProxyLauncher::CUSTOM_FRAME_NATIVE_THEME);
}
#endif
} // namespace
<|endoftext|>
|
<commit_before>/*
* OTV0P2BASE_SoftSerial2.cpp
*
* Created on: 15 Apr 2016
* Author: denzo
*/
#include "OTV0P2BASE_SoftSerial2.h"
namespace OTV0P2BASE
{
OTSoftSerial2::OTSoftSerial2(uint8_t _rxPin, uint8_t _txPin): rxPin(_rxPin), txPin(_txPin)
{
}
void OTV0P2BASE::OTSoftSerial2::begin(long speed) {
}
bool OTV0P2BASE::OTSoftSerial2::listen() {
}
void OTV0P2BASE::OTSoftSerial2::end() {
}
bool OTV0P2BASE::OTSoftSerial2::isListening() {
}
bool OTV0P2BASE::OTSoftSerial2::stopListening() {
}
bool OTV0P2BASE::OTSoftSerial2::overflow() {
}
int OTV0P2BASE::OTSoftSerial2::peek() {
}
size_t OTV0P2BASE::OTSoftSerial2::write(uint8_t byte) {
}
int OTV0P2BASE::OTSoftSerial2::read() {
}
int OTV0P2BASE::OTSoftSerial2::available() {
}
void OTV0P2BASE::OTSoftSerial2::flush() {
}
}
<commit_msg>fixed namespace<commit_after>/*
* OTV0P2BASE_SoftSerial2.cpp
*
* Created on: 15 Apr 2016
* Author: denzo
*/
#include "OTV0P2BASE_SoftSerial2.h"
namespace OTV0P2BASE
{
OTSoftSerial2::OTSoftSerial2(uint8_t _rxPin, uint8_t _txPin): rxPin(_rxPin), txPin(_txPin)
{
}
void OTSoftSerial2::begin(long speed) {
}
bool OTSoftSerial2::listen() {
}
void OTSoftSerial2::end() {
}
bool OTSoftSerial2::isListening() {
}
bool OTSoftSerial2::stopListening() {
}
bool OTSoftSerial2::overflow() {
}
int OTSoftSerial2::peek() {
}
size_t OTSoftSerial2::write(uint8_t byte) {
}
int OTSoftSerial2::read() {
}
int OTSoftSerial2::available() {
}
void OTSoftSerial2::flush() {
}
}
<|endoftext|>
|
<commit_before>/*
* Copyright 2016 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "Fuzz.h"
#include "FuzzCommon.h"
#include "SkPath.h"
#include "SkPathOps.h"
const int kLastOp = SkPathOp::kReverseDifference_SkPathOp;
DEF_FUZZ(Pathop, fuzz) {
SkOpBuilder builder;
uint8_t stragglerOp;
fuzz->next(&stragglerOp);
SkPath path;
FuzzEvilPath(fuzz, &path, SkPath::Verb::kDone_Verb);
builder.add(path, static_cast<SkPathOp>(stragglerOp % (kLastOp + 1)));
SkPath result;
builder.resolve(&result);
}
<commit_msg>Exercise entire public PathOp API<commit_after>/*
* Copyright 2016 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "Fuzz.h"
#include "FuzzCommon.h"
#include "SkPath.h"
#include "SkPathOps.h"
#include "SkRect.h"
const uint8_t MAX_OPS = 20;
DEF_FUZZ(Pathop, fuzz) {
uint8_t choice;
fuzz->nextRange(&choice, 0, 4);
switch (choice) {
case 0: {
SkPath path;
FuzzEvilPath(fuzz, &path, SkPath::Verb::kDone_Verb);
SkPath::FillType ft;
fuzz->nextEnum(&ft, 0, SkPath::kInverseEvenOdd_FillType);
path.setFillType(ft);
uint8_t ops;
fuzz->nextRange(&ops, 0, MAX_OPS);
SkOpBuilder builder;
for (uint8_t i = 0; i < ops; i++) {
SkPathOp op;
fuzz->nextEnum(&op, 0, SkPathOp::kReverseDifference_SkPathOp);
builder.add(path, op);
}
SkPath result;
builder.resolve(&result);
break;
}
case 1: {
SkPath path;
FuzzEvilPath(fuzz, &path, SkPath::Verb::kDone_Verb);
SkPath::FillType ft;
fuzz->nextEnum(&ft, 0, SkPath::kInverseEvenOdd_FillType);
path.setFillType(ft);
SkPath result;
bool isSame;
fuzz->next(&isSame);
if (isSame) {
result = path;
}
Simplify(path, &result);
break;
}
case 2: {
SkPath path;
FuzzEvilPath(fuzz, &path, SkPath::Verb::kDone_Verb);
SkPath::FillType ft;
fuzz->nextEnum(&ft, 0, SkPath::kInverseEvenOdd_FillType);
path.setFillType(ft);
SkPath path2;
FuzzEvilPath(fuzz, &path2, SkPath::Verb::kDone_Verb);
fuzz->nextEnum(&ft, 0, SkPath::kInverseEvenOdd_FillType);
path.setFillType(ft);
SkPathOp op;
fuzz->nextEnum(&op, 0, SkPathOp::kReverseDifference_SkPathOp);
SkPath result;
uint8_t pickOutput;
fuzz->nextRange(&pickOutput, 0, 2);
if (pickOutput == 1) {
result = path;
} else if (pickOutput == 2) {
result = path2;
}
Op(path, path2, op, &result);
break;
}
case 3: {
SkPath path;
FuzzEvilPath(fuzz, &path, SkPath::Verb::kDone_Verb);
SkPath::FillType ft;
fuzz->nextEnum(&ft, 0, SkPath::kInverseEvenOdd_FillType);
path.setFillType(ft);
SkPath result;
bool isSame;
fuzz->next(&isSame);
if (isSame) {
result = path;
}
AsWinding(path, &result);
break;
}
case 4: {
SkPath path;
FuzzEvilPath(fuzz, &path, SkPath::Verb::kDone_Verb);
SkPath::FillType ft;
fuzz->nextEnum(&ft, 0, SkPath::kInverseEvenOdd_FillType);
path.setFillType(ft);
SkRect result;
TightBounds(path, &result);
break;
}
default: {
SkASSERT(false);
break;
}
}
}
<|endoftext|>
|
<commit_before>/*
* Copyright 2013 Puck Meerburg, [email protected]
* All rights reserved. Distributed under the terms of the MIT License.
*/
#include "BlogPositivePlugin.h"
#include <TextControl.h>
#include <Message.h>
#include <GroupLayout.h>
#include <LayoutBuilder.h>
#include <Window.h>
#include <List.h>
#include "../BlogPositiveMain/BlogPositiveMainView.h"
#include "../BlogPositiveSettings.h"
class BlogPositiveCreateBlog : public BWindow {
public:
BlogPositiveCreateBlog(BlogPositiveMainView* aView,
BlogPositivePlugin* pl);
void SetBlogHandler(int32 blogHandler);
void MessageReceived(BMessage* message);
int32 BlogHandler();
private:
int32 fBlogHandler;
BTextControl* fNameControl;
BTextControl* fAuthControl;
BlogPositiveMainView* fMainView;
};
BlogPositiveCreateBlog::BlogPositiveCreateBlog(BlogPositiveMainView* aView,
BlogPositivePlugin* pl)
:
BWindow(BRect(100, 100, 400, 190), "Create Blog",
B_MODAL_WINDOW_LOOK, B_NORMAL_WINDOW_FEEL, 0)
{
fNameControl = new BTextControl("NameControl", "Name: ",
"", new BMessage('CBFA'));
fAuthControl = new BTextControl("AuthControl", "Auth: ",
"", new BMessage('CBNB'));
SetLayout(new BGroupLayout(B_VERTICAL));
AddChild(fNameControl);
AddChild(fAuthControl);
fMainView = aView;
fNameControl->MakeFocus();
fBlogHandler = pl->MainHandler();
}
void
BlogPositiveCreateBlog::SetBlogHandler(int32 blogHandler)
{
fBlogHandler = blogHandler;
}
void
BlogPositiveCreateBlog::MessageReceived(BMessage* message)
{
switch (message->what) {
case 'CBFA':
fAuthControl->MakeFocus();
break;
case 'CBNB':
{
BlogPositiveSettings* settings = new BlogPositiveSettings("bloglist");
BlogList* lis = BlogPositiveBlog::DeserializeList(settings, "blogs");
BlogPositiveBlog* blog = new BlogPositiveBlog();
blog->SetName(fNameControl->Text());
blog->SetAuthentication(fAuthControl->Text());
blog->SetBlogHandler(fBlogHandler);
lis->AddItem(blog);
if (fMainView->LockLooper())
{
fMainView->Reload(lis);
fMainView->UnlockLooper();
}
BlogPositiveSettings::SaveOther(
BlogPositiveBlog::SerializeList(lis, "blogs"), "bloglist");
Hide();
break;
}
default:
BWindow::MessageReceived(message);
break;
}
}
uint32
BlogPositivePlugin::Version()
{
return 0;
}
uint32
BlogPositivePlugin::MainHandler()
{
return 'BACN';
}
const char*
BlogPositivePlugin::Name()
{
return "Unknown";
}
int32
BlogPositivePlugin::Type()
{
return kBlogPositiveBlogApi;
}
bool
BlogPositivePlugin::Supports(int32 Code)
{
return false;
}
PostList*
BlogPositivePlugin::GetBlogPosts(BlogPositiveBlog* blog)
{
return new PostList();
}
BlogPositivePost*
BlogPositivePlugin::CreateNewPost(BlogPositiveBlog* blog, const char* name)
{
return NULL;
}
void
BlogPositivePlugin::RemovePost(BlogPositivePost* post)
{
}
void
BlogPositivePlugin::SavePost(BlogPositivePost* post)
{
}
void
BlogPositivePlugin::OpenNewBlogWindow(BlogPositiveMainView* mainView)
{
(new BlogPositiveCreateBlog(mainView, this))->Show();
}
<commit_msg>Add view for plugin<commit_after>/*
* Copyright 2013 Puck Meerburg, [email protected]
* All rights reserved. Distributed under the terms of the MIT License.
*/
#include "BlogPositivePlugin.h"
#include <TextControl.h>
#include <Message.h>
#include <GroupLayout.h>
#include <LayoutBuilder.h>
#include <Window.h>
#include <List.h>
#include "../BlogPositiveMain/BlogPositiveMainView.h"
#include "../BlogPositiveSettings.h"
class BlogPositiveCreateBlog : public BWindow {
public:
BlogPositiveCreateBlog(BlogPositiveMainView* aView,
BlogPositivePlugin* pl);
void SetBlogHandler(int32 blogHandler);
void MessageReceived(BMessage* message);
int32 BlogHandler();
private:
int32 fBlogHandler;
BTextControl* fNameControl;
BTextControl* fAuthControl;
BlogPositiveMainView* fMainView;
};
BlogPositiveCreateBlog::BlogPositiveCreateBlog(BlogPositiveMainView* aView,
BlogPositivePlugin* pl)
:
BWindow(BRect(100, 100, 400, 190), "Create Blog",
B_MODAL_WINDOW_LOOK, B_NORMAL_WINDOW_FEEL, 0)
{
fNameControl = new BTextControl("NameControl", "Name: ",
"", new BMessage('CBFA'));
fAuthControl = new BTextControl("AuthControl", "Auth: ",
"", new BMessage('CBNB'));
SetLayout(new BGroupLayout(B_VERTICAL));
BView* view = new BView("view", B_SUPPORTS_LAYOUT);
view->SetLayout(new BGroupLayout(B_VERTICAL));
view->AddChild(fNameControl);
view->AddChild(fAuthControl);
AddChild(view);
fMainView = aView;
fNameControl->MakeFocus();
fBlogHandler = pl->MainHandler();
}
void
BlogPositiveCreateBlog::SetBlogHandler(int32 blogHandler)
{
fBlogHandler = blogHandler;
}
void
BlogPositiveCreateBlog::MessageReceived(BMessage* message)
{
switch (message->what) {
case 'CBFA':
fAuthControl->MakeFocus();
break;
case 'CBNB':
{
BlogPositiveSettings* settings = new BlogPositiveSettings("bloglist");
BlogList* lis = BlogPositiveBlog::DeserializeList(settings, "blogs");
BlogPositiveBlog* blog = new BlogPositiveBlog();
blog->SetName(fNameControl->Text());
blog->SetAuthentication(fAuthControl->Text());
blog->SetBlogHandler(fBlogHandler);
lis->AddItem(blog);
if (fMainView->LockLooper())
{
fMainView->Reload(lis);
fMainView->UnlockLooper();
}
BlogPositiveSettings::SaveOther(
BlogPositiveBlog::SerializeList(lis, "blogs"), "bloglist");
Hide();
break;
}
default:
BWindow::MessageReceived(message);
break;
}
}
uint32
BlogPositivePlugin::Version()
{
return 0;
}
uint32
BlogPositivePlugin::MainHandler()
{
return 'BACN';
}
const char*
BlogPositivePlugin::Name()
{
return "Unknown";
}
int32
BlogPositivePlugin::Type()
{
return kBlogPositiveBlogApi;
}
bool
BlogPositivePlugin::Supports(int32 Code)
{
return false;
}
PostList*
BlogPositivePlugin::GetBlogPosts(BlogPositiveBlog* blog)
{
return new PostList();
}
BlogPositivePost*
BlogPositivePlugin::CreateNewPost(BlogPositiveBlog* blog, const char* name)
{
return NULL;
}
void
BlogPositivePlugin::RemovePost(BlogPositivePost* post)
{
}
void
BlogPositivePlugin::SavePost(BlogPositivePost* post)
{
}
void
BlogPositivePlugin::OpenNewBlogWindow(BlogPositiveMainView* mainView)
{
(new BlogPositiveCreateBlog(mainView, this))->Show();
}
<|endoftext|>
|
<commit_before>/*
* APSRack.cpp
*
* Created on: Jun 13, 2012
* Author: cryan
*/
#include "APSRack.h"
APSRack::APSRack() : numDevices_{0} {
}
APSRack::~APSRack() {
//Close the logging file so we don't leave it dangling
fclose(Output2FILE::Stream());
}
//Initialize the rack by polling for devices and serial numbers
int APSRack::init() {
//Create the logger
FILE* pFile = fopen("libaps.log", "a");
Output2FILE::Stream() = pFile;
//Enumerate the serial numbers of the devices attached
enumerate_devices();
return 0;
}
//Initialize a specific APS unit
int APSRack::initAPS(const int & deviceID, const string & bitFile, const bool & forceReload){
return APSs_[deviceID].init(bitFile, forceReload);
}
int APSRack::get_num_devices() {
int numDevices;
FT_ListDevices(&numDevices, NULL, FT_LIST_NUMBER_ONLY);
if (numDevices_ != numDevices) {
update_device_enumeration();
}
return numDevices;
}
string APSRack::get_deviceSerial(const int & deviceID) {
// get current number of devices
get_num_devices();
// Get serials from FTDI layer to check for change in devices
vector<string> testSerials;
FTDI::get_device_serials(testSerials);
// match serials for each device id to make sure mapping of device count to serial
// number is still correct
// if serial number is different re-enumerate
for(unsigned int cnt = 0; cnt < testSerials.size(); cnt++) {
if (testSerials[cnt].compare(deviceSerials_[cnt]) != 0) {
FILE_LOG(logDEBUG) << testSerials[cnt] << " does not match " << deviceSerials_[cnt] << " re-enumerating.";
update_device_enumeration();
break;
}
}
// test to make sure ID is valid relative to vector size
if (static_cast<size_t>(deviceID) > deviceSerials_.size()) {
return "InvalidID";
}
return deviceSerials_[deviceID];
}
//This will reset the APS vector so it really should only be called during initialization
void APSRack::enumerate_devices() {
//Have to disconnect everything first
for (auto & aps : APSs_){
aps.disconnect();
}
FTDI::get_device_serials(deviceSerials_);
numDevices_ = deviceSerials_.size();
APSs_.clear();
APSs_.reserve(numDevices_);
// Now setup the map between device serials and number and assign the APS units appropriately
// Also setup the FPGA checksums
size_t devicect = 0;
for (string tmpSerial : deviceSerials_) {
serial2dev[tmpSerial] = devicect;
APSs_.emplace_back(devicect, tmpSerial);
FILE_LOG(logDEBUG) << "Device " << devicect << " has serial number " << tmpSerial;
devicect++;
}
}
// This will update enumerate of devices by matching serial numbers
// If a device is missing it will be removed
// New devices are added
// Old devices are left as is (moved in place to new vector)
void APSRack::update_device_enumeration() {
vector<string> newSerials;
FTDI::get_device_serials(newSerials);
// construct new APS_ vector & new serial2dev map
vector<APS> newAPS_;
map<string, int> newSerial2dev;
size_t devicect = 0;
for (string tmpSerial : newSerials) {
// example test to see if FTDI thinks device is open
if (FTDI::isOpen(devicect)) {
FILE_LOG(logDEBUG) << "Device " << devicect << " [ " << tmpSerial << " ] is open";
}
// does the new serial number exist in the old list?
if ( serial2dev.count(tmpSerial) > 0) {
// move from old APSs_ vector to new
newAPS_.push_back(std::move(APSs_[serial2dev[tmpSerial]]));
FILE_LOG(logDEBUG) << "Old Device " << devicect << " [ " << tmpSerial << " ] moved";
} else {
// does not exist so construct it in the new vector
newAPS_.emplace_back(devicect, tmpSerial);
FILE_LOG(logDEBUG) << "New Device " << devicect << " [ " << tmpSerial << " ]";
}
newSerial2dev[tmpSerial] = devicect;
devicect++;
}
// update APSRack members with new lists
numDevices_ = newSerials.size(); // number of devices
deviceSerials_ = newSerials; // device serial vector
APSs_ = std::move(newAPS_); // APS vector
serial2dev = newSerial2dev; // serial to device map
}
int APSRack::read_bitfile_version(const int & deviceID) const {
return APSs_[deviceID].read_bitFile_version(ALL_FPGAS);
}
int APSRack::connect(const int & deviceID){
//Connect to a instrument specified by deviceID
return APSs_[deviceID].connect();
}
int APSRack::disconnect(const int & deviceID){
return APSs_[deviceID].disconnect();
}
int APSRack::connect(const string & deviceSerial){
//Look up the associated ID and call the next connect
return APSs_[serial2dev[deviceSerial]].connect();
}
int APSRack::disconnect(const string & deviceSerial){
//Look up the associated ID and call the next connect
return APSs_[serial2dev[deviceSerial]].disconnect();
}
int APSRack::program_FPGA(const int & deviceID, const string &bitFile, const FPGASELECT & chipSelect, const int & expectedVersion){
return APSs_[deviceID].program_FPGA(bitFile, chipSelect, expectedVersion);
}
int APSRack::setup_DACs(const int & deviceID) const{
return APSs_[deviceID].setup_DACs();
}
int APSRack::set_sampleRate(const int & deviceID, const int & freq) {
return APSs_[deviceID].set_sampleRate(freq);
}
int APSRack::get_sampleRate(const int & deviceID) const{
return APSs_[deviceID].get_sampleRate();
}
int APSRack::set_run_mode(const int & deviceID, const int & dac, const RUN_MODE & mode){
return APSs_[deviceID].set_run_mode(dac, mode);
}
int APSRack::set_repeat_mode(const int & deviceID, const int & dac, const bool & mode){
return APSs_[deviceID].set_repeat_mode(dac, mode);
}
int APSRack::clear_channel_data(const int & deviceID) {
return APSs_[deviceID].clear_channel_data();
}
int APSRack::run(const int & deviceID) {
return APSs_[deviceID].run();
}
int APSRack::stop(const int & deviceID) {
return APSs_[deviceID].stop();
}
int APSRack::load_sequence_file(const int & deviceID, const string & seqFile){
return APSs_[deviceID].load_sequence_file(seqFile);
}
int APSRack::set_LL_data(const int & deviceID, const int & channelNum, const WordVec & addr, const WordVec & count, const WordVec & trigger1, const WordVec & trigger2, const WordVec & repeat){
return APSs_[deviceID].set_LLData_IQ(dac2fpga(channelNum), addr, count, trigger1, trigger2, repeat);
}
int APSRack::get_running(const int & deviceID){
//TODO:
// return APSs_[deviceID].running_;
return 0;
}
int APSRack::set_log(FILE * pFile) {
if (pFile) {
//Close the current file
if(Output2FILE::Stream()) fclose(Output2FILE::Stream());
//Assign the new one
Output2FILE::Stream() = pFile;
return 1;
} else {
return 0;
}
}
int APSRack::set_logging_level(const int & logLevel){
FILELog::ReportingLevel() = TLogLevel(logLevel);
return 0;
}
int APSRack::set_trigger_source(const int & deviceID, const TRIGGERSOURCE & triggerSource) {
return APSs_[deviceID].set_trigger_source(triggerSource);
}
TRIGGERSOURCE APSRack::get_trigger_source(const int & deviceID) const{
return APSs_[deviceID].get_trigger_source();
}
int APSRack::set_trigger_interval(const int & deviceID, const double & interval){
return APSs_[deviceID].set_trigger_interval(interval);
}
double APSRack::get_trigger_interval(const int & deviceID) const{
return APSs_[deviceID].get_trigger_interval();
}
int APSRack::set_miniLL_repeat(const int & deviceID, const USHORT & repeat){
return APSs_[deviceID].set_miniLL_repeat(repeat);
}
int APSRack::set_channel_enabled(const int & deviceID, const int & channelNum, const bool & enable){
return APSs_[deviceID].set_channel_enabled(channelNum, enable);
}
bool APSRack::get_channel_enabled(const int & deviceID, const int & channelNum) const{
return APSs_[deviceID].get_channel_enabled(channelNum);
}
int APSRack::set_channel_offset(const int & deviceID, const int & channelNum, const float & offset){
return APSs_[deviceID].set_channel_offset(channelNum, offset);
}
float APSRack::get_channel_offset(const int & deviceID, const int & channelNum) const{
return APSs_[deviceID].get_channel_offset(channelNum);
}
int APSRack::set_channel_scale(const int & deviceID, const int & channelNum, const float & scale){
return APSs_[deviceID].set_channel_scale(channelNum, scale);
}
float APSRack::get_channel_scale(const int & deviceID, const int & channelNum) const{
return APSs_[deviceID].get_channel_scale(channelNum);
}
int APSRack::save_state_files(){
// loop through available APS Units and save state
for(unsigned int apsct = 0; apsct < APSs_.size(); apsct++) {
string stateFileName = ""; // use default file name
APSs_[apsct].save_state_file(stateFileName);
}
return 0;
}
int APSRack::read_state_files(){
// loop through available APS Units and load state
for(unsigned int apsct = 0; apsct < APSs_.size(); apsct++) {
string stateFileName = ""; // use default file name
APSs_[apsct].read_state_file(stateFileName);
}
return 0;
}
int APSRack::save_bulk_state_file(string & stateFile){
if (stateFile.length() == 0) {
stateFile += "cache_APSRack.h5";
}
FILE_LOG(logDEBUG) << "Writing Bulk State File " << stateFile;
H5::H5File H5StateFile(stateFile, H5F_ACC_TRUNC);
// loop through available APS Units and save state
for(unsigned int apsct = 0; apsct < APSs_.size(); apsct++) {
string rootStr = "/";
rootStr += APSs_[apsct].deviceSerial_ ;
FILE_LOG(logDEBUG) << "Creating Group: " << rootStr;
H5::Group tmpGroup = H5StateFile.createGroup(rootStr);
tmpGroup.close();
APSs_[apsct].write_state_to_hdf5(H5StateFile, rootStr);
}
//Close the file
H5StateFile.close();
return 0;
}
int APSRack::read_bulk_state_file(string & stateFile){
if (stateFile.length() == 0) {
stateFile += "cache_APSRack.h5";
}
FILE_LOG(logDEBUG) << "Reading Bulk State File " << stateFile;
H5::H5File H5StateFile(stateFile, H5F_ACC_RDONLY);
// loop through available APS Units and load data
for(unsigned int apsct = 0; apsct < APSs_.size(); apsct++) {
string rootStr = "/";
rootStr += "/" + APSs_[apsct].deviceSerial_;
APSs_[apsct].read_state_from_hdf5(H5StateFile, rootStr);
}
//Close the file
H5StateFile.close();
return 0;
}
int APSRack::raw_write(int deviceID, int numBytes, UCHAR* data){
DWORD bytesWritten;
FT_Write(APSs_[deviceID].handle_, data, numBytes, &bytesWritten);
return int(bytesWritten);
}
int APSRack::raw_read(int deviceID, FPGASELECT fpga) {
DWORD bytesRead, bytesWritten;
UCHAR dataBuffer[2];
USHORT transferSize = 1;
int Command = APS_FPGA_IO;
//Send the read command byte
UCHAR commandPacket = 0x80 | Command | (fpga<<2) | transferSize;
FT_Write(APSs_[deviceID].handle_, &commandPacket, 1, &bytesWritten);
//Look for the data
FT_Read(APSs_[deviceID].handle_, dataBuffer, 2, &bytesRead);
FILE_LOG(logDEBUG2) << "Read " << bytesRead << " bytes with value" << myhex << ((dataBuffer[0] << 8) | dataBuffer[1]);
return int((dataBuffer[0] << 8) | dataBuffer[1]);
}
int APSRack::read_register(int deviceID, FPGASELECT fpga, int addr){
return FPGA::read_FPGA(APSs_[deviceID].handle_, addr, fpga);
}
<commit_msg>Update deviceID when moving<commit_after>/*
* APSRack.cpp
*
* Created on: Jun 13, 2012
* Author: cryan
*/
#include "APSRack.h"
APSRack::APSRack() : numDevices_{0} {
}
APSRack::~APSRack() {
//Close the logging file so we don't leave it dangling
fclose(Output2FILE::Stream());
}
//Initialize the rack by polling for devices and serial numbers
int APSRack::init() {
//Create the logger
FILE* pFile = fopen("libaps.log", "a");
Output2FILE::Stream() = pFile;
//Enumerate the serial numbers of the devices attached
enumerate_devices();
return 0;
}
//Initialize a specific APS unit
int APSRack::initAPS(const int & deviceID, const string & bitFile, const bool & forceReload){
return APSs_[deviceID].init(bitFile, forceReload);
}
int APSRack::get_num_devices() {
int numDevices;
FT_ListDevices(&numDevices, NULL, FT_LIST_NUMBER_ONLY);
if (numDevices_ != numDevices) {
update_device_enumeration();
}
return numDevices;
}
string APSRack::get_deviceSerial(const int & deviceID) {
// get current number of devices
get_num_devices();
// Get serials from FTDI layer to check for change in devices
vector<string> testSerials;
FTDI::get_device_serials(testSerials);
// match serials for each device id to make sure mapping of device count to serial
// number is still correct
// if serial number is different re-enumerate
for(unsigned int cnt = 0; cnt < testSerials.size(); cnt++) {
if (testSerials[cnt].compare(deviceSerials_[cnt]) != 0) {
FILE_LOG(logDEBUG) << testSerials[cnt] << " does not match " << deviceSerials_[cnt] << " re-enumerating.";
update_device_enumeration();
break;
}
}
// test to make sure ID is valid relative to vector size
if (static_cast<size_t>(deviceID) > deviceSerials_.size()) {
return "InvalidID";
}
return deviceSerials_[deviceID];
}
//This will reset the APS vector so it really should only be called during initialization
void APSRack::enumerate_devices() {
//Have to disconnect everything first
for (auto & aps : APSs_){
aps.disconnect();
}
FTDI::get_device_serials(deviceSerials_);
numDevices_ = deviceSerials_.size();
APSs_.clear();
APSs_.reserve(numDevices_);
// Now setup the map between device serials and number and assign the APS units appropriately
// Also setup the FPGA checksums
size_t devicect = 0;
for (string tmpSerial : deviceSerials_) {
serial2dev[tmpSerial] = devicect;
APSs_.emplace_back(devicect, tmpSerial);
FILE_LOG(logDEBUG) << "Device " << devicect << " has serial number " << tmpSerial;
devicect++;
}
}
// This will update enumerate of devices by matching serial numbers
// If a device is missing it will be removed
// New devices are added
// Old devices are left as is (moved in place to new vector)
void APSRack::update_device_enumeration() {
vector<string> newSerials;
FTDI::get_device_serials(newSerials);
// construct new APS_ vector & new serial2dev map
vector<APS> newAPS_;
map<string, int> newSerial2dev;
size_t devicect = 0;
for (string tmpSerial : newSerials) {
// example test to see if FTDI thinks device is open
if (FTDI::isOpen(devicect)) {
FILE_LOG(logDEBUG) << "Device " << devicect << " [ " << tmpSerial << " ] is open";
}
// does the new serial number exist in the old list?
if ( serial2dev.count(tmpSerial) > 0) {
// move from old APSs_ vector to new
newAPS_.push_back(std::move(APSs_[serial2dev[tmpSerial]]));
newAPS_.back().deviceID_ = devicect;
FILE_LOG(logDEBUG) << "Old Device " << devicect << " [ " << tmpSerial << " ] moved";
} else {
// does not exist so construct it in the new vector
newAPS_.emplace_back(devicect, tmpSerial);
FILE_LOG(logDEBUG) << "New Device " << devicect << " [ " << tmpSerial << " ]";
}
newSerial2dev[tmpSerial] = devicect;
devicect++;
}
// update APSRack members with new lists
numDevices_ = newSerials.size(); // number of devices
deviceSerials_ = newSerials; // device serial vector
APSs_ = std::move(newAPS_); // APS vector
serial2dev = newSerial2dev; // serial to device map
}
int APSRack::read_bitfile_version(const int & deviceID) const {
return APSs_[deviceID].read_bitFile_version(ALL_FPGAS);
}
int APSRack::connect(const int & deviceID){
//Connect to a instrument specified by deviceID
return APSs_[deviceID].connect();
}
int APSRack::disconnect(const int & deviceID){
return APSs_[deviceID].disconnect();
}
int APSRack::connect(const string & deviceSerial){
//Look up the associated ID and call the next connect
return APSs_[serial2dev[deviceSerial]].connect();
}
int APSRack::disconnect(const string & deviceSerial){
//Look up the associated ID and call the next connect
return APSs_[serial2dev[deviceSerial]].disconnect();
}
int APSRack::program_FPGA(const int & deviceID, const string &bitFile, const FPGASELECT & chipSelect, const int & expectedVersion){
return APSs_[deviceID].program_FPGA(bitFile, chipSelect, expectedVersion);
}
int APSRack::setup_DACs(const int & deviceID) const{
return APSs_[deviceID].setup_DACs();
}
int APSRack::set_sampleRate(const int & deviceID, const int & freq) {
return APSs_[deviceID].set_sampleRate(freq);
}
int APSRack::get_sampleRate(const int & deviceID) const{
return APSs_[deviceID].get_sampleRate();
}
int APSRack::set_run_mode(const int & deviceID, const int & dac, const RUN_MODE & mode){
return APSs_[deviceID].set_run_mode(dac, mode);
}
int APSRack::set_repeat_mode(const int & deviceID, const int & dac, const bool & mode){
return APSs_[deviceID].set_repeat_mode(dac, mode);
}
int APSRack::clear_channel_data(const int & deviceID) {
return APSs_[deviceID].clear_channel_data();
}
int APSRack::run(const int & deviceID) {
return APSs_[deviceID].run();
}
int APSRack::stop(const int & deviceID) {
return APSs_[deviceID].stop();
}
int APSRack::load_sequence_file(const int & deviceID, const string & seqFile){
return APSs_[deviceID].load_sequence_file(seqFile);
}
int APSRack::set_LL_data(const int & deviceID, const int & channelNum, const WordVec & addr, const WordVec & count, const WordVec & trigger1, const WordVec & trigger2, const WordVec & repeat){
return APSs_[deviceID].set_LLData_IQ(dac2fpga(channelNum), addr, count, trigger1, trigger2, repeat);
}
int APSRack::get_running(const int & deviceID){
//TODO:
// return APSs_[deviceID].running_;
return 0;
}
int APSRack::set_log(FILE * pFile) {
if (pFile) {
//Close the current file
if(Output2FILE::Stream()) fclose(Output2FILE::Stream());
//Assign the new one
Output2FILE::Stream() = pFile;
return 1;
} else {
return 0;
}
}
int APSRack::set_logging_level(const int & logLevel){
FILELog::ReportingLevel() = TLogLevel(logLevel);
return 0;
}
int APSRack::set_trigger_source(const int & deviceID, const TRIGGERSOURCE & triggerSource) {
return APSs_[deviceID].set_trigger_source(triggerSource);
}
TRIGGERSOURCE APSRack::get_trigger_source(const int & deviceID) const{
return APSs_[deviceID].get_trigger_source();
}
int APSRack::set_trigger_interval(const int & deviceID, const double & interval){
return APSs_[deviceID].set_trigger_interval(interval);
}
double APSRack::get_trigger_interval(const int & deviceID) const{
return APSs_[deviceID].get_trigger_interval();
}
int APSRack::set_miniLL_repeat(const int & deviceID, const USHORT & repeat){
return APSs_[deviceID].set_miniLL_repeat(repeat);
}
int APSRack::set_channel_enabled(const int & deviceID, const int & channelNum, const bool & enable){
return APSs_[deviceID].set_channel_enabled(channelNum, enable);
}
bool APSRack::get_channel_enabled(const int & deviceID, const int & channelNum) const{
return APSs_[deviceID].get_channel_enabled(channelNum);
}
int APSRack::set_channel_offset(const int & deviceID, const int & channelNum, const float & offset){
return APSs_[deviceID].set_channel_offset(channelNum, offset);
}
float APSRack::get_channel_offset(const int & deviceID, const int & channelNum) const{
return APSs_[deviceID].get_channel_offset(channelNum);
}
int APSRack::set_channel_scale(const int & deviceID, const int & channelNum, const float & scale){
return APSs_[deviceID].set_channel_scale(channelNum, scale);
}
float APSRack::get_channel_scale(const int & deviceID, const int & channelNum) const{
return APSs_[deviceID].get_channel_scale(channelNum);
}
int APSRack::save_state_files(){
// loop through available APS Units and save state
for(unsigned int apsct = 0; apsct < APSs_.size(); apsct++) {
string stateFileName = ""; // use default file name
APSs_[apsct].save_state_file(stateFileName);
}
return 0;
}
int APSRack::read_state_files(){
// loop through available APS Units and load state
for(unsigned int apsct = 0; apsct < APSs_.size(); apsct++) {
string stateFileName = ""; // use default file name
APSs_[apsct].read_state_file(stateFileName);
}
return 0;
}
int APSRack::save_bulk_state_file(string & stateFile){
if (stateFile.length() == 0) {
stateFile += "cache_APSRack.h5";
}
FILE_LOG(logDEBUG) << "Writing Bulk State File " << stateFile;
H5::H5File H5StateFile(stateFile, H5F_ACC_TRUNC);
// loop through available APS Units and save state
for(unsigned int apsct = 0; apsct < APSs_.size(); apsct++) {
string rootStr = "/";
rootStr += APSs_[apsct].deviceSerial_ ;
FILE_LOG(logDEBUG) << "Creating Group: " << rootStr;
H5::Group tmpGroup = H5StateFile.createGroup(rootStr);
tmpGroup.close();
APSs_[apsct].write_state_to_hdf5(H5StateFile, rootStr);
}
//Close the file
H5StateFile.close();
return 0;
}
int APSRack::read_bulk_state_file(string & stateFile){
if (stateFile.length() == 0) {
stateFile += "cache_APSRack.h5";
}
FILE_LOG(logDEBUG) << "Reading Bulk State File " << stateFile;
H5::H5File H5StateFile(stateFile, H5F_ACC_RDONLY);
// loop through available APS Units and load data
for(unsigned int apsct = 0; apsct < APSs_.size(); apsct++) {
string rootStr = "/";
rootStr += "/" + APSs_[apsct].deviceSerial_;
APSs_[apsct].read_state_from_hdf5(H5StateFile, rootStr);
}
//Close the file
H5StateFile.close();
return 0;
}
int APSRack::raw_write(int deviceID, int numBytes, UCHAR* data){
DWORD bytesWritten;
FT_Write(APSs_[deviceID].handle_, data, numBytes, &bytesWritten);
return int(bytesWritten);
}
int APSRack::raw_read(int deviceID, FPGASELECT fpga) {
DWORD bytesRead, bytesWritten;
UCHAR dataBuffer[2];
USHORT transferSize = 1;
int Command = APS_FPGA_IO;
//Send the read command byte
UCHAR commandPacket = 0x80 | Command | (fpga<<2) | transferSize;
FT_Write(APSs_[deviceID].handle_, &commandPacket, 1, &bytesWritten);
//Look for the data
FT_Read(APSs_[deviceID].handle_, dataBuffer, 2, &bytesRead);
FILE_LOG(logDEBUG2) << "Read " << bytesRead << " bytes with value" << myhex << ((dataBuffer[0] << 8) | dataBuffer[1]);
return int((dataBuffer[0] << 8) | dataBuffer[1]);
}
int APSRack::read_register(int deviceID, FPGASELECT fpga, int addr){
return FPGA::read_FPGA(APSs_[deviceID].handle_, addr, fpga);
}
<|endoftext|>
|
<commit_before>/*
Copyright 2011 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "GrGLConfig.h"
#include "GrGLInterface.h"
void GrGLClearErr() {
while (GR_GL_NO_ERROR != GrGLGetGLInterface()->fGetError()) {}
}
void GrGLCheckErr(const char* location, const char* call) {
uint32_t err = GrGLGetGLInterface()->fGetError();
if (GR_GL_NO_ERROR != err) {
GrPrintf("---- glGetError %x", err);
if (NULL != location) {
GrPrintf(" at\n\t%s", location);
}
if (NULL != call) {
GrPrintf("\n\t\t%s", call);
}
GrPrintf("\n");
}
}
void GrGLRestoreResetRowLength() {
if (GR_GL_SUPPORT_DESKTOP) {
GR_GL(PixelStorei(GR_GL_UNPACK_ROW_LENGTH, 0));
}
}
///////////////////////////////////////////////////////////////////////////////
bool gLogCallsGL = !!(GR_GL_LOG_CALLS_START);
bool gCheckErrorGL = !!(GR_GL_CHECK_ERROR_START);
<commit_msg>Only define debugging GL globals when the code paths are enabled<commit_after>/*
Copyright 2011 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "GrGLConfig.h"
#include "GrGLInterface.h"
void GrGLClearErr() {
while (GR_GL_NO_ERROR != GrGLGetGLInterface()->fGetError()) {}
}
void GrGLCheckErr(const char* location, const char* call) {
uint32_t err = GrGLGetGLInterface()->fGetError();
if (GR_GL_NO_ERROR != err) {
GrPrintf("---- glGetError %x", err);
if (NULL != location) {
GrPrintf(" at\n\t%s", location);
}
if (NULL != call) {
GrPrintf("\n\t\t%s", call);
}
GrPrintf("\n");
}
}
void GrGLRestoreResetRowLength() {
if (GR_GL_SUPPORT_DESKTOP) {
GR_GL(PixelStorei(GR_GL_UNPACK_ROW_LENGTH, 0));
}
}
///////////////////////////////////////////////////////////////////////////////
#if GR_GL_LOG_CALLS
bool gLogCallsGL = !!(GR_GL_LOG_CALLS_START);
#endif
#if GR_GL_CHECK_ERROR
bool gCheckErrorGL = !!(GR_GL_CHECK_ERROR_START);
#endif
<|endoftext|>
|
<commit_before>#include "unicode.h"
#include "strings.h"
#include "macros.h"
U32String DecodeUTF8(const char* _start, int byteCount){
// You know, you'd think static_cast would work. But apparently not.
const unsigned char* start = reinterpret_cast<const unsigned char*>(_start);
U32String decoded = {};
decoded.length = 0;
decoded.start = (unsigned int*)malloc(byteCount*sizeof(unsigned int));
unsigned char highBits[] = {0xC0, 0xE0, 0xF0, 0xF8, 0xFC, 0xFE};
for (int i = 0; i < byteCount; ){
if ((start[i] & 0x80) == 0){
// High bit not set, just ascii
decoded.start[decoded.length] = start[i];
decoded.length++;
i++;
}
else{
bool foundBit = false;
for (int j = 0; j < BNS_ARRAY_COUNT(highBits) - 1; j++){
if ((start[i] & highBits[j + 1]) == highBits[j]){
int codepoint = (start[i] & (~highBits[j + 1]));
for (int k = 0; k < j + 1; k++){
if ((start[i + 1 + k] & 0xC0) != 0x80){
ASSERT_WARN("Subsequent byte in UTF-8 string with improper high two bits: 0x%X", start[i + 1 + k]);
}
codepoint = (codepoint << 6) | (start[i + 1 + k] & 0x3F);
}
decoded.start[decoded.length] = codepoint;
decoded.length++;
i += (j + 2);
foundBit = true;
break;
}
}
ASSERT_MSG(foundBit, "Improper formatting on byte: 0x%X", start[i]);
}
}
return decoded;
}
int GetUTF8Size(const U32String string){
unsigned int upperLimits[] = {0x80, 0x800, 0x10000, 0x200000, 0x4000000, 0x80000000};
int byteCount = 0;
for (int i = 0; i < string.length; i++) {
bool foundLimit = false;
for (int j = 0; j < BNS_ARRAY_COUNT(upperLimits); j++) {
if (string.start[i] < upperLimits[j]) {
byteCount += (j + 1);
foundLimit = true;
break;
}
}
ASSERT_MSG(foundLimit, "Unicode codepoint %d out of range, occur at position %d.", string.start[i], i);
}
return byteCount;
}
int EncodeUTF8(const U32String inString, unsigned char* outString){
unsigned int upperLimits[] = { 0x800, 0x10000, 0x200000, 0x4000000, 0x80000000 };
unsigned char highBits[] = { 0xC0, 0xE0, 0xF0, 0xF8};
int bytesWritten = 0;
for (int i = 0; i < inString.length; i++) {
if (inString.start[i] < 0x80) {
outString[bytesWritten] = inString.start[i];
bytesWritten++;
}
else {
bool foundLimit = false;
int codepoint = inString.start[i];
for (int j = 0; j < BNS_ARRAY_COUNT(upperLimits); j++) {
if (codepoint < upperLimits[j]) {
for (int k = j + 1; k > 0; k--) {
outString[bytesWritten + k] = (codepoint & 0x3F) | 0x80;
codepoint >>= 6;
}
outString[bytesWritten] = codepoint | highBits[j];
bytesWritten += (j + 2);
foundLimit = true;
break;
}
}
ASSERT_MSG(foundLimit, "Unicode codepoint %d out of range, occur at position %d.", inString.start[i], i);
}
}
return bytesWritten;
}
int U32FindChar(const U32String string, int codepoint){
for (int i = 0; i < string.length; i++) {
if (string.start[i] == codepoint) {
return i;
}
}
return -1;
}
int U32StrFind(const U32String haystack, const U32String needle){
int hIndex = 0, nIndex = 0;
while (hIndex < haystack.length && nIndex < needle.length) {
if (haystack.start[hIndex] == needle.start[nIndex]) {
nIndex++;
}
else {
hIndex -= nIndex;
nIndex = 0;
}
hIndex++;
}
if (nIndex == needle.length) {
return hIndex - nIndex;
}
else {
return -1;
}
}
U32String U32StrDup(const U32String string){
U32String newStr;
newStr.length = string.length;
newStr.start = (unsigned int*)malloc((newStr.length + 1) * sizeof(unsigned int));
MemCpy(newStr.start, string.start, newStr.length * sizeof(unsigned int));
newStr.start[newStr.length] = 0;
return newStr;
}
// Strips out any characters outside of 0-127 ascii range
void ConvertToAscii(const U32String string, char* outAscii){
}
// Search is inclusive for both low and high (i.e. ascii search would be 0, 127)
int CountCharactersInRange(const U32String string, int codepointLow, int codepointHigh){
return -1;
}
void DeallocateU32String(U32String string){
free(string.start);
}
#if defined(UNICODE_TEST_MAIN)
#include "filesys.h"
int main(int argc, char** argv){
int fileLength = 0;
unsigned char* fileBytes = ReadBinaryFile("unicode_test.txt", &fileLength);
U32String utf32 = DecodeUTF8((char*)fileBytes, fileLength);
int reEncodeSize = GetUTF8Size(utf32);
unsigned char* reEncoded = (unsigned char*)malloc(reEncodeSize);
int bytesWritten = EncodeUTF8(utf32, reEncoded);
ASSERT(reEncodeSize == fileLength);
int diff = memcmp(fileBytes, reEncoded, reEncodeSize);
ASSERT(diff == 0);
U32String utf32dup = U32StrDup(utf32);
ASSERT(utf32dup.length == utf32.length);
int dupDiff = memcmp(utf32dup.start, utf32.start, utf32.length);
ASSERT(dupDiff == 0);
// 0x6211 is the codepoint for the chinese character 'wo3', meaning me/I
int locOfWo = U32FindChar(utf32, 0x6211);
ASSERT(locOfWo == 3);
FILE* unicodeOut = fopen("unicode__out.txt", "wb");
fwrite(reEncoded, 1, bytesWritten, unicodeOut);
fclose(unicodeOut);
DeallocateU32String(utf32dup);
DeallocateU32String(utf32);
free(fileBytes);
return 0;
}
#endif
<commit_msg>Fixing leak in unicode test.<commit_after>#include "unicode.h"
#include "strings.h"
#include "macros.h"
U32String DecodeUTF8(const char* _start, int byteCount){
// You know, you'd think static_cast would work. But apparently not.
const unsigned char* start = reinterpret_cast<const unsigned char*>(_start);
U32String decoded = {};
decoded.length = 0;
decoded.start = (unsigned int*)malloc(byteCount*sizeof(unsigned int));
unsigned char highBits[] = {0xC0, 0xE0, 0xF0, 0xF8, 0xFC, 0xFE};
for (int i = 0; i < byteCount; ){
if ((start[i] & 0x80) == 0){
// High bit not set, just ascii
decoded.start[decoded.length] = start[i];
decoded.length++;
i++;
}
else{
bool foundBit = false;
for (int j = 0; j < BNS_ARRAY_COUNT(highBits) - 1; j++){
if ((start[i] & highBits[j + 1]) == highBits[j]){
int codepoint = (start[i] & (~highBits[j + 1]));
for (int k = 0; k < j + 1; k++){
if ((start[i + 1 + k] & 0xC0) != 0x80){
ASSERT_WARN("Subsequent byte in UTF-8 string with improper high two bits: 0x%X", start[i + 1 + k]);
}
codepoint = (codepoint << 6) | (start[i + 1 + k] & 0x3F);
}
decoded.start[decoded.length] = codepoint;
decoded.length++;
i += (j + 2);
foundBit = true;
break;
}
}
ASSERT_MSG(foundBit, "Improper formatting on byte: 0x%X", start[i]);
}
}
return decoded;
}
int GetUTF8Size(const U32String string){
unsigned int upperLimits[] = {0x80, 0x800, 0x10000, 0x200000, 0x4000000, 0x80000000};
int byteCount = 0;
for (int i = 0; i < string.length; i++) {
bool foundLimit = false;
for (int j = 0; j < BNS_ARRAY_COUNT(upperLimits); j++) {
if (string.start[i] < upperLimits[j]) {
byteCount += (j + 1);
foundLimit = true;
break;
}
}
ASSERT_MSG(foundLimit, "Unicode codepoint %d out of range, occur at position %d.", string.start[i], i);
}
return byteCount;
}
int EncodeUTF8(const U32String inString, unsigned char* outString){
unsigned int upperLimits[] = { 0x800, 0x10000, 0x200000, 0x4000000, 0x80000000 };
unsigned char highBits[] = { 0xC0, 0xE0, 0xF0, 0xF8};
int bytesWritten = 0;
for (int i = 0; i < inString.length; i++) {
if (inString.start[i] < 0x80) {
outString[bytesWritten] = inString.start[i];
bytesWritten++;
}
else {
bool foundLimit = false;
int codepoint = inString.start[i];
for (int j = 0; j < BNS_ARRAY_COUNT(upperLimits); j++) {
if (codepoint < upperLimits[j]) {
for (int k = j + 1; k > 0; k--) {
outString[bytesWritten + k] = (codepoint & 0x3F) | 0x80;
codepoint >>= 6;
}
outString[bytesWritten] = codepoint | highBits[j];
bytesWritten += (j + 2);
foundLimit = true;
break;
}
}
ASSERT_MSG(foundLimit, "Unicode codepoint %d out of range, occur at position %d.", inString.start[i], i);
}
}
return bytesWritten;
}
int U32FindChar(const U32String string, int codepoint){
for (int i = 0; i < string.length; i++) {
if (string.start[i] == codepoint) {
return i;
}
}
return -1;
}
int U32StrFind(const U32String haystack, const U32String needle){
int hIndex = 0, nIndex = 0;
while (hIndex < haystack.length && nIndex < needle.length) {
if (haystack.start[hIndex] == needle.start[nIndex]) {
nIndex++;
}
else {
hIndex -= nIndex;
nIndex = 0;
}
hIndex++;
}
if (nIndex == needle.length) {
return hIndex - nIndex;
}
else {
return -1;
}
}
U32String U32StrDup(const U32String string){
U32String newStr;
newStr.length = string.length;
newStr.start = (unsigned int*)malloc((newStr.length + 1) * sizeof(unsigned int));
MemCpy(newStr.start, string.start, newStr.length * sizeof(unsigned int));
newStr.start[newStr.length] = 0;
return newStr;
}
// Strips out any characters outside of 0-127 ascii range
void ConvertToAscii(const U32String string, char* outAscii){
}
// Search is inclusive for both low and high (i.e. ascii search would be 0, 127)
int CountCharactersInRange(const U32String string, int codepointLow, int codepointHigh){
return -1;
}
void DeallocateU32String(U32String string){
free(string.start);
}
#if defined(UNICODE_TEST_MAIN)
#include "filesys.h"
int main(int argc, char** argv){
int fileLength = 0;
unsigned char* fileBytes = ReadBinaryFile("unicode_test.txt", &fileLength);
U32String utf32 = DecodeUTF8((char*)fileBytes, fileLength);
int reEncodeSize = GetUTF8Size(utf32);
unsigned char* reEncoded = (unsigned char*)malloc(reEncodeSize);
int bytesWritten = EncodeUTF8(utf32, reEncoded);
ASSERT(reEncodeSize == fileLength);
int diff = memcmp(fileBytes, reEncoded, reEncodeSize);
ASSERT(diff == 0);
U32String utf32dup = U32StrDup(utf32);
ASSERT(utf32dup.length == utf32.length);
int dupDiff = memcmp(utf32dup.start, utf32.start, utf32.length);
ASSERT(dupDiff == 0);
// 0x6211 is the codepoint for the chinese character 'wo3', meaning me/I
int locOfWo = U32FindChar(utf32, 0x6211);
ASSERT(locOfWo == 3);
FILE* unicodeOut = fopen("unicode__out.txt", "wb");
fwrite(reEncoded, 1, bytesWritten, unicodeOut);
fclose(unicodeOut);
DeallocateU32String(utf32dup);
DeallocateU32String(utf32);
free(fileBytes);
free(reEncoded);
return 0;
}
#endif
<|endoftext|>
|
<commit_before>/*
This file is part of Magnum.
Copyright © 2010, 2011, 2012, 2013, 2014, 2015, 2016
Vladimír Vondruš <[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 "WindowlessWglApplication.h"
#include <Corrade/Utility/Assert.h>
#include <Corrade/Utility/Debug.h>
#include "Magnum/Version.h"
#include "Magnum/Platform/Context.h"
namespace Magnum { namespace Platform {
#ifndef DOXYGEN_GENERATING_OUTPUT
int WindowlessWglApplication::create(LRESULT(CALLBACK windowProcedure)(HWND, UINT, WPARAM, LPARAM)) {
const WNDCLASS wc{
0,
windowProcedure,
0,
0,
GetModuleHandle(nullptr),
nullptr,
nullptr,
HBRUSH(COLOR_BACKGROUND),
nullptr,
L"Magnum Windowless Application"
};
if(!RegisterClass(&wc)) return 1;
CreateWindowW(wc.lpszClassName, L"Magnum Windowless Application",
WS_OVERLAPPEDWINDOW, 0, 0, 32, 32, 0, 0, wc.hInstance, 0);
/* Hammer the return code out of the messaging thingy */
MSG msg;
do {} while(GetMessageW(&msg, nullptr, 0, 0) != 0);
return msg.wParam;
}
#endif
#ifndef DOXYGEN_GENERATING_OUTPUT
WindowlessWglApplication::WindowlessWglApplication(const Arguments& arguments): WindowlessWglApplication{arguments, Configuration{}} {}
#endif
WindowlessWglApplication::WindowlessWglApplication(const Arguments& arguments, const Configuration& configuration): WindowlessWglApplication{arguments, nullptr} {
createContext(configuration);
}
WindowlessWglApplication::WindowlessWglApplication(const Arguments& arguments, std::nullptr_t): _window(arguments.window), _context{new Context{NoCreate, arguments.argc, arguments.argv}} {}
void WindowlessWglApplication::createContext() { createContext({}); }
void WindowlessWglApplication::createContext(const Configuration& configuration) {
if(!tryCreateContext(configuration)) std::exit(1);
}
bool WindowlessWglApplication::tryCreateContext(const Configuration& configuration) {
CORRADE_ASSERT(_context->version() == Version::None, "Platform::WindowlessWglApplication::tryCreateContext(): context already created", false);
/* Get device context */
_deviceContext = GetDC(_window);
/* Use first provided pixel format */
constexpr static const PIXELFORMATDESCRIPTOR pfd = {
sizeof(PIXELFORMATDESCRIPTOR),
1,
/* Double-buffered with OpenGL support */
PFD_DRAW_TO_WINDOW|PFD_SUPPORT_OPENGL|PFD_DOUBLEBUFFER,
PFD_TYPE_RGBA, /* RGBA */
32, /* 32 bit */
0, 0, 0, 0, 0, 0,
0,
0,
0,
0, 0, 0, 0,
24, /* 24-bit depth buffer */
8, /* 8-bit stencil buffer */
0,
PFD_MAIN_PLANE,
0,
0, 0, 0
};
const int pixelFormat = ChoosePixelFormat(_deviceContext, &pfd);
SetPixelFormat(_deviceContext, pixelFormat, &pfd);
const int attributes[] = {
WGL_CONTEXT_FLAGS_ARB, int(configuration.flags()),
0
};
/* Create temporary context so we are able to get the pointer to
wglCreateContextAttribsARB() */
HGLRC temporaryContext = wglCreateContext(_deviceContext);
if(!wglMakeCurrent(_deviceContext, temporaryContext)) {
Error() << "Platform::WindowlessWglApplication::tryCreateContext(): cannot make temporary context current:" << GetLastError();
return false;
}
/* Get pointer to proper context creation function and create real context
with it */
typedef HGLRC(WINAPI*PFNWGLCREATECONTEXTATTRIBSARBPROC)(HDC, HGLRC, const int*);
const PFNWGLCREATECONTEXTATTRIBSARBPROC wglCreateContextAttribsARB = reinterpret_cast<PFNWGLCREATECONTEXTATTRIBSARBPROC>( wglGetProcAddress(reinterpret_cast<LPCSTR>("wglCreateContextAttribsARB")));
_renderingContext = wglCreateContextAttribsARB(_deviceContext, 0, attributes);
/* Delete the temporary context */
wglMakeCurrent(_deviceContext, nullptr);
wglDeleteContext(temporaryContext);
if(!_renderingContext) {
Error() << "Platform::WindowlessWglApplication::tryCreateContext(): cannot create context:" << GetLastError();
return false;
}
/* Set OpenGL context as current */
if(!wglMakeCurrent(_deviceContext, _renderingContext)) {
Error() << "Platform::WindowlessWglApplication::tryCreateContext(): cannot make context current:" << GetLastError();
return false;
}
/* Return true if the initialization succeeds */
return _context->tryCreate();
}
WindowlessWglApplication::~WindowlessWglApplication() {
_context.reset();
wglMakeCurrent(_deviceContext, nullptr);
wglDeleteContext(_renderingContext);
}
}}
<commit_msg>Fix 'zero as null pointer constant' warning<commit_after>/*
This file is part of Magnum.
Copyright © 2010, 2011, 2012, 2013, 2014, 2015, 2016
Vladimír Vondruš <[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 "WindowlessWglApplication.h"
#include <Corrade/Utility/Assert.h>
#include <Corrade/Utility/Debug.h>
#include "Magnum/Version.h"
#include "Magnum/Platform/Context.h"
namespace Magnum { namespace Platform {
#ifndef DOXYGEN_GENERATING_OUTPUT
int WindowlessWglApplication::create(LRESULT(CALLBACK windowProcedure)(HWND, UINT, WPARAM, LPARAM)) {
const WNDCLASS wc{
0,
windowProcedure,
0,
0,
GetModuleHandle(nullptr),
nullptr,
nullptr,
HBRUSH(COLOR_BACKGROUND),
nullptr,
L"Magnum Windowless Application"
};
if(!RegisterClass(&wc)) return 1;
CreateWindowW(wc.lpszClassName, L"Magnum Windowless Application",
WS_OVERLAPPEDWINDOW, 0, 0, 32, 32, 0, 0, wc.hInstance, 0);
/* Hammer the return code out of the messaging thingy */
MSG msg;
do {} while(GetMessageW(&msg, nullptr, 0, 0) != 0);
return msg.wParam;
}
#endif
#ifndef DOXYGEN_GENERATING_OUTPUT
WindowlessWglApplication::WindowlessWglApplication(const Arguments& arguments): WindowlessWglApplication{arguments, Configuration{}} {}
#endif
WindowlessWglApplication::WindowlessWglApplication(const Arguments& arguments, const Configuration& configuration): WindowlessWglApplication{arguments, nullptr} {
createContext(configuration);
}
WindowlessWglApplication::WindowlessWglApplication(const Arguments& arguments, std::nullptr_t): _window(arguments.window), _context{new Context{NoCreate, arguments.argc, arguments.argv}} {}
void WindowlessWglApplication::createContext() { createContext({}); }
void WindowlessWglApplication::createContext(const Configuration& configuration) {
if(!tryCreateContext(configuration)) std::exit(1);
}
bool WindowlessWglApplication::tryCreateContext(const Configuration& configuration) {
CORRADE_ASSERT(_context->version() == Version::None, "Platform::WindowlessWglApplication::tryCreateContext(): context already created", false);
/* Get device context */
_deviceContext = GetDC(_window);
/* Use first provided pixel format */
constexpr static const PIXELFORMATDESCRIPTOR pfd = {
sizeof(PIXELFORMATDESCRIPTOR),
1,
/* Double-buffered with OpenGL support */
PFD_DRAW_TO_WINDOW|PFD_SUPPORT_OPENGL|PFD_DOUBLEBUFFER,
PFD_TYPE_RGBA, /* RGBA */
32, /* 32 bit */
0, 0, 0, 0, 0, 0,
0,
0,
0,
0, 0, 0, 0,
24, /* 24-bit depth buffer */
8, /* 8-bit stencil buffer */
0,
PFD_MAIN_PLANE,
0,
0, 0, 0
};
const int pixelFormat = ChoosePixelFormat(_deviceContext, &pfd);
SetPixelFormat(_deviceContext, pixelFormat, &pfd);
const int attributes[] = {
WGL_CONTEXT_FLAGS_ARB, int(configuration.flags()),
0
};
/* Create temporary context so we are able to get the pointer to
wglCreateContextAttribsARB() */
HGLRC temporaryContext = wglCreateContext(_deviceContext);
if(!wglMakeCurrent(_deviceContext, temporaryContext)) {
Error() << "Platform::WindowlessWglApplication::tryCreateContext(): cannot make temporary context current:" << GetLastError();
return false;
}
/* Get pointer to proper context creation function and create real context
with it */
typedef HGLRC(WINAPI*PFNWGLCREATECONTEXTATTRIBSARBPROC)(HDC, HGLRC, const int*);
const PFNWGLCREATECONTEXTATTRIBSARBPROC wglCreateContextAttribsARB = reinterpret_cast<PFNWGLCREATECONTEXTATTRIBSARBPROC>( wglGetProcAddress(reinterpret_cast<LPCSTR>("wglCreateContextAttribsARB")));
_renderingContext = wglCreateContextAttribsARB(_deviceContext, nullptr, attributes);
/* Delete the temporary context */
wglMakeCurrent(_deviceContext, nullptr);
wglDeleteContext(temporaryContext);
if(!_renderingContext) {
Error() << "Platform::WindowlessWglApplication::tryCreateContext(): cannot create context:" << GetLastError();
return false;
}
/* Set OpenGL context as current */
if(!wglMakeCurrent(_deviceContext, _renderingContext)) {
Error() << "Platform::WindowlessWglApplication::tryCreateContext(): cannot make context current:" << GetLastError();
return false;
}
/* Return true if the initialization succeeds */
return _context->tryCreate();
}
WindowlessWglApplication::~WindowlessWglApplication() {
_context.reset();
wglMakeCurrent(_deviceContext, nullptr);
wglDeleteContext(_renderingContext);
}
}}
<|endoftext|>
|
<commit_before>#include <MainApplication/Viewer/Gizmo/RotateGizmo.hpp>
#include <Core/Math/RayCast.hpp>
#include <Core/Math/ColorPresets.hpp>
#include <Core/Containers/VectorArray.hpp>
#include <Core/Mesh/MeshUtils.hpp>
#include <Engine/RadiumEngine.hpp>
#include <Engine/Renderer/Camera/Camera.hpp>
#include <Engine/Renderer/RenderTechnique/RenderTechnique.hpp>
#include <Engine/Renderer/Mesh/Mesh.hpp>
namespace Ra
{
namespace Gui
{
RotateGizmo::RotateGizmo(Engine::Component* c, const Core::Transform& t, Mode mode)
: Gizmo(c, t, mode), m_initialPix(Core::Vector2::Zero()), m_selectedAxis(-1)
{
constexpr Scalar tubeHeight = 0.001f;
constexpr Scalar tubeOutRadius = 0.1f;
constexpr Scalar tubeInRadius = 0.9f * tubeOutRadius;
// For x,y,z
for (uint i = 0; i < 3; ++i)
{
const Core::Vector3 tubeAxis = Core::Vector3::Unit(i);
Core::TriangleMesh tube = Core::MeshUtils::makeTube(-tubeHeight*tubeAxis, tubeHeight*tubeAxis, tubeOutRadius, tubeInRadius);
Core::Color tubeColor= Core::Color::Zero();
tubeColor[i] = 1.f;
Core::Vector4Array colors(tube.m_vertices.size(), tubeColor);
Engine::Mesh* mesh = new Engine::Mesh("Gizmo Arrow");
mesh->loadGeometry(tube);
mesh->addData(Engine::Mesh::VERTEX_COLOR, colors);
Engine::RenderObject* arrowDrawable = new Engine::RenderObject("Gizmo Arrow", m_comp, true);
Engine::RenderTechnique* rt = new Engine::RenderTechnique;
rt->shaderConfig = Ra::Engine::ShaderConfiguration("Plain", "../Shaders");
rt->material = new Ra::Engine::Material("Default material");
arrowDrawable->setRenderTechnique(rt);
arrowDrawable->setType(Engine::RenderObject::Type::RO_UI);
arrowDrawable->setMesh(mesh);
updateTransform(m_transform);
m_renderObjects.push_back(m_comp->addRenderObject(arrowDrawable));
}
}
void RotateGizmo::updateTransform(const Core::Transform& t)
{
m_transform = t;
Core::Transform displayTransform = Core::Transform::Identity();
if (m_mode == LOCAL)
{
displayTransform = m_transform;
}
else
{
displayTransform.translate(m_transform.translation());
}
for (auto roIdx : m_renderObjects)
{
Engine::RadiumEngine::getInstance()->getRenderObjectManager()->getRenderObject(
roIdx)->setLocalTransform(displayTransform);
}
}
void RotateGizmo::selectConstraint(int drawableIdx)
{
m_selectedAxis = -1;
if (drawableIdx >= 0)
{
auto found = std::find(m_renderObjects.cbegin(), m_renderObjects.cend(), Core::Index(drawableIdx));
if (found != m_renderObjects.cend())
{
m_selectedAxis = int(found - m_renderObjects.begin());
}
}
}
Core::Transform RotateGizmo::mouseMove(const Engine::Camera& cam, const Core::Vector2& nextXY)
{
if (m_selectedAxis >= 0)
{
const Core::Vector3 origin = m_transform.translation();
Core::Vector3 rotationAxis = Core::Vector3::Unit(m_selectedAxis);
if (m_mode == LOCAL)
{
rotationAxis = m_transform.rotation()*rotationAxis;
}
// Project the clicked points against the plane defined by the rotation circles.
std::vector<Scalar> hits1, hits2;
Core::Ray rayToFirstClick = cam.getRayFromScreen(m_initialPix);
Core::Ray rayToCurrentClick = cam.getRayFromScreen(nextXY);
bool hit1 = Core::RayCast::vsPlane(rayToFirstClick, origin, rotationAxis, hits1);
bool hit2 = Core::RayCast::vsPlane(rayToCurrentClick, origin, rotationAxis, hits2);
if (hit1 && hit2)
{
// Do the calculations relative to the circle center.
const Core::Vector3 originalHit = rayToFirstClick.at(hits1[0]) - origin;
const Core::Vector3 currentHit = rayToCurrentClick.at(hits2[0]) - origin;
// Get the angle between the two vectors with the correct sign
// (since we already know our current rotation axis).
auto c = originalHit.cross(currentHit);
Scalar d = originalHit.dot(currentHit);
Scalar angle = Core::Math::sign(c.dot(rotationAxis)) * std::atan2(c.norm(),d);
// Apply rotation.
auto newRot = Core::AngleAxis(angle, rotationAxis) * m_transform.rotation();
m_transform.fromPositionOrientationScale(origin, newRot, Core::Vector3::Ones());
}
m_initialPix = nextXY;
}
return m_transform;
}
void RotateGizmo::setInitialState(const Engine::Camera& cam, const Core::Vector2& initialXY)
{
m_initialPix = initialXY;
}
}
}
<commit_msg>Torus shape for rotation gizmo (#46)<commit_after>#include <MainApplication/Viewer/Gizmo/RotateGizmo.hpp>
#include <Core/Math/RayCast.hpp>
#include <Core/Math/ColorPresets.hpp>
#include <Core/Containers/VectorArray.hpp>
#include <Core/Mesh/MeshUtils.hpp>
#include <Engine/RadiumEngine.hpp>
#include <Engine/Renderer/Camera/Camera.hpp>
#include <Engine/Renderer/RenderTechnique/RenderTechnique.hpp>
#include <Engine/Renderer/Mesh/Mesh.hpp>
namespace Ra
{
namespace Gui
{
RotateGizmo::RotateGizmo(Engine::Component* c, const Core::Transform& t, Mode mode)
: Gizmo(c, t, mode), m_initialPix(Core::Vector2::Zero()), m_selectedAxis(-1)
{
constexpr Scalar torusOutRadius = 0.1f;
constexpr Scalar torusAspectRatio = 0.1f;
// For x,y,z
for (uint i = 0; i < 3; ++i)
{
Core::TriangleMesh torus = Core::MeshUtils::makeParametricTorus<32>(torusOutRadius, torusAspectRatio*torusOutRadius);
// Transform the torus from z-axis to axis i.
if (i < 2)
{
for (auto& v: torus.m_vertices)
{
std::swap( v[2], v[i]);
}
}
Core::Color torusColor= Core::Color::Zero();
torusColor[i] = 1.f;
Core::Vector4Array colors(torus.m_vertices.size(), torusColor);
Engine::Mesh* mesh = new Engine::Mesh("Gizmo Arrow");
mesh->loadGeometry(torus);
mesh->addData(Engine::Mesh::VERTEX_COLOR, colors);
Engine::RenderObject* arrowDrawable = new Engine::RenderObject("Gizmo Arrow", m_comp, true);
Engine::RenderTechnique* rt = new Engine::RenderTechnique;
rt->shaderConfig = Ra::Engine::ShaderConfiguration("Plain", "../Shaders");
rt->material = new Ra::Engine::Material("Default material");
arrowDrawable->setRenderTechnique(rt);
arrowDrawable->setType(Engine::RenderObject::Type::RO_UI);
arrowDrawable->setMesh(mesh);
updateTransform(m_transform);
m_renderObjects.push_back(m_comp->addRenderObject(arrowDrawable));
}
}
void RotateGizmo::updateTransform(const Core::Transform& t)
{
m_transform = t;
Core::Transform displayTransform = Core::Transform::Identity();
if (m_mode == LOCAL)
{
displayTransform = m_transform;
}
else
{
displayTransform.translate(m_transform.translation());
}
for (auto roIdx : m_renderObjects)
{
Engine::RadiumEngine::getInstance()->getRenderObjectManager()->getRenderObject(
roIdx)->setLocalTransform(displayTransform);
}
}
void RotateGizmo::selectConstraint(int drawableIdx)
{
m_selectedAxis = -1;
if (drawableIdx >= 0)
{
auto found = std::find(m_renderObjects.cbegin(), m_renderObjects.cend(), Core::Index(drawableIdx));
if (found != m_renderObjects.cend())
{
m_selectedAxis = int(found - m_renderObjects.begin());
}
}
}
Core::Transform RotateGizmo::mouseMove(const Engine::Camera& cam, const Core::Vector2& nextXY)
{
if (m_selectedAxis >= 0)
{
const Core::Vector3 origin = m_transform.translation();
Core::Vector3 rotationAxis = Core::Vector3::Unit(m_selectedAxis);
if (m_mode == LOCAL)
{
rotationAxis = m_transform.rotation()*rotationAxis;
}
// Project the clicked points against the plane defined by the rotation circles.
std::vector<Scalar> hits1, hits2;
Core::Ray rayToFirstClick = cam.getRayFromScreen(m_initialPix);
Core::Ray rayToCurrentClick = cam.getRayFromScreen(nextXY);
bool hit1 = Core::RayCast::vsPlane(rayToFirstClick, origin, rotationAxis, hits1);
bool hit2 = Core::RayCast::vsPlane(rayToCurrentClick, origin, rotationAxis, hits2);
if (hit1 && hit2)
{
// Do the calculations relative to the circle center.
const Core::Vector3 originalHit = rayToFirstClick.at(hits1[0]) - origin;
const Core::Vector3 currentHit = rayToCurrentClick.at(hits2[0]) - origin;
// Get the angle between the two vectors with the correct sign
// (since we already know our current rotation axis).
auto c = originalHit.cross(currentHit);
Scalar d = originalHit.dot(currentHit);
Scalar angle = Core::Math::sign(c.dot(rotationAxis)) * std::atan2(c.norm(),d);
// Apply rotation.
auto newRot = Core::AngleAxis(angle, rotationAxis) * m_transform.rotation();
m_transform.fromPositionOrientationScale(origin, newRot, Core::Vector3::Ones());
}
m_initialPix = nextXY;
}
return m_transform;
}
void RotateGizmo::setInitialState(const Engine::Camera& cam, const Core::Vector2& initialXY)
{
m_initialPix = initialXY;
}
}
}
<|endoftext|>
|
<commit_before>/*
License
Menge
Copyright and trademark 2012-14 University of North Carolina at Chapel Hill.
All rights reserved.
Permission to use, copy, modify, and distribute this software and its documentation
for educational, research, and non-profit purposes, without fee, and without a
written agreement is hereby granted, provided that the above copyright notice,
this paragraph, and the following four paragraphs appear in all copies.
This software program and documentation are copyrighted by the University of North
Carolina at Chapel Hill. The software program and documentation are supplied "as is,"
without any accompanying services from the University of North Carolina at Chapel
Hill or the authors. The University of North Carolina at Chapel Hill and the
authors do not warrant that the operation of the program will be uninterrupted
or error-free. The end-user understands that the program was developed for research
purposes and is advised not to rely exclusively on the program for any reason.
IN NO EVENT SHALL THE UNIVERSITY OF NORTH CAROLINA AT CHAPEL HILL OR THE AUTHORS
BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS
DOCUMENTATION, EVEN IF THE UNIVERSITY OF NORTH CAROLINA AT CHAPEL HILL OR THE
AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
THE UNIVERSITY OF NORTH CAROLINA AT CHAPEL HILL AND THE AUTHORS SPECIFICALLY
DISCLAIM ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE AND ANY STATUTORY WARRANTY
OF NON-INFRINGEMENT. THE SOFTWARE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND
THE UNIVERSITY OF NORTH CAROLINA AT CHAPEL HILL AND THE AUTHORS HAVE NO OBLIGATIONS
TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
Any questions or comments should be sent to the authors {menge,geom}@cs.unc.edu
*/
#include "SimulatorDBEntry.h"
// Menge Runtime
#include "SimSystem.h"
#include "BaseAgentContext.h"
#include "Logger.h"
// Agents
#include "AgentInitializer.h"
#include "SimulatorInterface.h"
// BFSM
#include "FSMDescrip.h"
#include "FSM.h"
// SceneGraph
#include "GLScene.h"
#include "MengeException.h"
namespace Menge {
/////////////////////////////////////////////////////////////////////////////
// Implementation of SimulatorDBEntry
////////////////////////////////////////////////////////////////////////////
SimSystem * SimulatorDBEntry::createSimSystem( bool visualize, float duration ) {
return new SimSystem( visualize, duration );
}
////////////////////////////////////////////////////////////////////////////
Agents::SimulatorInterface * SimulatorDBEntry::initSimulator( const std::string & sceneFileName, bool VERBOSE ) {
Agents::SimulatorInterface * sim = getNewSimulator();
Agents::AgentInitializer * agentInit = getAgentInitalizer();
Agents::SimXMLLoader loader( sim );
logger.line();
if ( ! loader.loadFromXML( sceneFileName, agentInit, VERBOSE ) ) {
logger << Logger::ERR_MSG << "Couldn't initialize scene from xml.";
return 0x0;
}
return sim;
}
////////////////////////////////////////////////////////////////////////////
BFSM::FSM * SimulatorDBEntry::initFSM( const std::string & behaveFile, Agents::SimulatorInterface * sim, bool VERBOSE ) {
logger.line();
BFSM::FSMDescrip fsmDescrip;
if ( ! fsmDescrip.loadFromXML( behaveFile, VERBOSE ) ) {
logger << Logger::ERR_MSG << "Problems loading behavior specification!";
return 0x0;
}
if ( VERBOSE ) logger << fsmDescrip << "\n";
BFSM::FSM * fsm = BFSM::buildFSM( fsmDescrip, sim, VERBOSE );
if ( !fsm ) {
logger << Logger::ERR_MSG << "Error instantiating FSM from description.";
}
return fsm;
}
////////////////////////////////////////////////////////////////////////////
bool SimulatorDBEntry::finalize( Agents::SimulatorInterface * sim, BFSM::FSM * fsm ) {
// older versions of OpenMP require signed for loop counters
int agtCount = (int)sim->getNumAgents();
#pragma omp parallel for
for ( int a = 0; a < agtCount; ++a ) {
Agents::BaseAgent * agt = sim->getAgent( a );
fsm->computePrefVelocity( agt );
}
try {
sim->finalize();
} catch ( Menge::MengeException & e ) {
logger << Logger::ERR_MSG << "Problem in finalizing the simulator.\n";
logger << "\t" << e.what() ;
delete fsm;
return false;
}
try {
fsm->finalize();
} catch ( Menge::MengeFatalException & e ) {
logger << Logger::ERR_MSG << "Fatal error finalizing the finite state machine!\n";
logger << "\t" << e.what();
delete fsm;
return false;
} catch ( Menge::MengeException & e ) {
logger << Logger::WARN_MSG << "There were non-fatal errors in finalizing the finite state machine!\n";
logger << "\t" << e.what();
}
return true;
}
////////////////////////////////////////////////////////////////////////////
SimSystem * SimulatorDBEntry::getSimulatorSystem( size_t & agentCount,
float & simTimeStep,
size_t subSteps,
float simDuration,
const std::string & behaveFile,
const std::string & sceneFile,
const std::string & outFile,
const std::string & scbVersion,
bool visualize,
bool VERBOSE )
{
_sim = initSimulator( sceneFile, VERBOSE );
if ( !_sim ) {
return 0x0;
}
// TODO: Remove time step from the simulator specification!
float specTimeStep = _sim->getTimeStep();
_fsm = initFSM( behaveFile, _sim, VERBOSE );
if ( !_fsm ) {
return 0x0;
}
if ( !finalize( _sim, _fsm ) ) {
return 0x0;
}
if ( simTimeStep > 0.f ) {
if ( VERBOSE ) {
logger << Logger::INFO_MSG << "Simulation time step set by command-line argument: " << simTimeStep << ".";
}
_sim->setTimeStep( simTimeStep );
} else {
simTimeStep = specTimeStep;
if ( VERBOSE ) {
logger << Logger::INFO_MSG << "Simulation time step set by specification file: " << specTimeStep << ".";
}
}
_sim->setSubSteps( subSteps );
float effTimeStep = simTimeStep / ( 1.f + subSteps );
logger << Logger::INFO_MSG << "For logical time step: " << simTimeStep << " and " << subSteps << " sub step";
if ( subSteps !=1 ) {
logger << "s";
}
logger << ", effective time step is: " << effTimeStep;
SimSystem * system = createSimSystem( visualize, simDuration );
try {
if ( outFile != "" ) {
system->setSimulator( _sim, _fsm, outFile, scbVersion );
} else {
system->setSimulator( _sim, _fsm );
}
} catch ( SimSystemFatalException & e ) {
logger << Logger::ERR_MSG << e.what();
delete system;
delete _fsm;
delete _sim;
_sim = 0x0;
return 0x0;
}
agentCount = _sim->getNumAgents();
return system;
}
////////////////////////////////////////////////////////////////////////////
void SimulatorDBEntry::populateScene( SimSystem * system, SceneGraph::GLScene * scene ) {
system->populateScene( scene );
}
////////////////////////////////////////////////////////////////////////////
BaseAgentContext * SimulatorDBEntry::getAgentContext( SimSystem * simSystem ) {
BaseAgentContext * ctx = contextFromSystem( simSystem );
if ( ctx ) ctx->setFSMContext( _fsm->getContext() );
return ctx;
}
////////////////////////////////////////////////////////////////////////////
float SimulatorDBEntry::simDuration() const {
return _sim != 0x0 ? _sim->getGlobalTime() : -1.f;
}
////////////////////////////////////////////////////////////////////////////
BaseAgentContext * SimulatorDBEntry::contextFromSystem( SimSystem * simSystem ) {
return new BaseAgentContext( simSystem->getVisAgents(), simSystem->getAgentCount() );
}
////////////////////////////////////////////////////////////////////////////
Agents::AgentInitializer * SimulatorDBEntry::getAgentInitalizer() const {
return new Agents::AgentInitializer();
}
} // namespace Menge<commit_msg>Initializing simulator spec handles fatal exceptions gracefully<commit_after>/*
License
Menge
Copyright and trademark 2012-14 University of North Carolina at Chapel Hill.
All rights reserved.
Permission to use, copy, modify, and distribute this software and its documentation
for educational, research, and non-profit purposes, without fee, and without a
written agreement is hereby granted, provided that the above copyright notice,
this paragraph, and the following four paragraphs appear in all copies.
This software program and documentation are copyrighted by the University of North
Carolina at Chapel Hill. The software program and documentation are supplied "as is,"
without any accompanying services from the University of North Carolina at Chapel
Hill or the authors. The University of North Carolina at Chapel Hill and the
authors do not warrant that the operation of the program will be uninterrupted
or error-free. The end-user understands that the program was developed for research
purposes and is advised not to rely exclusively on the program for any reason.
IN NO EVENT SHALL THE UNIVERSITY OF NORTH CAROLINA AT CHAPEL HILL OR THE AUTHORS
BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS
DOCUMENTATION, EVEN IF THE UNIVERSITY OF NORTH CAROLINA AT CHAPEL HILL OR THE
AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
THE UNIVERSITY OF NORTH CAROLINA AT CHAPEL HILL AND THE AUTHORS SPECIFICALLY
DISCLAIM ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE AND ANY STATUTORY WARRANTY
OF NON-INFRINGEMENT. THE SOFTWARE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND
THE UNIVERSITY OF NORTH CAROLINA AT CHAPEL HILL AND THE AUTHORS HAVE NO OBLIGATIONS
TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
Any questions or comments should be sent to the authors {menge,geom}@cs.unc.edu
*/
#include "SimulatorDBEntry.h"
// Menge Runtime
#include "SimSystem.h"
#include "BaseAgentContext.h"
#include "Logger.h"
// Agents
#include "AgentInitializer.h"
#include "SimulatorInterface.h"
// BFSM
#include "FSMDescrip.h"
#include "FSM.h"
// SceneGraph
#include "GLScene.h"
#include "MengeException.h"
namespace Menge {
/////////////////////////////////////////////////////////////////////////////
// Implementation of SimulatorDBEntry
////////////////////////////////////////////////////////////////////////////
SimSystem * SimulatorDBEntry::createSimSystem( bool visualize, float duration ) {
return new SimSystem( visualize, duration );
}
////////////////////////////////////////////////////////////////////////////
Agents::SimulatorInterface * SimulatorDBEntry::initSimulator( const std::string & sceneFileName, bool VERBOSE ) {
Agents::SimulatorInterface * sim = getNewSimulator();
Agents::AgentInitializer * agentInit = getAgentInitalizer();
Agents::SimXMLLoader loader( sim );
logger.line();
try {
if (!loader.loadFromXML(sceneFileName, agentInit, VERBOSE)) {
logger << Logger::ERR_MSG << "Couldn't initialize scene from xml.";
return 0x0;
}
}
catch (MengeFatalException e) {
logger << Logger::ERR_MSG << e._msg;
return 0x0;
}
return sim;
}
////////////////////////////////////////////////////////////////////////////
BFSM::FSM * SimulatorDBEntry::initFSM( const std::string & behaveFile, Agents::SimulatorInterface * sim, bool VERBOSE ) {
logger.line();
BFSM::FSMDescrip fsmDescrip;
if ( ! fsmDescrip.loadFromXML( behaveFile, VERBOSE ) ) {
logger << Logger::ERR_MSG << "Problems loading behavior specification!";
return 0x0;
}
if ( VERBOSE ) logger << fsmDescrip << "\n";
BFSM::FSM * fsm = BFSM::buildFSM( fsmDescrip, sim, VERBOSE );
if ( !fsm ) {
logger << Logger::ERR_MSG << "Error instantiating FSM from description.";
}
return fsm;
}
////////////////////////////////////////////////////////////////////////////
bool SimulatorDBEntry::finalize( Agents::SimulatorInterface * sim, BFSM::FSM * fsm ) {
// older versions of OpenMP require signed for loop counters
int agtCount = (int)sim->getNumAgents();
#pragma omp parallel for
for ( int a = 0; a < agtCount; ++a ) {
Agents::BaseAgent * agt = sim->getAgent( a );
fsm->computePrefVelocity( agt );
}
try {
sim->finalize();
} catch ( Menge::MengeException & e ) {
logger << Logger::ERR_MSG << "Problem in finalizing the simulator.\n";
logger << "\t" << e.what() ;
delete fsm;
return false;
}
try {
fsm->finalize();
} catch ( Menge::MengeFatalException & e ) {
logger << Logger::ERR_MSG << "Fatal error finalizing the finite state machine!\n";
logger << "\t" << e.what();
delete fsm;
return false;
} catch ( Menge::MengeException & e ) {
logger << Logger::WARN_MSG << "There were non-fatal errors in finalizing the finite state machine!\n";
logger << "\t" << e.what();
}
return true;
}
////////////////////////////////////////////////////////////////////////////
SimSystem * SimulatorDBEntry::getSimulatorSystem( size_t & agentCount,
float & simTimeStep,
size_t subSteps,
float simDuration,
const std::string & behaveFile,
const std::string & sceneFile,
const std::string & outFile,
const std::string & scbVersion,
bool visualize,
bool VERBOSE )
{
_sim = initSimulator( sceneFile, VERBOSE );
if ( !_sim ) {
return 0x0;
}
// TODO: Remove time step from the simulator specification!
float specTimeStep = _sim->getTimeStep();
_fsm = initFSM( behaveFile, _sim, VERBOSE );
if ( !_fsm ) {
return 0x0;
}
if ( !finalize( _sim, _fsm ) ) {
return 0x0;
}
if ( simTimeStep > 0.f ) {
if ( VERBOSE ) {
logger << Logger::INFO_MSG << "Simulation time step set by command-line argument: " << simTimeStep << ".";
}
_sim->setTimeStep( simTimeStep );
} else {
simTimeStep = specTimeStep;
if ( VERBOSE ) {
logger << Logger::INFO_MSG << "Simulation time step set by specification file: " << specTimeStep << ".";
}
}
_sim->setSubSteps( subSteps );
float effTimeStep = simTimeStep / ( 1.f + subSteps );
logger << Logger::INFO_MSG << "For logical time step: " << simTimeStep << " and " << subSteps << " sub step";
if ( subSteps !=1 ) {
logger << "s";
}
logger << ", effective time step is: " << effTimeStep;
SimSystem * system = createSimSystem( visualize, simDuration );
try {
if ( outFile != "" ) {
system->setSimulator( _sim, _fsm, outFile, scbVersion );
} else {
system->setSimulator( _sim, _fsm );
}
} catch ( SimSystemFatalException & e ) {
logger << Logger::ERR_MSG << e.what();
delete system;
delete _fsm;
delete _sim;
_sim = 0x0;
return 0x0;
}
agentCount = _sim->getNumAgents();
return system;
}
////////////////////////////////////////////////////////////////////////////
void SimulatorDBEntry::populateScene( SimSystem * system, SceneGraph::GLScene * scene ) {
system->populateScene( scene );
}
////////////////////////////////////////////////////////////////////////////
BaseAgentContext * SimulatorDBEntry::getAgentContext( SimSystem * simSystem ) {
BaseAgentContext * ctx = contextFromSystem( simSystem );
if ( ctx ) ctx->setFSMContext( _fsm->getContext() );
return ctx;
}
////////////////////////////////////////////////////////////////////////////
float SimulatorDBEntry::simDuration() const {
return _sim != 0x0 ? _sim->getGlobalTime() : -1.f;
}
////////////////////////////////////////////////////////////////////////////
BaseAgentContext * SimulatorDBEntry::contextFromSystem( SimSystem * simSystem ) {
return new BaseAgentContext( simSystem->getVisAgents(), simSystem->getAgentCount() );
}
////////////////////////////////////////////////////////////////////////////
Agents::AgentInitializer * SimulatorDBEntry::getAgentInitalizer() const {
return new Agents::AgentInitializer();
}
} // namespace Menge<|endoftext|>
|
<commit_before>#ifndef ITER_PERMUTATIONS_HPP_
#define ITER_PERMUTATIONS_HPP_
#include "iterbase.hpp"
#include "iteratoriterator.hpp"
#include <algorithm>
#include <initializer_list>
#include <vector>
#include <utility>
#include <iterator>
namespace iter {
template <typename Container>
class Permuter {
private:
Container container;
using IndexVector = std::vector<iterator_type<Container>>;
using Permutable = IterIterWrapper<IndexVector>;
public:
Permuter(Container&& in_container)
: container(std::forward<Container>(in_container))
{ }
class Iterator
: public std::iterator<std::input_iterator_tag, Permutable>
{
private:
static constexpr const int COMPLETE = -1;
static bool cmp_iters(
const iterator_type<Container>& lhs,
const iterator_type<Container>& rhs) noexcept {
return *lhs < *rhs;
}
Permutable working_set;
int steps{};
public:
Iterator(iterator_type<Container>&& sub_iter,
iterator_type<Container>&& sub_end)
: steps{ sub_iter != sub_end ? 0 : COMPLETE }
{
// done like this instead of using vector ctor with
// two iterators because that causes a substitution
// failure when the iterator is minimal
while (sub_iter != sub_end) {
this->working_set.get().push_back(sub_iter);
++sub_iter;
}
std::sort(std::begin(working_set.get()),
std::end(working_set.get()),
cmp_iters);
}
Permutable& operator*() {
return working_set;
}
Iterator& operator++() {
++this->steps;
if (!std::next_permutation(std::begin(working_set.get()),
std::end(working_set.get()), cmp_iters)) {
this->steps = COMPLETE;
}
return *this;
}
Iterator operator++(int) {
auto ret = *this;
++*this;
return ret;
}
bool operator!=(const Iterator& other) const {
return !(*this == other);
}
bool operator==(const Iterator& other) const {
return this->steps == other.steps;
}
};
Iterator begin() {
return {std::begin(this->container),
std::end(this->container)};
}
Iterator end() {
return {std::end(this->container),
std::end(this->container)};
}
};
template <typename Container>
Permuter<Container> permutations(Container&& container) {
return {std::forward<Container>(container)};
}
template <typename T>
Permuter<std::initializer_list<T>> permutations(
std::initializer_list<T> il) {
return {std::move(il)};
}
}
#endif
<commit_msg>adds permutations iter -><commit_after>#ifndef ITER_PERMUTATIONS_HPP_
#define ITER_PERMUTATIONS_HPP_
#include "iterbase.hpp"
#include "iteratoriterator.hpp"
#include <algorithm>
#include <initializer_list>
#include <vector>
#include <utility>
#include <iterator>
namespace iter {
template <typename Container>
class Permuter {
private:
Container container;
using IndexVector = std::vector<iterator_type<Container>>;
using Permutable = IterIterWrapper<IndexVector>;
public:
Permuter(Container&& in_container)
: container(std::forward<Container>(in_container))
{ }
class Iterator
: public std::iterator<std::input_iterator_tag, Permutable>
{
private:
static constexpr const int COMPLETE = -1;
static bool cmp_iters(
const iterator_type<Container>& lhs,
const iterator_type<Container>& rhs) noexcept {
return *lhs < *rhs;
}
Permutable working_set;
int steps{};
public:
Iterator(iterator_type<Container>&& sub_iter,
iterator_type<Container>&& sub_end)
: steps{ sub_iter != sub_end ? 0 : COMPLETE }
{
// done like this instead of using vector ctor with
// two iterators because that causes a substitution
// failure when the iterator is minimal
while (sub_iter != sub_end) {
this->working_set.get().push_back(sub_iter);
++sub_iter;
}
std::sort(std::begin(working_set.get()),
std::end(working_set.get()),
cmp_iters);
}
Permutable& operator*() {
return this->working_set;
}
Permutable *operator->() {
return &this->working_set;
}
Iterator& operator++() {
++this->steps;
if (!std::next_permutation(std::begin(working_set.get()),
std::end(working_set.get()), cmp_iters)) {
this->steps = COMPLETE;
}
return *this;
}
Iterator operator++(int) {
auto ret = *this;
++*this;
return ret;
}
bool operator!=(const Iterator& other) const {
return !(*this == other);
}
bool operator==(const Iterator& other) const {
return this->steps == other.steps;
}
};
Iterator begin() {
return {std::begin(this->container),
std::end(this->container)};
}
Iterator end() {
return {std::end(this->container),
std::end(this->container)};
}
};
template <typename Container>
Permuter<Container> permutations(Container&& container) {
return {std::forward<Container>(container)};
}
template <typename T>
Permuter<std::initializer_list<T>> permutations(
std::initializer_list<T> il) {
return {std::move(il)};
}
}
#endif
<|endoftext|>
|
<commit_before>// RUN: %clang_analyze_cc1 -Wno-unused-value -std=c++14 -analyzer-checker=core,debug.ExprInspection,alpha.core.PointerArithm -verify %s
struct X {
int *p;
int zero;
void foo () {
reset(p - 1);
}
void reset(int *in) {
while (in != p) // Loop must be entered.
zero = 1;
}
};
int test (int *in) {
X littleX;
littleX.zero = 0;
littleX.p = in;
littleX.foo();
return 5/littleX.zero; // no-warning
}
class Base {};
class Derived : public Base {};
void checkPolymorphicUse() {
Derived d[10];
Base *p = d;
++p; // expected-warning{{Pointer arithmetic on a pointer to base class is dangerous}}
}
void checkBitCasts() {
long l;
char *p = (char*)&l;
p = p+2;
}
void checkBasicarithmetic(int i) {
int t[10];
int *p = t;
++p;
int a = 5;
p = &a;
++p; // expected-warning{{Pointer arithmetic on non-array variables relies on memory layout, which is dangerous}}
p = p + 2; // expected-warning{{}}
p = 2 + p; // expected-warning{{}}
p += 2; // expected-warning{{}}
a += p[2]; // expected-warning{{}}
p = i*0 + p;
p = p + i*0;
p += i*0;
}
void checkArithOnSymbolic(int*p) {
++p;
p = p + 2;
p = 2 + p;
p += 2;
(void)p[2];
}
struct S {
int t[10];
};
void arrayInStruct() {
S s;
int * p = s.t;
++p;
S *sp = new S;
p = sp->t;
++p;
delete sp;
}
void checkNew() {
int *p = new int;
p[1] = 1; // expected-warning{{}}
}
void InitState(int* state) {
state[1] = 1; // expected-warning{{}}
}
int* getArray(int size) {
if (size == 0)
return new int;
return new int[5];
}
void checkConditionalArray() {
int* maybeArray = getArray(0);
InitState(maybeArray);
}
void checkMultiDimansionalArray() {
int a[5][5];
*(*(a+1)+2) = 2;
}
unsigned ptrSubtractionNoCrash(char *Begin, char *End) {
auto N = End - Begin;
if (Begin)
return 0;
return N;
}
<commit_msg>[analyzer] Fix crash in modeling arithmetic<commit_after>// RUN: %clang_analyze_cc1 -Wno-unused-value -std=c++14 -analyzer-checker=core,debug.ExprInspection,alpha.core.PointerArithm -verify %s
struct X {
int *p;
int zero;
void foo () {
reset(p - 1);
}
void reset(int *in) {
while (in != p) // Loop must be entered.
zero = 1;
}
};
int test (int *in) {
X littleX;
littleX.zero = 0;
littleX.p = in;
littleX.foo();
return 5/littleX.zero; // no-warning
}
class Base {};
class Derived : public Base {};
void checkPolymorphicUse() {
Derived d[10];
Base *p = d;
++p; // expected-warning{{Pointer arithmetic on a pointer to base class is dangerous}}
}
void checkBitCasts() {
long l;
char *p = (char*)&l;
p = p+2;
}
void checkBasicarithmetic(int i) {
int t[10];
int *p = t;
++p;
int a = 5;
p = &a;
++p; // expected-warning{{Pointer arithmetic on non-array variables relies on memory layout, which is dangerous}}
p = p + 2; // expected-warning{{}}
p = 2 + p; // expected-warning{{}}
p += 2; // expected-warning{{}}
a += p[2]; // expected-warning{{}}
p = i*0 + p;
p = p + i*0;
p += i*0;
}
void checkArithOnSymbolic(int*p) {
++p;
p = p + 2;
p = 2 + p;
p += 2;
(void)p[2];
}
struct S {
int t[10];
};
void arrayInStruct() {
S s;
int * p = s.t;
++p;
S *sp = new S;
p = sp->t;
++p;
delete sp;
}
void checkNew() {
int *p = new int;
p[1] = 1; // expected-warning{{}}
}
void InitState(int* state) {
state[1] = 1; // expected-warning{{}}
}
int* getArray(int size) {
if (size == 0)
return new int;
return new int[5];
}
void checkConditionalArray() {
int* maybeArray = getArray(0);
InitState(maybeArray);
}
void checkMultiDimansionalArray() {
int a[5][5];
*(*(a+1)+2) = 2;
}
unsigned ptrSubtractionNoCrash(char *Begin, char *End) {
auto N = End - Begin;
if (Begin)
return 0;
return N;
}
// Bug 34309
bool ptrAsIntegerSubtractionNoCrash(long x, char *p) {
long y = (long)p - 1;
return y == x;
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2018 Roberto Raggi <[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 "pgen/ir-print.h"
#include "pgen/flags.h"
#include "pgen/token.h"
#include <fmt/format.h>
#include <fmt/ostream.h>
#include <cctype>
#include <iostream>
namespace IR {
namespace {
std::string tokenName(const std::string& spell) {
std::string name = "T_";
for (auto ch : spell) name += std::toupper(ch);
return name;
}
} // namespace
Print::Print(std::ostream& out) : out(out) {}
void Print::operator()(IR::Stmt* s) { s->accept(this); }
void Print::setNextBasicBlock(IR::BasicBlock* block) { nextBlock_ = block; }
void Print::visit(IR::Exp* e) {
if (auto code = e->expr()->asCode()) {
fmt::print(out, "\t{0};", code->text());
out << std::endl;
} else {
assert(!"unreachable");
}
}
void Print::visit(IR::Move* m) {
fmt::print(out, "{0} = {1};", m->target()->name(), m->source()->name());
out << std::endl;
}
void Print::visit(IR::Save* s) {
fmt::print(out, "\t{0} = yycursor;", s->target()->name());
out << std::endl;
}
void Print::visit(IR::Restore* s) {
fmt::print(out, "\tif ({0} > yyparsed) yyparsed = {0};", s->source()->name());
out << std::endl;
fmt::print(out, "\tyyrewind({0});", s->source()->name());
out << std::endl;
}
void Print::visit(IR::Ret* r) {
if (r->result()) {
out << "\treturn true;" << std::endl;
return;
}
out << "\tyyrewind(yyparsed);" << std::endl;
out << "\treturn false;" << std::endl;
}
void Print::visit(IR::Jump* j) {
if (nextBlock_ == j->target()) {
out << std::endl;
return;
}
fmt::print(out, "\tgoto L{0};", j->target()->index);
out << std::endl;
}
void Print::visit(IR::CJump* cj) {
IR::BasicBlock* target = cj->iftrue();
IR::BasicBlock* cont = cj->iffalse();
std::string unop = "";
std::string binop = "==";
if (nextBlock_ == cj->iftrue()) {
std::swap(target, cont);
unop = "!";
binop = "!=";
}
if (auto name = cj->cond()->asName()) {
if (FLAGS_lines) {
out << std::endl;
fmt::print(out, "#line {0} \"{1}\"", name->sym()->line, FLAGS_input);
out << std::endl;
}
const auto& id = name->sym()->name;
if (name->sym()->isTerminal) {
fmt::print(out, "\tif (yytoken() {0} {1}) goto L{2};", binop,
tokenName(id), target->index);
} else {
fmt::print(out, "\tif ({0}parse_{1}({2})) goto L{3};", unop, id,
name->sym()->extra, target->index);
}
out << std::endl;
} else if (auto code = cj->cond()->asCode()) {
if (FLAGS_lines && code->line() != 1) {
out << std::endl;
fmt::print(out, "#line {0} \"{1}\"", code->line(), FLAGS_input);
out << std::endl;
}
fmt::print(out,
"\tif ({0}([&]() -> bool {{{1} return true; }})()) goto L{2};",
unop, code->text(), target->index);
out << std::endl;
} else if (auto literal = cj->cond()->asCharLiteral()) {
if (FLAGS_lines) {
out << std::endl;
fmt::print(out, "#line {0} \"{1}\"", literal->line(), FLAGS_input);
out << std::endl;
}
fmt::print(out, "\tif (yytoken() {0} {1}) goto L{2};", binop,
literal->value(), target->index);
out << std::endl;
} else {
assert(!"unreachable");
}
if (cont != nextBlock_) {
fmt::print(out, "\tgoto L{0};", cont->index);
out << std::endl;
}
}
} // namespace IR
<commit_msg>Fix build<commit_after>// Copyright (c) 2018 Roberto Raggi <[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 "pgen/ir-print.h"
#include "pgen/flags.h"
#include "pgen/token.h"
#include <fmt/format.h>
#include <fmt/ostream.h>
#include <cctype>
#include <iostream>
#include <cassert>
namespace IR {
namespace {
std::string tokenName(const std::string& spell) {
std::string name = "T_";
for (auto ch : spell) name += std::toupper(ch);
return name;
}
} // namespace
Print::Print(std::ostream& out) : out(out) {}
void Print::operator()(IR::Stmt* s) { s->accept(this); }
void Print::setNextBasicBlock(IR::BasicBlock* block) { nextBlock_ = block; }
void Print::visit(IR::Exp* e) {
if (auto code = e->expr()->asCode()) {
fmt::print(out, "\t{0};", code->text());
out << std::endl;
} else {
assert(!"unreachable");
}
}
void Print::visit(IR::Move* m) {
fmt::print(out, "{0} = {1};", m->target()->name(), m->source()->name());
out << std::endl;
}
void Print::visit(IR::Save* s) {
fmt::print(out, "\t{0} = yycursor;", s->target()->name());
out << std::endl;
}
void Print::visit(IR::Restore* s) {
fmt::print(out, "\tif ({0} > yyparsed) yyparsed = {0};", s->source()->name());
out << std::endl;
fmt::print(out, "\tyyrewind({0});", s->source()->name());
out << std::endl;
}
void Print::visit(IR::Ret* r) {
if (r->result()) {
out << "\treturn true;" << std::endl;
return;
}
out << "\tyyrewind(yyparsed);" << std::endl;
out << "\treturn false;" << std::endl;
}
void Print::visit(IR::Jump* j) {
if (nextBlock_ == j->target()) {
out << std::endl;
return;
}
fmt::print(out, "\tgoto L{0};", j->target()->index);
out << std::endl;
}
void Print::visit(IR::CJump* cj) {
IR::BasicBlock* target = cj->iftrue();
IR::BasicBlock* cont = cj->iffalse();
std::string unop = "";
std::string binop = "==";
if (nextBlock_ == cj->iftrue()) {
std::swap(target, cont);
unop = "!";
binop = "!=";
}
if (auto name = cj->cond()->asName()) {
if (FLAGS_lines) {
out << std::endl;
fmt::print(out, "#line {0} \"{1}\"", name->sym()->line, FLAGS_input);
out << std::endl;
}
const auto& id = name->sym()->name;
if (name->sym()->isTerminal) {
fmt::print(out, "\tif (yytoken() {0} {1}) goto L{2};", binop,
tokenName(id), target->index);
} else {
fmt::print(out, "\tif ({0}parse_{1}({2})) goto L{3};", unop, id,
name->sym()->extra, target->index);
}
out << std::endl;
} else if (auto code = cj->cond()->asCode()) {
if (FLAGS_lines && code->line() != 1) {
out << std::endl;
fmt::print(out, "#line {0} \"{1}\"", code->line(), FLAGS_input);
out << std::endl;
}
fmt::print(out,
"\tif ({0}([&]() -> bool {{{1} return true; }})()) goto L{2};",
unop, code->text(), target->index);
out << std::endl;
} else if (auto literal = cj->cond()->asCharLiteral()) {
if (FLAGS_lines) {
out << std::endl;
fmt::print(out, "#line {0} \"{1}\"", literal->line(), FLAGS_input);
out << std::endl;
}
fmt::print(out, "\tif (yytoken() {0} {1}) goto L{2};", binop,
literal->value(), target->index);
out << std::endl;
} else {
assert(!"unreachable");
}
if (cont != nextBlock_) {
fmt::print(out, "\tgoto L{0};", cont->index);
out << std::endl;
}
}
} // namespace IR
<|endoftext|>
|
<commit_before>// Copyright (c) 2020 by Robert Bosch GmbH. 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.
#ifndef IOX_UTILS_WIN_PLATFORM_MMAN_HPP
#define IOX_UTILS_WIN_PLATFORM_MMAN_HPP
#include "iceoryx_utils/platform/fcntl.hpp"
#include "iceoryx_utils/platform/types.hpp"
#include "iceoryx_utils/platform/unistd.hpp"
#include "iceoryx_utils/platform/win32_errorHandling.hpp"
#include <cstdio>
#include <string>
#include <sys/stat.h>
#define MAP_SHARED 0
#define MAP_FAILED 1
#define PROT_READ 3
#define PROT_WRITE 4
inline void* mmap(void* addr, size_t length, int prot, int flags, int fd, off_t offset)
{
DWORD desiredAccess = FILE_MAP_ALL_ACCESS;
DWORD fileOffsetHigh = 0;
DWORD fileOffsetLow = 0;
DWORD numberOfBytesToMap = length;
void* mappedObject = MapViewOfFile(
HandleTranslator::getInstance().get(fd), desiredAccess, fileOffsetHigh, fileOffsetLow, numberOfBytesToMap);
if (mappedObject == nullptr)
{
PrintLastErrorToConsole();
}
return mappedObject;
}
inline int munmap(void* addr, size_t length)
{
if (UnmapViewOfFile(addr))
{
return 0;
}
PrintLastErrorToConsole();
return -1;
}
inline int shm_open(const char* name, int oflag, mode_t mode)
{
static constexpr DWORD MAXIMUM_SIZE_HIGH = 0;
static constexpr DWORD MAXIMUM_SIZE_LOW = 256;
HANDLE sharedMemoryHandle{nullptr};
DWORD access = (oflag & O_RDWR) ? PAGE_READWRITE : PAGE_READONLY;
if (oflag & O_CREAT) // O_EXCL
{
sharedMemoryHandle =
CreateFileMapping(INVALID_HANDLE_VALUE, nullptr, access, MAXIMUM_SIZE_HIGH, MAXIMUM_SIZE_LOW, name);
if (oflag & O_EXCL && PrintLastErrorToConsole() == ERROR_ALREADY_EXISTS)
{
if (sharedMemoryHandle != nullptr)
{
CloseHandle(sharedMemoryHandle);
}
return -1;
}
}
else
{
sharedMemoryHandle = OpenFileMapping(FILE_MAP_ALL_ACCESS, false, name);
if (PrintLastErrorToConsole() != 0)
{
if (sharedMemoryHandle != nullptr)
{
CloseHandle(sharedMemoryHandle);
}
return -1;
}
}
return HandleTranslator::getInstance().add(sharedMemoryHandle);
}
inline int shm_unlink(const char* name)
{
return 0;
}
#endif // IOX_UTILS_WIN_PLATFORM_MMAN_HPP
<commit_msg>iox-#252 Fix Windows build<commit_after>// Copyright (c) 2020 by Robert Bosch GmbH. 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.
#ifndef IOX_UTILS_WIN_PLATFORM_MMAN_HPP
#define IOX_UTILS_WIN_PLATFORM_MMAN_HPP
#include "iceoryx_utils/platform/fcntl.hpp"
#include "iceoryx_utils/platform/types.hpp"
#include "iceoryx_utils/platform/unistd.hpp"
#include "iceoryx_utils/platform/win32_errorHandling.hpp"
#include <cstdio>
#include <string>
#include <sys/stat.h>
#define MAP_SHARED 0
#define MAP_FAILED 1
#define PROT_NONE 0
#define PROT_READ 3
#define PROT_WRITE 4
inline void* mmap(void* addr, size_t length, int prot, int flags, int fd, off_t offset)
{
DWORD desiredAccess = FILE_MAP_ALL_ACCESS;
DWORD fileOffsetHigh = 0;
DWORD fileOffsetLow = 0;
DWORD numberOfBytesToMap = length;
void* mappedObject = MapViewOfFile(
HandleTranslator::getInstance().get(fd), desiredAccess, fileOffsetHigh, fileOffsetLow, numberOfBytesToMap);
if (mappedObject == nullptr)
{
PrintLastErrorToConsole();
}
return mappedObject;
}
inline int munmap(void* addr, size_t length)
{
if (UnmapViewOfFile(addr))
{
return 0;
}
PrintLastErrorToConsole();
return -1;
}
inline int shm_open(const char* name, int oflag, mode_t mode)
{
static constexpr DWORD MAXIMUM_SIZE_HIGH = 0;
static constexpr DWORD MAXIMUM_SIZE_LOW = 256;
HANDLE sharedMemoryHandle{nullptr};
DWORD access = (oflag & O_RDWR) ? PAGE_READWRITE : PAGE_READONLY;
if (oflag & O_CREAT) // O_EXCL
{
sharedMemoryHandle =
CreateFileMapping(INVALID_HANDLE_VALUE, nullptr, access, MAXIMUM_SIZE_HIGH, MAXIMUM_SIZE_LOW, name);
if (oflag & O_EXCL && PrintLastErrorToConsole() == ERROR_ALREADY_EXISTS)
{
if (sharedMemoryHandle != nullptr)
{
CloseHandle(sharedMemoryHandle);
}
return -1;
}
}
else
{
sharedMemoryHandle = OpenFileMapping(FILE_MAP_ALL_ACCESS, false, name);
if (PrintLastErrorToConsole() != 0)
{
if (sharedMemoryHandle != nullptr)
{
CloseHandle(sharedMemoryHandle);
}
return -1;
}
}
return HandleTranslator::getInstance().add(sharedMemoryHandle);
}
inline int shm_unlink(const char* name)
{
return 0;
}
#endif // IOX_UTILS_WIN_PLATFORM_MMAN_HPP
<|endoftext|>
|
<commit_before>#include "colibri_ca.h"
#include "colibri_local_nav.h"
#include "colibri_action.h"
#include "PID_controller.h"
#include "global_planner.h"
#include "task_mgr.h"
#include <boost/bind.hpp>
#include "geometry_msgs/PoseStamped.h"
void PlannerCallback(planner *plannerObj, float* start_pos, float* goal_pos, bool *finish_flag);
int main(int argc, char* argv[])
{
ROS_INFO("Start to Go to Mult Goals in Rviz ... ");
// ROS nav node initial
ros::init(argc, argv, "Nav_Mult_RvizGoal_Node");
ros::Rate loop_rate(10); // Set control freq at 10 hz
unsigned int delay_cnt = 0; // Init delay conter for scanObj
// Auto nav obj initial
scan_ca scan4caObj;
local_nav local4navObj;
nav_action actionObj;
planner plannerObj;
task_mgr taskObj;
// Local key points relation param initial
float tmp_delta_dis = 0.0;
float tmp_robot2goal_yaw = 0.0;
float tmp_laser2goal_yaw = 0.0;
float dir_goal_in_laser = 0.0;
float self_rotation_angle = 0.0;
bool goal_inlaser_flag = true;
unsigned int turn_adj_flag = 1;
float tmp_action_cmd_t[2] = {0.0, 0.0};
float* ptr_action_cmd_t = tmp_action_cmd_t;
unsigned int micro_adj_flag = 0;
unsigned int adj_flag = 0;
bool obtain_flag = false;
unsigned int search_start = 0;
ros::NodeHandle nh_fp;
ros::Timer planner_timer;
bool finish_plan = false;
bool tmp_timer_finish =false;
bool *timer_finish = &tmp_timer_finish;
static unsigned int index4gravaton = 0;
float delta_robot2gravaton = 0.0;
bool at_gravaton_flag = false;
bool exist_gravaton_flag = false;
bool replan_flag = false;
float rt_r2g_dis = 100.0;
// Waiting for set goal in Rviz
while(taskObj.obtain_goal_flag == false)
{
ros::spinOnce();
loop_rate.sleep();
}
local4navObj.goal_state[0] = taskObj.cur_goal[0]; // Extract the Rviz goal for nav
local4navObj.goal_state[1] = taskObj.cur_goal[1];
local4navObj.goal_state[2] = taskObj.cur_goal[2];
while (!ros::service::waitForService(plannerObj.srv4make_plan, ros::Duration(0.2))) // Waiting for path paln srv
{
ROS_INFO("Waiting for srv move_base/make_plan to become available");
}
ROS_INFO("Srv move_base/make_plan prepared OK...");
// Inital path plan calling and gravaton calc
finish_plan = plannerObj.ExecMonoPlanAndGravaton(plannerObj,&local4navObj.cur_robot_state[0],&local4navObj.goal_state[0], search_start,index4gravaton);
// Set path plan timer
planner_timer = nh_fp.createTimer(ros::Duration(PLAN_INTERVAL), boost::bind(&PlannerCallback, &plannerObj, &local4navObj.amcl_cur_state[0],&taskObj.cur_goal[0], timer_finish));
while (ros::ok())
{
if(delay_cnt < DELAY_CNT_MAX)
{
delay_cnt++;
ros::spinOnce();
loop_rate.sleep();
}
if(delay_cnt >= DELAY_CNT_MAX)
{
ROS_INFO("------ start ------");
if(*timer_finish == true)
{
*timer_finish = false;
index4gravaton = 0;
replan_flag = true;
}
else
{
if((at_gravaton_flag == true && local4navObj.approaching_flag == false)||(replan_flag == true))
{
plannerObj.CalcPath2RobotDeltaDis(plannerObj.path_array, local4navObj.amcl_cur_state);
index4gravaton = plannerObj.CalcGravatonFromPath(plannerObj.path_array, plannerObj.path2robot_array, index4gravaton, plannerObj.gravaton,exist_gravaton_flag);
at_gravaton_flag = false;
replan_flag = false;
}
at_gravaton_flag = actionObj.ReachGravatonOK(&local4navObj.amcl_cur_state[0],&plannerObj.gravaton.x, delta_robot2gravaton);
if(local4navObj.approaching_flag == true)
{
plannerObj.gravaton.x = taskObj.cur_goal[0];
plannerObj.gravaton.y = taskObj.cur_goal[1];
plannerObj.gravaton.yaw = taskObj.cur_goal[2];
}
}
local4navObj.CalcOffsetOfGoalAndRobot(local4navObj.amcl_cur_state, &plannerObj.gravaton.x, &tmp_delta_dis, &tmp_robot2goal_yaw, &tmp_laser2goal_yaw);
goal_inlaser_flag = local4navObj.CalcGoalDirOfLaserViewNew(&tmp_laser2goal_yaw, &local4navObj.amcl_cur_state[2], &dir_goal_in_laser, &self_rotation_angle);
scan4caObj.CalcPhiParam(local4navObj.cur_robot_vel[0], dir_goal_in_laser);
scan4caObj.CalcKrfTheta(scan4caObj.kp_phi_vec, scan4caObj.phi_start_vec, scan4caObj.phi_end_vec);
scan4caObj.CalcCorrectedKrf();
scan4caObj.CalcPassFcnAndFwdBnd(scan4caObj.wander, &scan4caObj.max_passfcn_val, scan4caObj.passfcn_vec);
scan4caObj.CalcPassFcnAndBwdBnd(scan4caObj.wander, &scan4caObj.max_passfcn_val, scan4caObj.passfcn_vec);
scan4caObj.angle_adj = scan4caObj.CalcAdjDir(scan4caObj.passfcn_vec,scan4caObj.max_passfcn_val, &scan4caObj.maxfcn_fwdbnd,&scan4caObj.maxfcn_bwdbnd);
scan4caObj.CalcCollisionInAPF();
if(goal_inlaser_flag == true)
{
local4navObj.apf_ctrl_output[0] = (V_MAX - V_MIN) * (scan4caObj.max_passfcn_val / D_M) + V_MIN;
local4navObj.apf_ctrl_output[1] = scan4caObj.angle_adj / 200.0;
}
else
{
local4navObj.apf_ctrl_output[0] = 0.0;
local4navObj.apf_ctrl_output[1] = 0.0;
}
local4navObj.SatuateCmdVel(local4navObj.apf_ctrl_output,local4navObj.apf_ctrl_output+1);
local4navObj.CalcEuclidDistance(local4navObj.amcl_cur_state, taskObj.cur_goal, rt_r2g_dis);
local4navObj.approaching_flag = local4navObj.ReachApprochingAreaOK(&rt_r2g_dis);
if(tmp_delta_dis >= GOAL_NGHBORHD)
{
ptr_action_cmd_t = actionObj.AdjustMovingDirAction(&local4navObj.amcl_cur_state[2], &dir_goal_in_laser, &tmp_robot2goal_yaw, &turn_adj_flag);
}
else
{
}
if(turn_adj_flag == 1)
{
if(local4navObj.approaching_flag == false)
{
*ptr_action_cmd_t = local4navObj.apf_ctrl_output[0];
*(ptr_action_cmd_t + 1) = local4navObj.apf_ctrl_output[1];
}
else
{
ptr_action_cmd_t = actionObj.ApproachingGoalAction(&local4navObj.amcl_cur_state[0],&local4navObj.goal_state[0],&dir_goal_in_laser,µ_adj_flag);
}
}
//local4navObj.position_OK_flag = local4navObj.ReachGoalPositionOK(&tmp_delta_dis);
local4navObj.SatuateCmdVel(ptr_action_cmd_t,ptr_action_cmd_t + 1);
local4navObj.apf_cmd_vel.linear.x = *ptr_action_cmd_t;
local4navObj.apf_cmd_vel.angular.z = *(ptr_action_cmd_t + 1);
if(local4navObj.position_OK_flag == true)
{
local4navObj.apf_cmd_vel.linear.x = 0.0;
local4navObj.apf_cmd_vel.angular.z = 0.0;
}
local4navObj.pub_apf_twist.publish(local4navObj.apf_cmd_vel);
scan4caObj.fwd_maxpass_num = 0;
scan4caObj.bwd_maxpass_num = 0;
cout<<"taskObj.cur_goal[0]: "<<taskObj.cur_goal[0]<<endl;
cout<<"taskObj.cur_goal[1]: "<<taskObj.cur_goal[1]<<endl;
cout<<"taskObj.cur_goal[2]: "<<taskObj.cur_goal[2]<<endl;
ros::spinOnce();
loop_rate.sleep();
ROS_INFO("------- end --------");
}
}
local4navObj.apf_cmd_vel.linear.x = 0.0;
local4navObj.apf_cmd_vel.angular.z = 0.0;
local4navObj.pub_apf_twist.publish(local4navObj.apf_cmd_vel);
return 0;
}
void PlannerCallback(planner *plannerObj, float* start_pos, float* goal_pos, bool *finish_flag)
{
plannerObj->ObtainPathArray(plannerObj->serviceClient, plannerObj->path_srv, start_pos, goal_pos, finish_flag);
}
<commit_msg>modify the path plan timer handle name from nh_fp to nh_pp<commit_after>#include "colibri_ca.h"
#include "colibri_local_nav.h"
#include "colibri_action.h"
#include "PID_controller.h"
#include "global_planner.h"
#include "task_mgr.h"
#include <boost/bind.hpp>
#include "geometry_msgs/PoseStamped.h"
void PlannerCallback(planner *plannerObj, float* start_pos, float* goal_pos, bool *finish_flag);
int main(int argc, char* argv[])
{
ROS_INFO("Start to Go to Mult Goals in Rviz ... ");
// ROS nav node initial
ros::init(argc, argv, "Nav_Mult_RvizGoal_Node");
ros::Rate loop_rate(10); // Set control freq at 10 hz
unsigned int delay_cnt = 0; // Init delay conter for scanObj
// Auto nav obj initial
scan_ca scan4caObj;
local_nav local4navObj;
nav_action actionObj;
planner plannerObj;
task_mgr taskObj;
// Local key points relation param initial
float tmp_delta_dis = 0.0;
float tmp_robot2goal_yaw = 0.0;
float tmp_laser2goal_yaw = 0.0;
float dir_goal_in_laser = 0.0;
float self_rotation_angle = 0.0;
bool goal_inlaser_flag = true;
unsigned int turn_adj_flag = 1;
float tmp_action_cmd_t[2] = {0.0, 0.0};
float* ptr_action_cmd_t = tmp_action_cmd_t;
unsigned int micro_adj_flag = 0;
unsigned int adj_flag = 0;
bool obtain_flag = false;
unsigned int search_start = 0;
ros::NodeHandle nh_pp;
ros::Timer planner_timer;
bool finish_plan = false;
bool tmp_timer_finish =false;
bool *timer_finish = &tmp_timer_finish;
static unsigned int index4gravaton = 0;
float delta_robot2gravaton = 0.0;
bool at_gravaton_flag = false;
bool exist_gravaton_flag = false;
bool replan_flag = false;
float rt_r2g_dis = 100.0;
// Waiting for set goal in Rviz
while(taskObj.obtain_goal_flag == false)
{
ros::spinOnce();
loop_rate.sleep();
}
local4navObj.goal_state[0] = taskObj.cur_goal[0]; // Extract the Rviz goal for nav
local4navObj.goal_state[1] = taskObj.cur_goal[1];
local4navObj.goal_state[2] = taskObj.cur_goal[2];
while (!ros::service::waitForService(plannerObj.srv4make_plan, ros::Duration(0.2))) // Waiting for path paln srv
{
ROS_INFO("Waiting for srv move_base/make_plan to become available");
}
ROS_INFO("Srv move_base/make_plan prepared OK...");
// Inital path plan calling and gravaton calc
finish_plan = plannerObj.ExecMonoPlanAndGravaton(plannerObj,&local4navObj.cur_robot_state[0],&local4navObj.goal_state[0], search_start,index4gravaton);
// Set path plan timer
planner_timer = nh_pp.createTimer(ros::Duration(PLAN_INTERVAL), boost::bind(&PlannerCallback, &plannerObj, &local4navObj.amcl_cur_state[0],&taskObj.cur_goal[0], timer_finish));
while (ros::ok())
{
if(delay_cnt < DELAY_CNT_MAX)
{
delay_cnt++;
ros::spinOnce();
loop_rate.sleep();
}
if(delay_cnt >= DELAY_CNT_MAX)
{
ROS_INFO("------ start ------");
if(*timer_finish == true)
{
*timer_finish = false;
index4gravaton = 0;
replan_flag = true;
}
else
{
if((at_gravaton_flag == true && local4navObj.approaching_flag == false)||(replan_flag == true))
{
plannerObj.CalcPath2RobotDeltaDis(plannerObj.path_array, local4navObj.amcl_cur_state);
index4gravaton = plannerObj.CalcGravatonFromPath(plannerObj.path_array, plannerObj.path2robot_array, index4gravaton, plannerObj.gravaton,exist_gravaton_flag);
at_gravaton_flag = false;
replan_flag = false;
}
at_gravaton_flag = actionObj.ReachGravatonOK(&local4navObj.amcl_cur_state[0],&plannerObj.gravaton.x, delta_robot2gravaton);
if(local4navObj.approaching_flag == true)
{
plannerObj.gravaton.x = taskObj.cur_goal[0];
plannerObj.gravaton.y = taskObj.cur_goal[1];
plannerObj.gravaton.yaw = taskObj.cur_goal[2];
}
}
local4navObj.CalcOffsetOfGoalAndRobot(local4navObj.amcl_cur_state, &plannerObj.gravaton.x, &tmp_delta_dis, &tmp_robot2goal_yaw, &tmp_laser2goal_yaw);
goal_inlaser_flag = local4navObj.CalcGoalDirOfLaserViewNew(&tmp_laser2goal_yaw, &local4navObj.amcl_cur_state[2], &dir_goal_in_laser, &self_rotation_angle);
scan4caObj.CalcPhiParam(local4navObj.cur_robot_vel[0], dir_goal_in_laser);
scan4caObj.CalcKrfTheta(scan4caObj.kp_phi_vec, scan4caObj.phi_start_vec, scan4caObj.phi_end_vec);
scan4caObj.CalcCorrectedKrf();
scan4caObj.CalcPassFcnAndFwdBnd(scan4caObj.wander, &scan4caObj.max_passfcn_val, scan4caObj.passfcn_vec);
scan4caObj.CalcPassFcnAndBwdBnd(scan4caObj.wander, &scan4caObj.max_passfcn_val, scan4caObj.passfcn_vec);
scan4caObj.angle_adj = scan4caObj.CalcAdjDir(scan4caObj.passfcn_vec,scan4caObj.max_passfcn_val, &scan4caObj.maxfcn_fwdbnd,&scan4caObj.maxfcn_bwdbnd);
scan4caObj.CalcCollisionInAPF();
if(goal_inlaser_flag == true)
{
local4navObj.apf_ctrl_output[0] = (V_MAX - V_MIN) * (scan4caObj.max_passfcn_val / D_M) + V_MIN;
local4navObj.apf_ctrl_output[1] = scan4caObj.angle_adj / 200.0;
}
else
{
local4navObj.apf_ctrl_output[0] = 0.0;
local4navObj.apf_ctrl_output[1] = 0.0;
}
local4navObj.SatuateCmdVel(local4navObj.apf_ctrl_output,local4navObj.apf_ctrl_output+1);
local4navObj.CalcEuclidDistance(local4navObj.amcl_cur_state, taskObj.cur_goal, rt_r2g_dis);
local4navObj.approaching_flag = local4navObj.ReachApprochingAreaOK(&rt_r2g_dis);
if(tmp_delta_dis >= GOAL_NGHBORHD)
{
ptr_action_cmd_t = actionObj.AdjustMovingDirAction(&local4navObj.amcl_cur_state[2], &dir_goal_in_laser, &tmp_robot2goal_yaw, &turn_adj_flag);
}
else
{
}
if(turn_adj_flag == 1)
{
if(local4navObj.approaching_flag == false)
{
*ptr_action_cmd_t = local4navObj.apf_ctrl_output[0];
*(ptr_action_cmd_t + 1) = local4navObj.apf_ctrl_output[1];
}
else
{
ptr_action_cmd_t = actionObj.ApproachingGoalAction(&local4navObj.amcl_cur_state[0],&local4navObj.goal_state[0],&dir_goal_in_laser,µ_adj_flag);
}
}
//local4navObj.position_OK_flag = local4navObj.ReachGoalPositionOK(&tmp_delta_dis);
local4navObj.SatuateCmdVel(ptr_action_cmd_t,ptr_action_cmd_t + 1);
local4navObj.apf_cmd_vel.linear.x = *ptr_action_cmd_t;
local4navObj.apf_cmd_vel.angular.z = *(ptr_action_cmd_t + 1);
if(local4navObj.position_OK_flag == true)
{
local4navObj.apf_cmd_vel.linear.x = 0.0;
local4navObj.apf_cmd_vel.angular.z = 0.0;
}
local4navObj.pub_apf_twist.publish(local4navObj.apf_cmd_vel);
scan4caObj.fwd_maxpass_num = 0;
scan4caObj.bwd_maxpass_num = 0;
cout<<"taskObj.cur_goal[0]: "<<taskObj.cur_goal[0]<<endl;
cout<<"taskObj.cur_goal[1]: "<<taskObj.cur_goal[1]<<endl;
cout<<"taskObj.cur_goal[2]: "<<taskObj.cur_goal[2]<<endl;
ros::spinOnce();
loop_rate.sleep();
ROS_INFO("------- end --------");
}
}
local4navObj.apf_cmd_vel.linear.x = 0.0;
local4navObj.apf_cmd_vel.angular.z = 0.0;
local4navObj.pub_apf_twist.publish(local4navObj.apf_cmd_vel);
return 0;
}
void PlannerCallback(planner *plannerObj, float* start_pos, float* goal_pos, bool *finish_flag)
{
plannerObj->ObtainPathArray(plannerObj->serviceClient, plannerObj->path_srv, start_pos, goal_pos, finish_flag);
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: composedprops.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: hr $ $Date: 2003-03-19 15:58:30 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc..
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _COMPHELPER_COMPOSEDPROPS_HXX_
#define _COMPHELPER_COMPOSEDPROPS_HXX_
#ifndef _CPPUHELPER_IMPLBASE2_HXX_
#include <cppuhelper/implbase2.hxx>
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif
#ifndef _COMPHELPER_STLTYPES_HXX_
#include <comphelper/stl_types.hxx>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSTATE_HPP_
#include <com/sun/star/beans/XPropertyState.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSETINFO_HPP_
#include <com/sun/star/beans/XPropertySetInfo.hpp>
#endif
#ifndef _OSL_MUTEX_HXX_
#include <osl/mutex.hxx>
#endif
//.........................................................................
namespace comphelper
{
//.........................................................................
//=====================================================================
//= IPropertySetComposerCallback
//=====================================================================
class IPropertySetComposerCallback
{
public:
/** determines whether or not a property should appear in the composed property set
@param _rPropertyName
the name of the property
*/
virtual sal_Bool isComposeable(const ::rtl::OUString& _rPropertyName) const = 0;
};
//=====================================================================
//= OComposedPropertySet
//=====================================================================
class OComposedPropertySetInfo;
typedef ::cppu::WeakImplHelper2 < ::com::sun::star::beans::XPropertySet
, ::com::sun::star::beans::XPropertyState
> OComposedPropertySet_Base;
/** helper class for composing a property set from a sequence of other property sets.
<p>First: This class is a fast shot, so don't sue me :) (To be honest, it's the migration of an old ugly
implementation. It's still ugly).</p>
<p>The property listener mechanisms are not supported (you can't add property listeners).</p>
<p>Speaking strictly, the property defaults (getPropertyDefault) do not work correctly, as there's always
an empty <type scope="com.sun.star.uno">Any</type> returned.</p>
*/
class OComposedPropertySet : public OComposedPropertySet_Base
{
private:
::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property >
m_aProperties;
OComposedPropertySetInfo* m_pInfo;
protected:
::osl::Mutex m_aMutex;
DECLARE_STL_VECTOR(::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>, PropertySetArray);
PropertySetArray m_aSingleSets;
public:
/** constructs a composed property set
@param _rElements
the single property sets to compose
<p>The first property set in the sequence is the master set, any properties not present here
are not present in the composed set.<br/>
This may change in the future (as it's just missing implementation), so don't rely on this behaviour.</p>
@param _pPropertyMetaData
the callback for retrieving property meta data (namely composeability)<br/>
if not specified, all properties are assumed to be composable
*/
OComposedPropertySet(
const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet> > & _rElements,
const IPropertySetComposerCallback* _pPropertyMetaData = NULL
);
// XPropertyState
virtual ::com::sun::star::beans::PropertyState SAL_CALL getPropertyState( const ::rtl::OUString& PropertyName ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyState > SAL_CALL getPropertyStates( const ::com::sun::star::uno::Sequence< ::rtl::OUString >& aPropertyName ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setPropertyToDefault( const ::rtl::OUString& PropertyName ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Any SAL_CALL getPropertyDefault( const ::rtl::OUString& aPropertyName ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
// XPropertySet
virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo( ) throw(::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setPropertyValue( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Any& aValue ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Any SAL_CALL getPropertyValue( const ::rtl::OUString& PropertyName ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL addPropertyChangeListener( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener >& xListener ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL removePropertyChangeListener( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener >& aListener ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL addVetoableChangeListener( const ::rtl::OUString& PropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XVetoableChangeListener >& aListener ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL removeVetoableChangeListener( const ::rtl::OUString& PropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XVetoableChangeListener >& aListener ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
protected:
~OComposedPropertySet();
void compose(const IPropertySetComposerCallback* _pMetaData);
};
//.........................................................................
} // namespace comphelper
//.........................................................................
#endif // _COMPHELPER_COMPOSEDPROPS_HXX_
<commit_msg>INTEGRATION: CWS visibility02 (1.2.210); FILE MERGED 2005/01/05 05:54:06 mnicel 1.2.210.1: Issue number: 38608 Part of symbol visibility work.<commit_after>/*************************************************************************
*
* $RCSfile: composedprops.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: vg $ $Date: 2005-02-16 15:53:53 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc..
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _COMPHELPER_COMPOSEDPROPS_HXX_
#define _COMPHELPER_COMPOSEDPROPS_HXX_
#ifndef _CPPUHELPER_IMPLBASE2_HXX_
#include <cppuhelper/implbase2.hxx>
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif
#ifndef _COMPHELPER_STLTYPES_HXX_
#include <comphelper/stl_types.hxx>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSTATE_HPP_
#include <com/sun/star/beans/XPropertyState.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSETINFO_HPP_
#include <com/sun/star/beans/XPropertySetInfo.hpp>
#endif
#ifndef _OSL_MUTEX_HXX_
#include <osl/mutex.hxx>
#endif
#ifndef INCLUDED_COMPHELPERDLLAPI_H
#include "comphelper/comphelperdllapi.h"
#endif
//.........................................................................
namespace comphelper
{
//.........................................................................
//=====================================================================
//= IPropertySetComposerCallback
//=====================================================================
class IPropertySetComposerCallback
{
public:
/** determines whether or not a property should appear in the composed property set
@param _rPropertyName
the name of the property
*/
virtual sal_Bool isComposeable(const ::rtl::OUString& _rPropertyName) const = 0;
};
//=====================================================================
//= OComposedPropertySet
//=====================================================================
class OComposedPropertySetInfo;
typedef ::cppu::WeakImplHelper2 < ::com::sun::star::beans::XPropertySet
, ::com::sun::star::beans::XPropertyState
> OComposedPropertySet_Base;
/** helper class for composing a property set from a sequence of other property sets.
<p>First: This class is a fast shot, so don't sue me :) (To be honest, it's the migration of an old ugly
implementation. It's still ugly).</p>
<p>The property listener mechanisms are not supported (you can't add property listeners).</p>
<p>Speaking strictly, the property defaults (getPropertyDefault) do not work correctly, as there's always
an empty <type scope="com.sun.star.uno">Any</type> returned.</p>
*/
class COMPHELPER_DLLPUBLIC OComposedPropertySet : public OComposedPropertySet_Base
{
private:
::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property >
m_aProperties;
OComposedPropertySetInfo* m_pInfo;
protected:
::osl::Mutex m_aMutex;
DECLARE_STL_VECTOR(::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>, PropertySetArray);
PropertySetArray m_aSingleSets;
public:
/** constructs a composed property set
@param _rElements
the single property sets to compose
<p>The first property set in the sequence is the master set, any properties not present here
are not present in the composed set.<br/>
This may change in the future (as it's just missing implementation), so don't rely on this behaviour.</p>
@param _pPropertyMetaData
the callback for retrieving property meta data (namely composeability)<br/>
if not specified, all properties are assumed to be composable
*/
OComposedPropertySet(
const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet> > & _rElements,
const IPropertySetComposerCallback* _pPropertyMetaData = NULL
);
// XPropertyState
virtual ::com::sun::star::beans::PropertyState SAL_CALL getPropertyState( const ::rtl::OUString& PropertyName ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyState > SAL_CALL getPropertyStates( const ::com::sun::star::uno::Sequence< ::rtl::OUString >& aPropertyName ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setPropertyToDefault( const ::rtl::OUString& PropertyName ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Any SAL_CALL getPropertyDefault( const ::rtl::OUString& aPropertyName ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
// XPropertySet
virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo( ) throw(::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setPropertyValue( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Any& aValue ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Any SAL_CALL getPropertyValue( const ::rtl::OUString& PropertyName ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL addPropertyChangeListener( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener >& xListener ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL removePropertyChangeListener( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener >& aListener ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL addVetoableChangeListener( const ::rtl::OUString& PropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XVetoableChangeListener >& aListener ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL removeVetoableChangeListener( const ::rtl::OUString& PropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XVetoableChangeListener >& aListener ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
protected:
~OComposedPropertySet();
void compose(const IPropertySetComposerCallback* _pMetaData);
};
//.........................................................................
} // namespace comphelper
//.........................................................................
#endif // _COMPHELPER_COMPOSEDPROPS_HXX_
<|endoftext|>
|
<commit_before>// RUN: cat %s | %cling -Xclang -verify | FileCheck %s
//This file checks a call instruction. The called function has arguments with nonnull attribute.
#include <string.h>
//XFAIL: darwin
char *p = 0;
strcmp("a", p); // expected-warning {{you are about to dereference null ptr, which probably will lead to seg violation. Do you want to proceed?[y/n]}}
strcmp(p, "a"); // expected-warning {{you are about to dereference null ptr, which probably will lead to seg violation. Do you want to proceed?[y/n]}}
extern "C" int printf(const char* fmt, ...);
.rawInput 1
extern "C" int cannotCallWithNull(int* p = 0);
extern "C" int cannotCallWithNull(int* p) __attribute__((nonnull(1)));
extern "C" int cannotCallWithNull(int* p);
extern "C" int cannotCallWithNull(int* p);
.rawInput 0
extern "C" int cannotCallWithNull(int* p) {
if (!p)
printf("Must not be called with p=0.\n");
return 1;
}
cannotCallWithNull() // warning-expected {{null passed to a callee which requires a non-null argument}}
// expected-warning {{you are about to dereference null ptr, which probably will lead to seg violation. Do you want to proceed?[y/n]}}
//CHECK-NOT: Must not be called with p=0.
//CHECK: (int) 1
.q
<commit_msg>Spell correctly expected-warning and not warning expected. Call a function with non null and check the expected result.<commit_after>// RUN: cat %s | %cling -Xclang -verify | FileCheck %s
//This file checks a call instruction. The called function has arguments with nonnull attribute.
#include <string.h>
//XFAIL: darwin
char *p = 0;
strcmp("a", p); // expected-warning {{you are about to dereference null ptr, which probably will lead to seg violation. Do you want to proceed?[y/n]}}
strcmp(p, "a"); // expected-warning {{you are about to dereference null ptr, which probably will lead to seg violation. Do you want to proceed?[y/n]}}
extern "C" int printf(const char* fmt, ...);
.rawInput 1
extern "C" int cannotCallWithNull(int* p = 0);
extern "C" int cannotCallWithNull(int* p) __attribute__((nonnull(1)));
extern "C" int cannotCallWithNull(int* p);
extern "C" int cannotCallWithNull(int* p);
.rawInput 0
extern "C" int cannotCallWithNull(int* p) {
if (!p)
printf("Must not be called with p=0.\n");
return 1;
}
cannotCallWithNull() // expected-warning {{null passed to a callee which requires a non-null argument}}
// expected-warning {{you are about to dereference null ptr, which probably will lead to seg violation. Do you want to proceed?[y/n]}}
//CHECK-NOT: Must not be called with p=0.
cannotCallWithNull(new int(4))
//CHECK: (int) 1
.q
<|endoftext|>
|
<commit_before>#include <ngraph.h>
#include <engpar_support.h>
#include <iostream>
#include <PCU.h>
#include <vector>
#include "buildGraphs.h"
#include "gatherGraphs.h"
#include "TestingSuite.h"
#include <engpar.h>
int testVtxBalancer(agi::Ngraph*);
int testBalancer(agi::Ngraph*);
int testMultipleBalances(agi::Ngraph*);
int testWeightBalancer_1();
int testWeightBalancer_4();
int testWeightBalancer_100();
int testGlobalSplit(agi::Ngraph*);
int testLocalSplit(agi::Ngraph*);
int testSplitAndBalance(agi::Ngraph*);
void switchToOriginals(int smallSize, bool& isOriginal, MPI_Comm& newComm);
#define SPLIT_TEST 4
int main(int argc, char* argv[]) {
MPI_Init(&argc,&argv);
EnGPar_Initialize();
if (argc==1) {
if (!PCU_Comm_Self())
EnGPar_Warning_Message("Usage: %s <operation> [trial number]\n"
" operation 0 = vtxBalance\n"
" operation 1 = balance\n"
" operation 2 = balanceMultiple\n"
" operation 3 = balanceWeights\n"
" operation %d = ParMETIS global split\n"
" operation %d = ParMETIS local split\n"
" operation %d = ParMETIS split and balance\n"
,argv[0],SPLIT_TEST,SPLIT_TEST+1,SPLIT_TEST+2);
EnGPar_Finalize();
MPI_Finalize();
return 1;
}
int operation = -1;
if (argc>1)
operation = atoi(argv[1]);
int trial = -1;
if (argc>2)
trial = atoi(argv[2]);
EnGPar_Set_Verbosity(-1);
//Create the testing suite
TestingSuite suite(argv[0]);
//Gather specific tests that have more fine grain checks
if (operation==3) {
suite.addFineTest("Weight Balancer with 1 Component",testWeightBalancer_1);
suite.addFineTest("Weight Balancer with 4 Components",testWeightBalancer_4);
suite.addFineTest("Weight Balancer with 100 Components",testWeightBalancer_100);
}
bool isOriginal = true;
MPI_Comm newComm;
if (operation>=SPLIT_TEST) {
switchToOriginals(2, isOriginal,newComm);
//Switch the internal communicator (this changes PCU so use PCU_Comm_... with caution)
EnGPar_Switch_Comm(newComm);
}
//Gather the graphs for the general tests
if (isOriginal) {
//gatherEBINGraphs(suite);
gatherBGDGraphs(suite);
}
if (operation>=SPLIT_TEST) {
MPI_Comm_free(&newComm);
}
EnGPar_Switch_Comm(MPI_COMM_WORLD);
suite.fillEmptyTestGraphs();
//Gather general tests that run on the graphs collected prior to this
if (operation==0)
suite.addGeneralTest("Vertex Balancer",testVtxBalancer);
else if (operation==1)
suite.addGeneralTest("General Balancer",testBalancer);
else if (operation==2)
suite.addGeneralTest("Balance Twice",testMultipleBalances);
else if (operation == SPLIT_TEST)
suite.addGeneralTest("Global ParMETIS split",testGlobalSplit);
else if (operation == SPLIT_TEST+1)
suite.addGeneralTest("Local ParMETIS split",testLocalSplit);
else if (operation == SPLIT_TEST+2)
suite.addGeneralTest("Global Split and MC Balance",testSplitAndBalance);
//Run the tests and get the number of failures
int ierr = suite.runTests(trial);
suite.deleteTestGraphs();
EnGPar_Finalize();
MPI_Finalize();
return ierr;
}
agi::Ngraph* makeArtificialXGCMGraph(int numComps) {
//Create the graph where each process has 1 vertex per component
// each vertex has weight = PCU_Comm_Self()*100
/* The Ngraph for parts=4, numComps = 3 would be:
numbers=verts, letters = hyperedges
1 4 2 5 3 6
\ / \ / \ /
A B C
/ \ / \ / \
7 10 8 11 9 12
*/
agi::Ngraph* g= buildEmptyGraph();
agi::lid_t num_verts = numComps;
agi::gid_t* verts = new agi::gid_t[num_verts];
agi::wgt_t* weights = new agi::wgt_t[num_verts];
for (int i=0;i<num_verts;i++) {
verts[i] = PCU_Comm_Self()*numComps+i;
weights[i] = PCU_Comm_Self()*100;
}
g->constructVerts(true,num_verts,verts,weights);
delete [] verts;
delete [] weights;
agi::gid_t num_edges = numComps;
agi::gid_t* edge_ids = new agi::gid_t[num_edges];
agi::lid_t* degs = new agi::lid_t[num_edges];
agi::gid_t* pins_to_verts = new agi::gid_t[num_edges*PCU_Comm_Peers()];
for (int i=0;i<num_edges;i++) {
edge_ids[i] = i;
degs[i] = PCU_Comm_Peers();
for (int j=0;j<PCU_Comm_Peers();j++) {
pins_to_verts[i*PCU_Comm_Peers()+j] = i+j*num_edges;
}
}
g->constructEdges(num_edges,edge_ids,degs,pins_to_verts);
delete [] edge_ids;
delete [] degs;
delete [] pins_to_verts;
std::unordered_map<agi::gid_t,agi::part_t> owns;
for (int i=0;i<num_edges;i++) {
for (int j=0;j<PCU_Comm_Peers();j++) {
if (j!=PCU_Comm_Self())
owns[i+j*num_edges] = j;
}
}
g->constructGhosts(owns);
return g;
}
int testWeightBalancer_1() {
double tol = 1.025;
agi::Ngraph* g = makeArtificialXGCMGraph(1);
double step_factor = .25;
engpar::WeightInput* input = engpar::createWeightInput(g,tol,step_factor,0);
engpar::balanceWeights(input,-1);
//TODO: add balancing checks
agi::checkValidity(g);
agi::destroyGraph(g);
return 0;
}
int testWeightBalancer_4() {
double tol = 1.025;
agi::Ngraph* g = makeArtificialXGCMGraph(4);
double step_factor = .25;
engpar::WeightInput* input = engpar::createWeightInput(g,tol,step_factor,0);
engpar::balanceWeights(input,-1);
//TODO: add balancing checks
agi::checkValidity(g);
agi::destroyGraph(g);
return 0;
}
int testWeightBalancer_100() {
double tol = 1.025;
agi::Ngraph* g = makeArtificialXGCMGraph(100);
double step_factor = .25;
engpar::WeightInput* input = engpar::createWeightInput(g,tol,step_factor,0);
engpar::balanceWeights(input,-1);
//TODO: add balancing checks
agi::checkValidity(g);
agi::destroyGraph(g);
return 0;
}
int testVtxBalancer(agi::Ngraph* g) {
//Create the balancer
engpar::balanceVertices(g, 1.1, .1, -1);
agi::checkValidity(g);
if (engpar::EnGPar_Get_Imbalance(engpar::getWeight(g,-1)) >= 1.11)
return 1;
return 0;
}
int testBalancer(agi::Ngraph* g) {
double step_factor = 0.1;
engpar::DiffusiveInput* input = engpar::createDiffusiveInput(g,step_factor);
for (agi::etype t = 0; t < g->numEdgeTypes(); t++)
input->addPriority(t,1.1);
input->addPriority(-1,1.1);
input->maxIterationsPerType=50;
input->maxIterations=75;
//Create the balancer
engpar::balance(input,1);
//Ensure the graph is still valid
agi::checkValidity(g);
//Ensure the graph was balanced to the target tolerance
for (agi::etype t = 0; t < g->numEdgeTypes(); t++)
if (engpar::EnGPar_Get_Imbalance(engpar::getWeight(g,t)) >= 1.11)
return t+2;
if (engpar::EnGPar_Get_Imbalance(engpar::getWeight(g,-1)) >= 1.11)
return 1;
return 0;
}
int testMultipleBalances(agi::Ngraph* g) {
double step_factor = 0.1;
engpar::Input* input = engpar::createDiffusiveInput(g,step_factor);
input->addPriority(-1,1.1);
//Create the balancer
engpar::balance(input,-1);
//Ensure the graph is still valid
agi::checkValidity(g);
if (engpar::EnGPar_Get_Imbalance(engpar::getWeight(g,-1)) >= 1.11)
return 1;
//Alter weights so odd processes are heavier than even processes
agi::wgt_t* weights = new agi::wgt_t[g->numLocalVtxs()];
agi::wgt_t w = PCU_Comm_Self()%2+1;
for (agi::lid_t i =0;i<g->numLocalVtxs();i++) {
weights[i] = w;
}
g->setWeights(weights);
delete [] weights;
g->resetOwnership();
input = engpar::createDiffusiveInput(g,step_factor);
input->addPriority(-1,1.1);
//Create the balancer
engpar::balance(input,-1);
//Ensure the graph is still valid
agi::checkValidity(g);
if (engpar::EnGPar_Get_Imbalance(engpar::getWeight(g,-1)) >= 1.11)
return 2;
return 0;
}
void switchToOriginals(int split_factor, bool& isOriginal, MPI_Comm& newComm) {
int self = PCU_Comm_Self();
int group;
int groupRank;
isOriginal = self%split_factor==0;
if (isOriginal) {
group=0;
groupRank=self/split_factor;
}
else {
group = 1;
groupRank = 0;
}
MPI_Comm_split(MPI_COMM_WORLD,group,groupRank,&newComm);
}
int testGlobalSplit(agi::Ngraph* g) {
//Application code:
bool isOriginal = g->numLocalVtxs()>0;
MPI_Comm newComm;
int split_factor = 2;
switchToOriginals(split_factor, isOriginal, newComm);
//Switch the internal communicator (this changes PCU so use PCU_Comm_... with caution)
EnGPar_Switch_Comm(newComm);
//Create the input
double tolerance = 1.05;
agi::etype t = 0;
engpar::Input* input = engpar::createGlobalSplitInput(g,newComm,MPI_COMM_WORLD, isOriginal,
tolerance,t);
engpar::split(input,engpar::GLOBAL_PARMETIS);
if (PCU_Get_Comm() != MPI_COMM_WORLD)
return 2;
if (g->numGlobalVtxs() / PCU_Comm_Peers() >= 20 && engpar::EnGPar_Get_Imbalance(engpar::getWeight(g,-1)) >= 1.11)
return 1;
//Application continues:
MPI_Comm_free(&newComm);
return 0;
}
int testLocalSplit(agi::Ngraph* g) {
//Application code:
int split_factor = 2;
bool isOriginal = g->numLocalVtxs()>0;
MPI_Comm newComm;
switchToOriginals(split_factor, isOriginal, newComm);
//Switch the internal communicator (this changes PCU so use PCU_Comm_... with caution)
EnGPar_Switch_Comm(newComm);
//Create the input
double tolerance = 1.05;
agi::etype t = 0;
int my_rank;
MPI_Comm_rank(MPI_COMM_WORLD,&my_rank);
agi::part_t* others = new agi::part_t[split_factor];
for (int i=0;i<split_factor;i++) {
others[i] = my_rank+i;
}
engpar::Input* input = engpar::createLocalSplitInput(g,newComm,MPI_COMM_WORLD, isOriginal,
2,tolerance,others,t);
engpar::split(input,engpar::LOCAL_PARMETIS);
if (PCU_Get_Comm() != MPI_COMM_WORLD)
return 2;
if (g->numGlobalVtxs() / PCU_Comm_Peers() >= 20 && engpar::EnGPar_Get_Imbalance(engpar::getWeight(g,-1)) >= 1.11)
return 1;
//Application continues:
MPI_Comm_free(&newComm);
return 0;
}
int testSplitAndBalance(agi::Ngraph* g) {
int ierr = testGlobalSplit(g);
if (ierr>0)
return ierr;
ierr = testBalancer(g);
if (ierr>0)
return ierr+10;
return 0;
}
<commit_msg>Fix memory leak in local split<commit_after>#include <ngraph.h>
#include <engpar_support.h>
#include <iostream>
#include <PCU.h>
#include <vector>
#include "buildGraphs.h"
#include "gatherGraphs.h"
#include "TestingSuite.h"
#include <engpar.h>
int testVtxBalancer(agi::Ngraph*);
int testBalancer(agi::Ngraph*);
int testMultipleBalances(agi::Ngraph*);
int testWeightBalancer_1();
int testWeightBalancer_4();
int testWeightBalancer_100();
int testGlobalSplit(agi::Ngraph*);
int testLocalSplit(agi::Ngraph*);
int testSplitAndBalance(agi::Ngraph*);
void switchToOriginals(int smallSize, bool& isOriginal, MPI_Comm& newComm);
#define SPLIT_TEST 4
int main(int argc, char* argv[]) {
MPI_Init(&argc,&argv);
EnGPar_Initialize();
if (argc==1) {
if (!PCU_Comm_Self())
EnGPar_Warning_Message("Usage: %s <operation> [trial number]\n"
" operation 0 = vtxBalance\n"
" operation 1 = balance\n"
" operation 2 = balanceMultiple\n"
" operation 3 = balanceWeights\n"
" operation %d = ParMETIS global split\n"
" operation %d = ParMETIS local split\n"
" operation %d = ParMETIS split and balance\n"
,argv[0],SPLIT_TEST,SPLIT_TEST+1,SPLIT_TEST+2);
EnGPar_Finalize();
MPI_Finalize();
return 1;
}
int operation = -1;
if (argc>1)
operation = atoi(argv[1]);
int trial = -1;
if (argc>2)
trial = atoi(argv[2]);
EnGPar_Set_Verbosity(-1);
//Create the testing suite
TestingSuite suite(argv[0]);
//Gather specific tests that have more fine grain checks
if (operation==3) {
suite.addFineTest("Weight Balancer with 1 Component",testWeightBalancer_1);
suite.addFineTest("Weight Balancer with 4 Components",testWeightBalancer_4);
suite.addFineTest("Weight Balancer with 100 Components",testWeightBalancer_100);
}
bool isOriginal = true;
MPI_Comm newComm;
if (operation>=SPLIT_TEST) {
switchToOriginals(2, isOriginal,newComm);
//Switch the internal communicator (this changes PCU so use PCU_Comm_... with caution)
EnGPar_Switch_Comm(newComm);
}
//Gather the graphs for the general tests
if (isOriginal) {
//gatherEBINGraphs(suite);
gatherBGDGraphs(suite);
}
if (operation>=SPLIT_TEST) {
MPI_Comm_free(&newComm);
}
EnGPar_Switch_Comm(MPI_COMM_WORLD);
suite.fillEmptyTestGraphs();
//Gather general tests that run on the graphs collected prior to this
if (operation==0)
suite.addGeneralTest("Vertex Balancer",testVtxBalancer);
else if (operation==1)
suite.addGeneralTest("General Balancer",testBalancer);
else if (operation==2)
suite.addGeneralTest("Balance Twice",testMultipleBalances);
else if (operation == SPLIT_TEST)
suite.addGeneralTest("Global ParMETIS split",testGlobalSplit);
else if (operation == SPLIT_TEST+1)
suite.addGeneralTest("Local ParMETIS split",testLocalSplit);
else if (operation == SPLIT_TEST+2)
suite.addGeneralTest("Global Split and MC Balance",testSplitAndBalance);
//Run the tests and get the number of failures
int ierr = suite.runTests(trial);
suite.deleteTestGraphs();
EnGPar_Finalize();
MPI_Finalize();
return ierr;
}
agi::Ngraph* makeArtificialXGCMGraph(int numComps) {
//Create the graph where each process has 1 vertex per component
// each vertex has weight = PCU_Comm_Self()*100
/* The Ngraph for parts=4, numComps = 3 would be:
numbers=verts, letters = hyperedges
1 4 2 5 3 6
\ / \ / \ /
A B C
/ \ / \ / \
7 10 8 11 9 12
*/
agi::Ngraph* g= buildEmptyGraph();
agi::lid_t num_verts = numComps;
agi::gid_t* verts = new agi::gid_t[num_verts];
agi::wgt_t* weights = new agi::wgt_t[num_verts];
for (int i=0;i<num_verts;i++) {
verts[i] = PCU_Comm_Self()*numComps+i;
weights[i] = PCU_Comm_Self()*100;
}
g->constructVerts(true,num_verts,verts,weights);
delete [] verts;
delete [] weights;
agi::gid_t num_edges = numComps;
agi::gid_t* edge_ids = new agi::gid_t[num_edges];
agi::lid_t* degs = new agi::lid_t[num_edges];
agi::gid_t* pins_to_verts = new agi::gid_t[num_edges*PCU_Comm_Peers()];
for (int i=0;i<num_edges;i++) {
edge_ids[i] = i;
degs[i] = PCU_Comm_Peers();
for (int j=0;j<PCU_Comm_Peers();j++) {
pins_to_verts[i*PCU_Comm_Peers()+j] = i+j*num_edges;
}
}
g->constructEdges(num_edges,edge_ids,degs,pins_to_verts);
delete [] edge_ids;
delete [] degs;
delete [] pins_to_verts;
std::unordered_map<agi::gid_t,agi::part_t> owns;
for (int i=0;i<num_edges;i++) {
for (int j=0;j<PCU_Comm_Peers();j++) {
if (j!=PCU_Comm_Self())
owns[i+j*num_edges] = j;
}
}
g->constructGhosts(owns);
return g;
}
int testWeightBalancer_1() {
double tol = 1.025;
agi::Ngraph* g = makeArtificialXGCMGraph(1);
double step_factor = .25;
engpar::WeightInput* input = engpar::createWeightInput(g,tol,step_factor,0);
engpar::balanceWeights(input,-1);
//TODO: add balancing checks
agi::checkValidity(g);
agi::destroyGraph(g);
return 0;
}
int testWeightBalancer_4() {
double tol = 1.025;
agi::Ngraph* g = makeArtificialXGCMGraph(4);
double step_factor = .25;
engpar::WeightInput* input = engpar::createWeightInput(g,tol,step_factor,0);
engpar::balanceWeights(input,-1);
//TODO: add balancing checks
agi::checkValidity(g);
agi::destroyGraph(g);
return 0;
}
int testWeightBalancer_100() {
double tol = 1.025;
agi::Ngraph* g = makeArtificialXGCMGraph(100);
double step_factor = .25;
engpar::WeightInput* input = engpar::createWeightInput(g,tol,step_factor,0);
engpar::balanceWeights(input,-1);
//TODO: add balancing checks
agi::checkValidity(g);
agi::destroyGraph(g);
return 0;
}
int testVtxBalancer(agi::Ngraph* g) {
//Create the balancer
engpar::balanceVertices(g, 1.1, .1, -1);
agi::checkValidity(g);
if (engpar::EnGPar_Get_Imbalance(engpar::getWeight(g,-1)) >= 1.11)
return 1;
return 0;
}
int testBalancer(agi::Ngraph* g) {
double step_factor = 0.1;
engpar::DiffusiveInput* input = engpar::createDiffusiveInput(g,step_factor);
for (agi::etype t = 0; t < g->numEdgeTypes(); t++)
input->addPriority(t,1.1);
input->addPriority(-1,1.1);
input->maxIterationsPerType=50;
input->maxIterations=75;
//Create the balancer
engpar::balance(input,1);
//Ensure the graph is still valid
agi::checkValidity(g);
//Ensure the graph was balanced to the target tolerance
for (agi::etype t = 0; t < g->numEdgeTypes(); t++)
if (engpar::EnGPar_Get_Imbalance(engpar::getWeight(g,t)) >= 1.11)
return t+2;
if (engpar::EnGPar_Get_Imbalance(engpar::getWeight(g,-1)) >= 1.11)
return 1;
return 0;
}
int testMultipleBalances(agi::Ngraph* g) {
double step_factor = 0.1;
engpar::Input* input = engpar::createDiffusiveInput(g,step_factor);
input->addPriority(-1,1.1);
//Create the balancer
engpar::balance(input,-1);
//Ensure the graph is still valid
agi::checkValidity(g);
if (engpar::EnGPar_Get_Imbalance(engpar::getWeight(g,-1)) >= 1.11)
return 1;
//Alter weights so odd processes are heavier than even processes
agi::wgt_t* weights = new agi::wgt_t[g->numLocalVtxs()];
agi::wgt_t w = PCU_Comm_Self()%2+1;
for (agi::lid_t i =0;i<g->numLocalVtxs();i++) {
weights[i] = w;
}
g->setWeights(weights);
delete [] weights;
g->resetOwnership();
input = engpar::createDiffusiveInput(g,step_factor);
input->addPriority(-1,1.1);
//Create the balancer
engpar::balance(input,-1);
//Ensure the graph is still valid
agi::checkValidity(g);
if (engpar::EnGPar_Get_Imbalance(engpar::getWeight(g,-1)) >= 1.11)
return 2;
return 0;
}
void switchToOriginals(int split_factor, bool& isOriginal, MPI_Comm& newComm) {
int self = PCU_Comm_Self();
int group;
int groupRank;
isOriginal = self%split_factor==0;
if (isOriginal) {
group=0;
groupRank=self/split_factor;
}
else {
group = 1;
groupRank = 0;
}
MPI_Comm_split(MPI_COMM_WORLD,group,groupRank,&newComm);
}
int testGlobalSplit(agi::Ngraph* g) {
//Application code:
bool isOriginal = g->numLocalVtxs()>0;
MPI_Comm newComm;
int split_factor = 2;
switchToOriginals(split_factor, isOriginal, newComm);
//Switch the internal communicator (this changes PCU so use PCU_Comm_... with caution)
EnGPar_Switch_Comm(newComm);
//Create the input
double tolerance = 1.05;
agi::etype t = 0;
engpar::Input* input = engpar::createGlobalSplitInput(g,newComm,MPI_COMM_WORLD, isOriginal,
tolerance,t);
engpar::split(input,engpar::GLOBAL_PARMETIS);
if (PCU_Get_Comm() != MPI_COMM_WORLD)
return 2;
if (g->numGlobalVtxs() / PCU_Comm_Peers() >= 20 && engpar::EnGPar_Get_Imbalance(engpar::getWeight(g,-1)) >= 1.11)
return 1;
//Application continues:
MPI_Comm_free(&newComm);
return 0;
}
int testLocalSplit(agi::Ngraph* g) {
//Application code:
int split_factor = 2;
bool isOriginal = g->numLocalVtxs()>0;
MPI_Comm newComm;
switchToOriginals(split_factor, isOriginal, newComm);
//Switch the internal communicator (this changes PCU so use PCU_Comm_... with caution)
EnGPar_Switch_Comm(newComm);
//Create the input
double tolerance = 1.05;
agi::etype t = 0;
int my_rank;
MPI_Comm_rank(MPI_COMM_WORLD,&my_rank);
agi::part_t* others = new agi::part_t[split_factor];
for (int i=0;i<split_factor;i++) {
others[i] = my_rank+i;
}
engpar::Input* input = engpar::createLocalSplitInput(g,newComm,MPI_COMM_WORLD, isOriginal,
2,tolerance,others,t);
engpar::split(input,engpar::LOCAL_PARMETIS);
delete [] others;
if (PCU_Get_Comm() != MPI_COMM_WORLD)
return 2;
if (g->numGlobalVtxs() / PCU_Comm_Peers() >= 20 && engpar::EnGPar_Get_Imbalance(engpar::getWeight(g,-1)) >= 1.11)
return 1;
//Application continues:
MPI_Comm_free(&newComm);
return 0;
}
int testSplitAndBalance(agi::Ngraph* g) {
int ierr = testGlobalSplit(g);
if (ierr>0)
return ierr;
ierr = testBalancer(g);
if (ierr>0)
return ierr+10;
return 0;
}
<|endoftext|>
|
<commit_before>#ifndef _MSC_VER
#include <catch.hpp>
#include <vector>
#include <mockturtle/algorithms/cleanup.hpp>
#include <mockturtle/algorithms/collapse_mapped.hpp>
#include <mockturtle/algorithms/cut_enumeration.hpp>
#include <mockturtle/algorithms/cut_rewriting.hpp>
#include <mockturtle/algorithms/lut_mapping.hpp>
#include <mockturtle/algorithms/node_resynthesis.hpp>
#include <mockturtle/algorithms/node_resynthesis/akers.hpp>
#include <mockturtle/algorithms/node_resynthesis/mig_npn.hpp>
#include <mockturtle/algorithms/refactoring.hpp>
#include <mockturtle/algorithms/resubstitution.hpp>
#include <mockturtle/io/aiger_reader.hpp>
#include <mockturtle/io/write_bench.hpp>
#include <mockturtle/networks/aig.hpp>
#include <mockturtle/networks/klut.hpp>
#include <mockturtle/networks/mig.hpp>
#include <mockturtle/views/mapping_view.hpp>
#include <fmt/format.h>
#include <lorina/aiger.hpp>
using namespace mockturtle;
template<class Ntk, class Fn, class Ret = std::result_of_t<Fn( Ntk&, int )>>
std::vector<Ret> foreach_benchmark( Fn&& fn )
{
std::vector<Ret> v;
for ( auto const& id : {17, 432, 499, 880, 1355, 1908, 2670, 3540, 5315, 6288, 7552} )
{
Ntk ntk;
lorina::read_aiger( fmt::format( "{}/c{}.aig", BENCHMARKS_PATH, id ), aiger_reader( ntk ) );
v.emplace_back( fn( ntk, id ) );
}
return v;
}
TEST_CASE( "Test quality of cut_enumeration", "[quality]" )
{
const auto v = foreach_benchmark<aig_network>( []( auto& ntk, auto ) {
return cut_enumeration( ntk ).total_cuts();
} );
CHECK( v == std::vector<std::size_t>{{19, 1387, 3154, 1717, 5466, 2362, 4551, 6994, 11849, 34181, 12442}} );
}
TEST_CASE( "Test quality of lut_mapping", "[quality]" )
{
const auto v = foreach_benchmark<aig_network>( []( auto& ntk, auto ) {
mapping_view<aig_network, true> mapped{ntk};
lut_mapping<mapping_view<aig_network, true>, true>( mapped );
return mapped.num_cells();
} );
CHECK( v == std::vector<uint32_t>{{2, 50, 68, 77, 68, 71, 97, 231, 275, 453, 347}} );
}
TEST_CASE( "Test quality of MIG networks", "[quality]" )
{
const auto v = foreach_benchmark<mig_network>( []( auto& ntk, auto ) {
depth_view depth_ntk{ntk};
return std::pair{ntk.num_gates(), depth_ntk.depth()};
} );
CHECK( v == std::vector<std::pair<uint32_t, uint32_t>>{{{6, 3}, // 17
{208, 26}, // 432
{398, 19}, // 499
{325, 25}, // 880
{502, 25}, // 1355
{341, 27}, // 1908
{716, 20}, // 2670
{1024, 41}, // 3540
{1776, 37}, // 5315
{2337, 120}, // 6288
{1469, 26}}} ); // 7552
}
TEST_CASE( "Test quality of node resynthesis with NPN4 resynthesis", "[quality]" )
{
const auto v = foreach_benchmark<mig_network>( []( auto& ntk, auto ) {
mapping_view<mig_network, true> mapped{ntk};
lut_mapping_params ps;
ps.cut_enumeration_ps.cut_size = 4;
lut_mapping<mapping_view<mig_network, true>, true>( mapped, ps );
auto lut = *collapse_mapped_network<klut_network>( mapped );
mig_npn_resynthesis resyn;
auto mig = node_resynthesis<mig_network>( lut, resyn );
return mig.num_gates();
} );
CHECK( v == std::vector<uint32_t>{{7, 176, 316, 300, 316, 299, 502, 929, 1319, 1061, 1418}} );
}
TEST_CASE( "Test quality improvement of cut rewriting with NPN4 resynthesis", "[quality]" )
{
// without zero gain
const auto v = foreach_benchmark<mig_network>( []( auto& ntk, auto ) {
const auto before = ntk.num_gates();
mig_npn_resynthesis resyn;
cut_rewriting_params ps;
ps.cut_enumeration_ps.cut_size = 4;
cut_rewriting( ntk, resyn, ps );
ntk = cleanup_dangling( ntk );
return before - ntk.num_gates();
} );
CHECK( v == std::vector<uint32_t>{{0, 19, 80, 49, 102, 78, 201, 131, 510, 2, 258}} );
// with zero gain
const auto v2 = foreach_benchmark<mig_network>( []( auto& ntk, auto ) {
const auto before = ntk.num_gates();
mig_npn_resynthesis resyn;
cut_rewriting_params ps;
ps.allow_zero_gain = true;
ps.cut_enumeration_ps.cut_size = 4;
cut_rewriting( ntk, resyn, ps );
ntk = cleanup_dangling( ntk );
return before - ntk.num_gates();
} );
CHECK( v2 == std::vector<uint32_t>{{0, 3, 36, 12, 72, 13, 84, 47, 102, 2, 258}} );
}
TEST_CASE( "Test quality improvement of MIG refactoring with Akers resynthesis", "[quality]" )
{
// without zero gain
const auto v = foreach_benchmark<mig_network>( []( auto& ntk, auto ) {
const auto before = ntk.num_gates();
akers_resynthesis resyn;
refactoring( ntk, resyn );
ntk = cleanup_dangling( ntk );
return before - ntk.num_gates();
} );
CHECK( v == std::vector<uint32_t>{{0, 18, 34, 22, 114, 55, 141, 115, 423, 449, 67}} );
// with zero gain
const auto v2 = foreach_benchmark<mig_network>( []( auto& ntk, auto ) {
const auto before = ntk.num_gates();
akers_resynthesis resyn;
refactoring_params ps;
ps.allow_zero_gain = true;
refactoring( ntk, resyn, ps );
ntk = cleanup_dangling( ntk );
return before - ntk.num_gates();
} );
CHECK( v2 == std::vector<uint32_t>{{0, 18, 34, 21, 114, 54, 143, 122, 417, 449, 66}} );
}
TEST_CASE( "Test quality of MIG resubstitution", "[quality]" )
{
const auto v = foreach_benchmark<mig_network>( []( auto& ntk, auto ) {
resubstitution( ntk );
ntk = cleanup_dangling( ntk );
return ntk.num_gates();
} );
CHECK( v == std::vector<uint32_t>{{6, 206, 398, 325, 502, 338, 703, 1015, 1738, 2335, 1467}} );
}
#endif
<commit_msg>quality tests.<commit_after>#ifndef _MSC_VER
#include <catch.hpp>
#include <vector>
#include <mockturtle/algorithms/cleanup.hpp>
#include <mockturtle/algorithms/collapse_mapped.hpp>
#include <mockturtle/algorithms/cut_enumeration.hpp>
#include <mockturtle/algorithms/cut_rewriting.hpp>
#include <mockturtle/algorithms/lut_mapping.hpp>
#include <mockturtle/algorithms/node_resynthesis.hpp>
#include <mockturtle/algorithms/node_resynthesis/akers.hpp>
#include <mockturtle/algorithms/node_resynthesis/mig_npn.hpp>
#include <mockturtle/algorithms/refactoring.hpp>
#include <mockturtle/algorithms/resubstitution.hpp>
#include <mockturtle/io/aiger_reader.hpp>
#include <mockturtle/io/write_bench.hpp>
#include <mockturtle/networks/aig.hpp>
#include <mockturtle/networks/klut.hpp>
#include <mockturtle/networks/mig.hpp>
#include <mockturtle/views/mapping_view.hpp>
#include <fmt/format.h>
#include <lorina/aiger.hpp>
using namespace mockturtle;
template<class Ntk, class Fn, class Ret = std::result_of_t<Fn( Ntk&, int )>>
std::vector<Ret> foreach_benchmark( Fn&& fn )
{
std::vector<Ret> v;
for ( auto const& id : {17, 432, 499, 880, 1355, 1908, 2670, 3540, 5315, 6288, 7552} )
{
Ntk ntk;
lorina::read_aiger( fmt::format( "{}/c{}.aig", BENCHMARKS_PATH, id ), aiger_reader( ntk ) );
v.emplace_back( fn( ntk, id ) );
}
return v;
}
TEST_CASE( "Test quality of cut_enumeration", "[quality]" )
{
const auto v = foreach_benchmark<aig_network>( []( auto& ntk, auto ) {
return cut_enumeration( ntk ).total_cuts();
} );
CHECK( v == std::vector<std::size_t>{{19, 1387, 3154, 1717, 5466, 2362, 4551, 6994, 11849, 34181, 12442}} );
}
TEST_CASE( "Test quality of lut_mapping", "[quality]" )
{
const auto v = foreach_benchmark<aig_network>( []( auto& ntk, auto ) {
mapping_view<aig_network, true> mapped{ntk};
lut_mapping<mapping_view<aig_network, true>, true>( mapped );
return mapped.num_cells();
} );
CHECK( v == std::vector<uint32_t>{{2, 50, 68, 77, 68, 71, 97, 231, 275, 453, 347}} );
}
TEST_CASE( "Test quality of MIG networks", "[quality]" )
{
const auto v = foreach_benchmark<mig_network>( []( auto& ntk, auto ) {
depth_view depth_ntk{ntk};
return std::pair{ntk.num_gates(), depth_ntk.depth()};
} );
CHECK( v == std::vector<std::pair<uint32_t, uint32_t>>{{{6, 3}, // 17
{208, 26}, // 432
{398, 19}, // 499
{325, 25}, // 880
{502, 25}, // 1355
{341, 27}, // 1908
{716, 20}, // 2670
{1024, 41}, // 3540
{1776, 37}, // 5315
{2337, 120}, // 6288
{1469, 26}}} ); // 7552
}
TEST_CASE( "Test quality of node resynthesis with NPN4 resynthesis", "[quality]" )
{
const auto v = foreach_benchmark<mig_network>( []( auto& ntk, auto ) {
mapping_view<mig_network, true> mapped{ntk};
lut_mapping_params ps;
ps.cut_enumeration_ps.cut_size = 4;
lut_mapping<mapping_view<mig_network, true>, true>( mapped, ps );
auto lut = *collapse_mapped_network<klut_network>( mapped );
mig_npn_resynthesis resyn;
auto mig = node_resynthesis<mig_network>( lut, resyn );
return mig.num_gates();
} );
CHECK( v == std::vector<uint32_t>{{7, 176, 316, 300, 316, 299, 502, 929, 1319, 1061, 1418}} );
}
TEST_CASE( "Test quality improvement of cut rewriting with NPN4 resynthesis", "[quality]" )
{
// without zero gain
const auto v = foreach_benchmark<mig_network>( []( auto& ntk, auto ) {
const auto before = ntk.num_gates();
mig_npn_resynthesis resyn;
cut_rewriting_params ps;
ps.cut_enumeration_ps.cut_size = 4;
cut_rewriting( ntk, resyn, ps );
ntk = cleanup_dangling( ntk );
return before - ntk.num_gates();
} );
CHECK( v == std::vector<uint32_t>{{0, 19, 80, 49, 98, 80, 200, 131, 507, 2, 258}} );
// with zero gain
const auto v2 = foreach_benchmark<mig_network>( []( auto& ntk, auto ) {
const auto before = ntk.num_gates();
mig_npn_resynthesis resyn;
cut_rewriting_params ps;
ps.allow_zero_gain = true;
ps.cut_enumeration_ps.cut_size = 4;
cut_rewriting( ntk, resyn, ps );
ntk = cleanup_dangling( ntk );
return before - ntk.num_gates();
} );
CHECK( v2 == std::vector<uint32_t>{{0, 3, 36, 12, 55, 10, 86, 40, 107, 2, 46}} );
}
TEST_CASE( "Test quality improvement of MIG refactoring with Akers resynthesis", "[quality]" )
{
// without zero gain
const auto v = foreach_benchmark<mig_network>( []( auto& ntk, auto ) {
const auto before = ntk.num_gates();
akers_resynthesis resyn;
refactoring( ntk, resyn );
ntk = cleanup_dangling( ntk );
return before - ntk.num_gates();
} );
CHECK( v == std::vector<uint32_t>{{0, 18, 34, 22, 114, 55, 141, 115, 423, 449, 67}} );
// with zero gain
const auto v2 = foreach_benchmark<mig_network>( []( auto& ntk, auto ) {
const auto before = ntk.num_gates();
akers_resynthesis resyn;
refactoring_params ps;
ps.allow_zero_gain = true;
refactoring( ntk, resyn, ps );
ntk = cleanup_dangling( ntk );
return before - ntk.num_gates();
} );
CHECK( v2 == std::vector<uint32_t>{{0, 18, 34, 21, 114, 54, 143, 122, 417, 449, 66}} );
}
TEST_CASE( "Test quality of MIG resubstitution", "[quality]" )
{
const auto v = foreach_benchmark<mig_network>( []( auto& ntk, auto ) {
resubstitution( ntk );
ntk = cleanup_dangling( ntk );
return ntk.num_gates();
} );
CHECK( v == std::vector<uint32_t>{{6, 208, 398, 317, 502, 333, 704, 1007, 1741, 2322, 1460}} );
}
#endif
<|endoftext|>
|
<commit_before>// Example command line to build on Android ARM64:
/*
~/android/toolchains/r15c-aarch64/bin/aarch64-linux-android-clang++ \
test/benchmark_all_sizes.cc -o /tmp/b -O3 --std=c++11 -fPIE -static \
-DBENCHMARK_QUICK -DBENCHMARK_8bit
*/
#include <algorithm>
#include <cmath>
#include <cstdint>
#include <ctime>
#include <iostream>
#include <map>
#include <random>
#include <set>
#include "../public/gemmlowp.h"
// Minimum duration of each benchmark measurement. Also, duration
// of sleep time between each two consecutive benchmark measurements to
// prevent over-heating.
const double kBenchmarkSecs = 0.1;
// Sleep time before each benchmark.
const int kCooldownBeforeBenchmarkSecs = 0;
// Number of benchmark passes.
const int kPasses = 4;
#ifdef BENCHMARK_NUM_THREADS
const int kNumThreads = BENCHMARK_NUM_THREADS;
#else
const int kNumThreads = 1;
#endif
double time() {
timespec t;
clock_gettime(CLOCK_REALTIME, &t);
return t.tv_sec + 1e-9 * t.tv_nsec;
}
namespace gemmlowp {
// gemmlowp itself doesn't have a Matrix class, only a MatrixMap class,
// since it only maps existing data. In tests though, we need to
// create our own matrices.
template <typename tScalar, MapOrder tOrder>
class Matrix : public MatrixMap<tScalar, tOrder> {
public:
typedef MatrixMap<tScalar, tOrder> Map;
typedef MatrixMap<const tScalar, tOrder> ConstMap;
typedef typename Map::Scalar Scalar;
static const MapOrder Order = tOrder;
using Map::cols_;
using Map::data_;
using Map::kOrder;
using Map::rows_;
using Map::stride_;
public:
Matrix() : Map(nullptr, 0, 0, 0) {}
Matrix(int rows, int cols) : Map(nullptr, 0, 0, 0) { Resize(rows, cols); }
Matrix(const Matrix& other) : Map(nullptr, 0, 0, 0) { *this = other; }
Matrix& operator=(const Matrix& other) {
Resize(other.rows_, other.cols_);
std::memcpy(data_, other.data_, size() * sizeof(Scalar));
return *this;
}
friend bool operator==(const Matrix& a, const Matrix& b) {
return a.rows_ == b.rows_ && a.cols_ == b.cols_ &&
!std::memcmp(a.data_, b.data_, a.size());
}
void Resize(int rows, int cols) {
rows_ = rows;
cols_ = cols;
stride_ = kOrder == MapOrder::ColMajor ? rows : cols;
storage.resize(size());
data_ = storage.data();
}
int size() const { return rows_ * cols_; }
Map& map() { return *static_cast<Map*>(this); }
ConstMap const_map() const { return ConstMap(data_, rows_, cols_, stride_); }
protected:
std::vector<Scalar> storage;
};
template <typename MatrixType>
void MakeZero(MatrixType* m) {
for (int c = 0; c < m->cols(); c++) {
for (int r = 0; r < m->rows(); r++) {
(*m)(r, c) = 128;
}
}
}
} // end namespace gemmlowp
template <typename BitDepthParams>
float benchmark_8bit(int rows, int depth, int cols) {
using namespace gemmlowp;
typedef Matrix<std::uint8_t, MapOrder::RowMajor> LhsType;
typedef Matrix<std::uint8_t, MapOrder::ColMajor> RhsType;
typedef Matrix<std::uint8_t, MapOrder::ColMajor> ResultType;
LhsType lhs;
RhsType rhs;
ResultType result;
lhs.Resize(rows, depth);
rhs.Resize(depth, cols);
result.Resize(rows, cols);
MakeZero(&lhs);
MakeZero(&rhs);
MakeZero(&result);
typedef std::tuple<OutputStageQuantizeDownInt32ToUint8ScaleByFixedPoint,
OutputStageSaturatingCastToUint8>
Pipeline;
gemmlowp::OutputStageQuantizeDownInt32ToUint8ScaleByFixedPoint
quantize_down_stage;
quantize_down_stage.result_offset_after_shift = 128;
quantize_down_stage.result_fixedpoint_multiplier = 1234567890;
quantize_down_stage.result_shift = 16;
gemmlowp::OutputStageSaturatingCastToUint8 saturating_cast_stage;
const auto output_pipeline =
std::make_tuple(quantize_down_stage, saturating_cast_stage);
GemmContext gemm_context;
gemm_context.set_max_num_threads(kNumThreads);
gemmlowp::GemmWithOutputPipeline<std::uint8_t, std::uint8_t, BitDepthParams>(
&gemm_context, lhs.const_map(), rhs.const_map(), &result.map(), -128,
-128, output_pipeline);
double time_start = time();
double t = time_start;
int iters = 0;
int iters_at_a_time = 1;
while (t - time_start < kBenchmarkSecs) {
for (int i = 0; i < iters_at_a_time; i++) {
gemmlowp::GemmWithOutputPipeline<std::uint8_t, std::uint8_t,
BitDepthParams>(
&gemm_context, lhs.const_map(), rhs.const_map(), &result.map(), -128,
-128, output_pipeline);
iters++;
}
iters_at_a_time *= 2;
t = time();
}
return (t - time_start) / iters;
}
template <typename BitDepthParams>
float benchmark_8bit_to_32bit(int rows, int depth, int cols) {
using namespace gemmlowp;
typedef Matrix<std::uint8_t, MapOrder::RowMajor> LhsType;
typedef Matrix<std::uint8_t, MapOrder::ColMajor> RhsType;
typedef Matrix<std::int32_t, MapOrder::ColMajor> ResultType;
LhsType lhs;
RhsType rhs;
ResultType result;
lhs.Resize(rows, depth);
rhs.Resize(depth, cols);
result.Resize(rows, cols);
MakeZero(&lhs);
MakeZero(&rhs);
MakeZero(&result);
typedef std::tuple<> EmptyPipeline;
GemmContext gemm_context;
gemm_context.set_max_num_threads(kNumThreads);
gemmlowp::GemmWithOutputPipeline<std::uint8_t, std::int32_t, BitDepthParams>(
&gemm_context, lhs.const_map(), rhs.const_map(), &result.map(), -128,
-128, EmptyPipeline());
double time_start = time();
double t = time_start;
int iters = 0;
int iters_at_a_time = 1;
while (t - time_start < kBenchmarkSecs) {
for (int i = 0; i < iters_at_a_time; i++) {
gemmlowp::GemmWithOutputPipeline<std::uint8_t, std::int32_t,
BitDepthParams>(
&gemm_context, lhs.const_map(), rhs.const_map(), &result.map(), -128,
-128, EmptyPipeline());
iters++;
}
iters_at_a_time *= 2;
t = time();
}
return (t - time_start) / iters;
}
struct Shape {
int rows;
int depth;
int cols;
};
bool operator==(const Shape& s1, const Shape& s2) {
return s1.rows == s2.rows && s1.depth == s2.depth && s1.cols == s2.cols;
}
bool operator<(const Shape& shape1, const Shape& shape2) {
return shape1.depth < shape2.depth ||
(shape1.depth == shape2.depth &&
(shape1.rows < shape2.rows ||
(shape1.rows == shape2.rows && shape1.cols < shape2.cols)));
};
float benchmark(const Shape& shape) {
if (kCooldownBeforeBenchmarkSecs) {
sleep(kCooldownBeforeBenchmarkSecs);
}
#if defined BENCHMARK_8bit
// Benchmark the fast 8bit path, using L8R8WithLhsNonzeroBitDepthParams.
// This is the recommended thing to default to: it's what most applications
// want to use, as it's the fastest.
// The contract is that LHS must take values in [1, 255], while RHS can take
// any value in [0, 255].
return benchmark_8bit<gemmlowp::L8R8WithLhsNonzeroBitDepthParams>(
shape.rows, shape.depth, shape.cols);
#elif defined BENCHMARK_8bit_wide
// Variant benchmarking the slower (mostly legacy) DefaultL8R8BitDepthParams.
// The only contract difference is that both LHS and RHS can take values in
// [0, 255].
return benchmark_8bit<gemmlowp::DefaultL8R8BitDepthParams>(
shape.rows, shape.depth, shape.cols);
#elif defined BENCHMARK_8bit_to_32bit
// Variant of BENCHMARK_8bit where the user asks for getting raw int32
// accumulators, instead of a 8bit-downscaled result.
return benchmark_8bit_to_32bit<gemmlowp::L8R8WithLhsNonzeroBitDepthParams>(
shape.rows, shape.depth, shape.cols);
#elif defined BENCHMARK_8bit_to_32bit_wide
// Variant of BENCHMARK_8bit_wide where the user asks for getting raw int32
// accumulators, instead of a 8bit-downscaled result.
return benchmark_8bit_to_32bit<gemmlowp::DefaultL8R8BitDepthParams>(
shape.rows, shape.depth, shape.cols);
#elif defined BENCHMARK_float
return benchmark_float(shape.rows, shape.depth, shape.cols);
#else
#error What arithmetic path should we benchmark? (Suggestion: #define BENCHMARK_8bit)
#endif
}
std::set<int> all_sizes() {
std::set<int> sizes;
for (int i = 1; i <= 2048; i *= 2) {
sizes.insert(i);
}
for (double x = 8; x <= 2048; x *= std::sqrt(2.)) {
sizes.insert(static_cast<int>(std::round(x)));
}
for (double x = 16; x <= 512; x *= std::pow(2., 1. / 4.)) {
sizes.insert(static_cast<int>(std::round(x)));
}
return sizes;
}
std::mt19937& RandomEngine() {
static std::mt19937 engine;
return engine;
}
std::vector<Shape> all_shapes_in_random_order() {
std::vector<Shape> shapes;
const std::set<int> sizes = all_sizes();
#if defined BENCHMARK_ROWS
// Benchmark one specific shape
Shape shape;
shape.rows = BENCHMARK_ROWS;
shape.depth = BENCHMARK_DEPTH;
shape.cols = BENCHMARK_COLS;
shapes.push_back(shape);
#elif defined BENCHMARK_QUICK
// Benchmark an assortment of cubic shapes
for (int size : sizes) {
Shape shape;
shape.rows = size;
shape.depth = size;
shape.cols = size;
shapes.push_back(shape);
}
#elif defined BENCHMARK_EXHAUSTIVE
// Benchmark all sorts of shapes
for (int rows : sizes) {
for (int depth : sizes) {
for (int cols : sizes) {
Shape shape;
shape.rows = rows;
shape.depth = depth;
shape.cols = cols;
shapes.push_back(shape);
}
}
}
#else
#error What shapes should we benchmark? (Suggestion: #define BENCHMARK_QUICK)
#endif
std::shuffle(std::begin(shapes), std::end(shapes), RandomEngine());
return shapes;
}
void run_benchmarks(std::map<Shape, float>* results) {
std::vector<Shape> shapes;
for (int pass = 0; pass < kPasses; pass++) {
const std::vector<Shape> pass_shapes = all_shapes_in_random_order();
shapes.insert(std::end(shapes), std::begin(pass_shapes),
std::end(pass_shapes));
}
const double time_start = time();
for (std::size_t i = 0; i < shapes.size(); i++) {
const double ratio = static_cast<double>(i) / shapes.size();
const double elapsed = time() - time_start;
const double elapsed_hours = elapsed / 3600.;
const double eta_hours = elapsed_hours * (1. - ratio) / ratio;
fprintf(stderr,
"Benchmarking: %.2f%% done, Elapsed: %.2f hours, ETA: %.2f "
"hours... \r",
100. * ratio, elapsed_hours, eta_hours);
fflush(stderr);
const Shape& shape = shapes[i];
float latency = benchmark(shape);
if (results->count(shape)) {
(*results)[shape] = std::min(latency, (*results)[shape]);
} else {
(*results)[shape] = latency;
}
}
fprintf(stderr, "\n");
}
int main() {
std::map<Shape, float> results;
run_benchmarks(&results);
printf("Using %d thread(s)\n", kNumThreads);
printf("depth,rows,cols,latency(s),Gop/s\n");
for (const auto& result : results) {
const Shape& shape = result.first;
printf("%d,%d,%d,%.4g,%.4g\n", shape.depth, shape.rows, shape.cols,
result.second,
2e-9 * shape.depth * shape.rows * shape.cols / result.second);
}
}
<commit_msg>Build on Android ARM 32bit toolchains<commit_after>// Example command line to build on Android ARM64:
/*
~/android/toolchains/r15c-aarch64/bin/aarch64-linux-android-clang++ \
test/benchmark_all_sizes.cc -o /tmp/b -O3 --std=c++11 -fPIE -static \
-DBENCHMARK_QUICK -DBENCHMARK_8bit
*/
#include <algorithm>
#include <cmath>
#include <cstdint>
#include <ctime>
#include <iostream>
#include <map>
#include <random>
#include <set>
#include "../public/gemmlowp.h"
#if defined GEMMLOWP_ANDROID && defined GEMMLOWP_ARM_32
// Compilation workaround
namespace std {
using ::round;
}
#endif
// Minimum duration of each benchmark measurement. Also, duration
// of sleep time between each two consecutive benchmark measurements to
// prevent over-heating.
const double kBenchmarkSecs = 0.1;
// Sleep time before each benchmark.
const int kCooldownBeforeBenchmarkSecs = 0;
// Number of benchmark passes.
const int kPasses = 4;
#ifdef BENCHMARK_NUM_THREADS
const int kNumThreads = BENCHMARK_NUM_THREADS;
#else
const int kNumThreads = 1;
#endif
double time() {
timespec t;
clock_gettime(CLOCK_REALTIME, &t);
return t.tv_sec + 1e-9 * t.tv_nsec;
}
namespace gemmlowp {
// gemmlowp itself doesn't have a Matrix class, only a MatrixMap class,
// since it only maps existing data. In tests though, we need to
// create our own matrices.
template <typename tScalar, MapOrder tOrder>
class Matrix : public MatrixMap<tScalar, tOrder> {
public:
typedef MatrixMap<tScalar, tOrder> Map;
typedef MatrixMap<const tScalar, tOrder> ConstMap;
typedef typename Map::Scalar Scalar;
static const MapOrder Order = tOrder;
using Map::cols_;
using Map::data_;
using Map::kOrder;
using Map::rows_;
using Map::stride_;
public:
Matrix() : Map(nullptr, 0, 0, 0) {}
Matrix(int rows, int cols) : Map(nullptr, 0, 0, 0) { Resize(rows, cols); }
Matrix(const Matrix& other) : Map(nullptr, 0, 0, 0) { *this = other; }
Matrix& operator=(const Matrix& other) {
Resize(other.rows_, other.cols_);
std::memcpy(data_, other.data_, size() * sizeof(Scalar));
return *this;
}
friend bool operator==(const Matrix& a, const Matrix& b) {
return a.rows_ == b.rows_ && a.cols_ == b.cols_ &&
!std::memcmp(a.data_, b.data_, a.size());
}
void Resize(int rows, int cols) {
rows_ = rows;
cols_ = cols;
stride_ = kOrder == MapOrder::ColMajor ? rows : cols;
storage.resize(size());
data_ = storage.data();
}
int size() const { return rows_ * cols_; }
Map& map() { return *static_cast<Map*>(this); }
ConstMap const_map() const { return ConstMap(data_, rows_, cols_, stride_); }
protected:
std::vector<Scalar> storage;
};
template <typename MatrixType>
void MakeZero(MatrixType* m) {
for (int c = 0; c < m->cols(); c++) {
for (int r = 0; r < m->rows(); r++) {
(*m)(r, c) = 128;
}
}
}
} // end namespace gemmlowp
template <typename BitDepthParams>
float benchmark_8bit(int rows, int depth, int cols) {
using namespace gemmlowp;
typedef Matrix<std::uint8_t, MapOrder::RowMajor> LhsType;
typedef Matrix<std::uint8_t, MapOrder::ColMajor> RhsType;
typedef Matrix<std::uint8_t, MapOrder::ColMajor> ResultType;
LhsType lhs;
RhsType rhs;
ResultType result;
lhs.Resize(rows, depth);
rhs.Resize(depth, cols);
result.Resize(rows, cols);
MakeZero(&lhs);
MakeZero(&rhs);
MakeZero(&result);
typedef std::tuple<OutputStageQuantizeDownInt32ToUint8ScaleByFixedPoint,
OutputStageSaturatingCastToUint8>
Pipeline;
gemmlowp::OutputStageQuantizeDownInt32ToUint8ScaleByFixedPoint
quantize_down_stage;
quantize_down_stage.result_offset_after_shift = 128;
quantize_down_stage.result_fixedpoint_multiplier = 1234567890;
quantize_down_stage.result_shift = 16;
gemmlowp::OutputStageSaturatingCastToUint8 saturating_cast_stage;
const auto output_pipeline =
std::make_tuple(quantize_down_stage, saturating_cast_stage);
GemmContext gemm_context;
gemm_context.set_max_num_threads(kNumThreads);
gemmlowp::GemmWithOutputPipeline<std::uint8_t, std::uint8_t, BitDepthParams>(
&gemm_context, lhs.const_map(), rhs.const_map(), &result.map(), -128,
-128, output_pipeline);
double time_start = time();
double t = time_start;
int iters = 0;
int iters_at_a_time = 1;
while (t - time_start < kBenchmarkSecs) {
for (int i = 0; i < iters_at_a_time; i++) {
gemmlowp::GemmWithOutputPipeline<std::uint8_t, std::uint8_t,
BitDepthParams>(
&gemm_context, lhs.const_map(), rhs.const_map(), &result.map(), -128,
-128, output_pipeline);
iters++;
}
iters_at_a_time *= 2;
t = time();
}
return (t - time_start) / iters;
}
template <typename BitDepthParams>
float benchmark_8bit_to_32bit(int rows, int depth, int cols) {
using namespace gemmlowp;
typedef Matrix<std::uint8_t, MapOrder::RowMajor> LhsType;
typedef Matrix<std::uint8_t, MapOrder::ColMajor> RhsType;
typedef Matrix<std::int32_t, MapOrder::ColMajor> ResultType;
LhsType lhs;
RhsType rhs;
ResultType result;
lhs.Resize(rows, depth);
rhs.Resize(depth, cols);
result.Resize(rows, cols);
MakeZero(&lhs);
MakeZero(&rhs);
MakeZero(&result);
typedef std::tuple<> EmptyPipeline;
GemmContext gemm_context;
gemm_context.set_max_num_threads(kNumThreads);
gemmlowp::GemmWithOutputPipeline<std::uint8_t, std::int32_t, BitDepthParams>(
&gemm_context, lhs.const_map(), rhs.const_map(), &result.map(), -128,
-128, EmptyPipeline());
double time_start = time();
double t = time_start;
int iters = 0;
int iters_at_a_time = 1;
while (t - time_start < kBenchmarkSecs) {
for (int i = 0; i < iters_at_a_time; i++) {
gemmlowp::GemmWithOutputPipeline<std::uint8_t, std::int32_t,
BitDepthParams>(
&gemm_context, lhs.const_map(), rhs.const_map(), &result.map(), -128,
-128, EmptyPipeline());
iters++;
}
iters_at_a_time *= 2;
t = time();
}
return (t - time_start) / iters;
}
struct Shape {
int rows;
int depth;
int cols;
};
bool operator==(const Shape& s1, const Shape& s2) {
return s1.rows == s2.rows && s1.depth == s2.depth && s1.cols == s2.cols;
}
bool operator<(const Shape& shape1, const Shape& shape2) {
return shape1.depth < shape2.depth ||
(shape1.depth == shape2.depth &&
(shape1.rows < shape2.rows ||
(shape1.rows == shape2.rows && shape1.cols < shape2.cols)));
};
float benchmark(const Shape& shape) {
if (kCooldownBeforeBenchmarkSecs) {
sleep(kCooldownBeforeBenchmarkSecs);
}
#if defined BENCHMARK_8bit
// Benchmark the fast 8bit path, using L8R8WithLhsNonzeroBitDepthParams.
// This is the recommended thing to default to: it's what most applications
// want to use, as it's the fastest.
// The contract is that LHS must take values in [1, 255], while RHS can take
// any value in [0, 255].
return benchmark_8bit<gemmlowp::L8R8WithLhsNonzeroBitDepthParams>(
shape.rows, shape.depth, shape.cols);
#elif defined BENCHMARK_8bit_wide
// Variant benchmarking the slower (mostly legacy) DefaultL8R8BitDepthParams.
// The only contract difference is that both LHS and RHS can take values in
// [0, 255].
return benchmark_8bit<gemmlowp::DefaultL8R8BitDepthParams>(
shape.rows, shape.depth, shape.cols);
#elif defined BENCHMARK_8bit_to_32bit
// Variant of BENCHMARK_8bit where the user asks for getting raw int32
// accumulators, instead of a 8bit-downscaled result.
return benchmark_8bit_to_32bit<gemmlowp::L8R8WithLhsNonzeroBitDepthParams>(
shape.rows, shape.depth, shape.cols);
#elif defined BENCHMARK_8bit_to_32bit_wide
// Variant of BENCHMARK_8bit_wide where the user asks for getting raw int32
// accumulators, instead of a 8bit-downscaled result.
return benchmark_8bit_to_32bit<gemmlowp::DefaultL8R8BitDepthParams>(
shape.rows, shape.depth, shape.cols);
#elif defined BENCHMARK_float
return benchmark_float(shape.rows, shape.depth, shape.cols);
#else
#error What arithmetic path should we benchmark? (Suggestion: #define BENCHMARK_8bit)
#endif
}
std::set<int> all_sizes() {
std::set<int> sizes;
for (int i = 1; i <= 2048; i *= 2) {
sizes.insert(i);
}
for (double x = 8; x <= 2048; x *= std::sqrt(2.)) {
sizes.insert(static_cast<int>(std::round(x)));
}
for (double x = 16; x <= 512; x *= std::pow(2., 1. / 4.)) {
sizes.insert(static_cast<int>(std::round(x)));
}
return sizes;
}
std::mt19937& RandomEngine() {
static std::mt19937 engine;
return engine;
}
std::vector<Shape> all_shapes_in_random_order() {
std::vector<Shape> shapes;
const std::set<int> sizes = all_sizes();
#if defined BENCHMARK_ROWS
// Benchmark one specific shape
Shape shape;
shape.rows = BENCHMARK_ROWS;
shape.depth = BENCHMARK_DEPTH;
shape.cols = BENCHMARK_COLS;
shapes.push_back(shape);
#elif defined BENCHMARK_QUICK
// Benchmark an assortment of cubic shapes
for (int size : sizes) {
Shape shape;
shape.rows = size;
shape.depth = size;
shape.cols = size;
shapes.push_back(shape);
}
#elif defined BENCHMARK_EXHAUSTIVE
// Benchmark all sorts of shapes
for (int rows : sizes) {
for (int depth : sizes) {
for (int cols : sizes) {
Shape shape;
shape.rows = rows;
shape.depth = depth;
shape.cols = cols;
shapes.push_back(shape);
}
}
}
#else
#error What shapes should we benchmark? (Suggestion: #define BENCHMARK_QUICK)
#endif
std::shuffle(std::begin(shapes), std::end(shapes), RandomEngine());
return shapes;
}
void run_benchmarks(std::map<Shape, float>* results) {
std::vector<Shape> shapes;
for (int pass = 0; pass < kPasses; pass++) {
const std::vector<Shape> pass_shapes = all_shapes_in_random_order();
shapes.insert(std::end(shapes), std::begin(pass_shapes),
std::end(pass_shapes));
}
const double time_start = time();
for (std::size_t i = 0; i < shapes.size(); i++) {
const double ratio = static_cast<double>(i) / shapes.size();
const double elapsed = time() - time_start;
const double elapsed_hours = elapsed / 3600.;
const double eta_hours = elapsed_hours * (1. - ratio) / ratio;
fprintf(stderr,
"Benchmarking: %.2f%% done, Elapsed: %.2f hours, ETA: %.2f "
"hours... \r",
100. * ratio, elapsed_hours, eta_hours);
fflush(stderr);
const Shape& shape = shapes[i];
float latency = benchmark(shape);
if (results->count(shape)) {
(*results)[shape] = std::min(latency, (*results)[shape]);
} else {
(*results)[shape] = latency;
}
}
fprintf(stderr, "\n");
}
int main() {
std::map<Shape, float> results;
run_benchmarks(&results);
printf("Using %d thread(s)\n", kNumThreads);
printf("depth,rows,cols,latency(s),Gop/s\n");
for (const auto& result : results) {
const Shape& shape = result.first;
printf("%d,%d,%d,%.4g,%.4g\n", shape.depth, shape.rows, shape.cols,
result.second,
2e-9 * shape.depth * shape.rows * shape.cols / result.second);
}
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: AGroups.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: oj $ $Date: 2001-11-09 07:05:38 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _CONNECTIVITY_ADO_GROUPS_HXX_
#include "ado/AGroups.hxx"
#endif
#ifndef _CONNECTIVITY_ADO_GROUP_HXX_
#include "ado/AGroup.hxx"
#endif
#ifndef _CONNECTIVITY_ADO_TABLE_HXX_
#include "ado/ATable.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBC_XROW_HPP_
#include <com/sun/star/sdbc/XRow.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_
#include <com/sun/star/sdbc/XResultSet.hpp>
#endif
#ifndef _CONNECTIVITY_SDBCX_IREFRESHABLE_HXX_
#include "connectivity/sdbcx/IRefreshable.hxx"
#endif
#ifndef CONNECTIVITY_CONNECTION_HXX
#include "TConnection.hxx"
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif
using namespace comphelper;
using namespace connectivity::ado;
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::beans;
using namespace com::sun::star::sdbc;
using namespace com::sun::star::container;
typedef connectivity::sdbcx::OCollection OCollection_TYPE;
// -------------------------------------------------------------------------
Reference< XNamed > OGroups::createObject(const ::rtl::OUString& _rName)
{
return new OAdoGroup(m_pCatalog,isCaseSensitive(),_rName);
}
// -------------------------------------------------------------------------
void OGroups::impl_refresh() throw(RuntimeException)
{
m_aCollection.Refresh();
}
// -------------------------------------------------------------------------
Reference< XPropertySet > OGroups::createEmptyObject()
{
return new OAdoGroup(m_pCatalog,isCaseSensitive());
}
// -------------------------------------------------------------------------
// XAppend
void OGroups::appendObject( const Reference< XPropertySet >& descriptor )
{
OAdoGroup* pGroup = NULL;
if(getImplementation(pGroup,descriptor) && pGroup != NULL)
m_aCollection.Append(pGroup->getImpl());
}
// -------------------------------------------------------------------------
// XDrop
void OGroups::dropObject(sal_Int32 _nPos,const ::rtl::OUString _sElementName)
{
m_aCollection.Delete(_sElementName);
}
// -----------------------------------------------------------------------------
Reference< XNamed > OGroups::cloneObject(const Reference< XPropertySet >& _xDescriptor)
{
Reference< XNamed > xName(_xDescriptor,UNO_QUERY);
OSL_ENSURE(xName.is(),"Must be a XName interface here !");
return xName.is() ? createObject(xName->getName()) : Reference< XNamed >();
}
// -----------------------------------------------------------------------------
<commit_msg>INTEGRATION: CWS dba24 (1.6.260); FILE MERGED 2005/02/09 08:07:39 oj 1.6.260.1: #i26950# remove the need for XNamed<commit_after>/*************************************************************************
*
* $RCSfile: AGroups.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: vg $ $Date: 2005-03-10 15:22:38 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _CONNECTIVITY_ADO_GROUPS_HXX_
#include "ado/AGroups.hxx"
#endif
#ifndef _CONNECTIVITY_ADO_GROUP_HXX_
#include "ado/AGroup.hxx"
#endif
#ifndef _CONNECTIVITY_ADO_TABLE_HXX_
#include "ado/ATable.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBC_XROW_HPP_
#include <com/sun/star/sdbc/XRow.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_
#include <com/sun/star/sdbc/XResultSet.hpp>
#endif
#ifndef _CONNECTIVITY_SDBCX_IREFRESHABLE_HXX_
#include "connectivity/sdbcx/IRefreshable.hxx"
#endif
#ifndef CONNECTIVITY_CONNECTION_HXX
#include "TConnection.hxx"
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif
using namespace comphelper;
using namespace connectivity;
using namespace connectivity::ado;
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::beans;
using namespace com::sun::star::sdbc;
using namespace com::sun::star::container;
typedef connectivity::sdbcx::OCollection OCollection_TYPE;
// -------------------------------------------------------------------------
sdbcx::ObjectType OGroups::createObject(const ::rtl::OUString& _rName)
{
return new OAdoGroup(m_pCatalog,isCaseSensitive(),_rName);
}
// -------------------------------------------------------------------------
void OGroups::impl_refresh() throw(RuntimeException)
{
m_aCollection.Refresh();
}
// -------------------------------------------------------------------------
Reference< XPropertySet > OGroups::createEmptyObject()
{
return new OAdoGroup(m_pCatalog,isCaseSensitive());
}
// -------------------------------------------------------------------------
// XAppend
void OGroups::appendObject( const Reference< XPropertySet >& descriptor )
{
OAdoGroup* pGroup = NULL;
if(getImplementation(pGroup,descriptor) && pGroup != NULL)
m_aCollection.Append(pGroup->getImpl());
}
// -------------------------------------------------------------------------
// XDrop
void OGroups::dropObject(sal_Int32 _nPos,const ::rtl::OUString _sElementName)
{
m_aCollection.Delete(_sElementName);
}
// -----------------------------------------------------------------------------
<|endoftext|>
|
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#include "java/io/Reader.hxx"
#include <string.h>
using namespace connectivity;
using ::com::sun::star::uno::Sequence;
//************ Class: java.io.Reader
jclass java_io_Reader::theClass = 0;
java_io_Reader::java_io_Reader( JNIEnv * pEnv, jobject myObj )
: java_lang_Object( pEnv, myObj )
{
SDBThreadAttach::addRef();
}
java_io_Reader::~java_io_Reader()
{
SDBThreadAttach::releaseRef();
}
jclass java_io_Reader::getMyClass() const
{
// the class must be fetched only once, therefore static
if( !theClass )
theClass = findMyClass("java/io/Reader");
return theClass;
}
sal_Int32 SAL_CALL java_io_Reader::readSomeBytes( ::com::sun::star::uno::Sequence< sal_Int8 >& aData, sal_Int32 nMaxBytesToRead ) throw(::com::sun::star::io::NotConnectedException, ::com::sun::star::io::BufferSizeExceededException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException, std::exception)
{
return readBytes(aData,nMaxBytesToRead);
}
void SAL_CALL java_io_Reader::skipBytes( sal_Int32 nBytesToSkip ) throw(::com::sun::star::io::NotConnectedException, ::com::sun::star::io::BufferSizeExceededException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException, std::exception)
{
static jmethodID mID(NULL);
if(nBytesToSkip <= 0)
return;
if(m_buf != boost::none)
{
m_buf = boost::none;
--nBytesToSkip;
}
static_assert(sizeof(jchar) == 2, "I thought Java characters were UTF16 code units?");
sal_Int32 nCharsToSkip = nBytesToSkip / sizeof(jchar);
callIntMethodWithIntArg_ThrowRuntime("skip",mID,nCharsToSkip);
if(nBytesToSkip % sizeof(jchar) != 0)
{
assert(nBytesToSkip % sizeof(jchar) == 1);
Sequence< sal_Int8 > aData(1);
assert(m_buf == boost::none);
readBytes(aData, 1);
}
}
sal_Int32 SAL_CALL java_io_Reader::available( ) throw(::com::sun::star::io::NotConnectedException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException, std::exception)
{
if(m_buf != boost::none)
return 1;
jboolean out;
SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment geloescht worden!");
{
static const char * cSignature = "()Z";
static const char * cMethodName = "ready";
// Java-Call
static jmethodID mID(NULL);
obtainMethodId_throwRuntime(t.pEnv, cMethodName,cSignature, mID);
out = t.pEnv->CallBooleanMethod( object, mID);
ThrowRuntimeException(t.pEnv,*this);
} //t.pEnv
return (m_buf != boost::none && out) ? 1 : 0; // no way to tell *how much* is ready
}
void SAL_CALL java_io_Reader::closeInput( ) throw(::com::sun::star::io::NotConnectedException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException, std::exception)
{
static jmethodID mID(NULL);
callVoidMethod_ThrowRuntime("close", mID);
}
sal_Int32 SAL_CALL java_io_Reader::readBytes( ::com::sun::star::uno::Sequence< sal_Int8 >& aData, sal_Int32 nBytesToRead ) throw(::com::sun::star::io::NotConnectedException, ::com::sun::star::io::BufferSizeExceededException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException, std::exception)
{
OSL_ENSURE(aData.getLength() >= nBytesToRead," Sequence is smaller than BytesToRead");
if(nBytesToRead == 0)
return 0;
sal_Int8 *dst(aData.getArray());
sal_Int32 nBytesWritten(0);
if(m_buf != boost::none)
{
if(aData.getLength() == 0)
{
aData.realloc(1);
dst = aData.getArray();
}
*dst = *m_buf;
m_buf = boost::none;
++nBytesWritten;
++dst;
--nBytesToRead;
}
if(nBytesToRead == 0)
return 0;
sal_Int32 nCharsToRead = (nBytesToRead + 1)/2;
jint outChars(0);
SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment geloescht worden!");
{
jcharArray pCharArray = t.pEnv->NewCharArray(nCharsToRead);
static const char * cSignature = "([CII)I";
static const char * cMethodName = "read";
// Java-Call
static jmethodID mID(NULL);
obtainMethodId_throwRuntime(t.pEnv, cMethodName,cSignature, mID);
outChars = t.pEnv->CallIntMethod( object, mID, pCharArray, 0, nCharsToRead );
if ( !outChars )
{
if(nBytesWritten==0)
ThrowRuntimeException(t.pEnv,*this);
else
return 1;
}
if(outChars > 0)
{
static_assert(sizeof(jchar) == 2, "I thought Java characters were UTF16 code units?");
const sal_Int32 jcs = sizeof(jchar);
const sal_Int32 outBytes = std::min(nBytesToRead, outChars*jcs);
assert(outBytes == outChars*jcs || outBytes == outChars*jcs - 1);
jboolean p = JNI_FALSE;
if(aData.getLength() < nBytesWritten + outBytes)
{
aData.realloc(nBytesWritten + outBytes);
dst = aData.getArray() + nBytesWritten;
}
jchar *outBuf(t.pEnv->GetCharArrayElements(pCharArray,&p));
memcpy(dst, outBuf, outBytes);
nBytesWritten += outBytes;
if(outBytes < outChars*jcs)
{
assert(outChars*jcs - outBytes == 1);
assert(m_buf == boost::none);
m_buf = reinterpret_cast<char*>(outBuf)[outBytes];
}
}
t.pEnv->DeleteLocalRef(pCharArray);
} //t.pEnv
return nBytesWritten;
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>...or rather, like this<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#include "java/io/Reader.hxx"
#include <string.h>
using namespace connectivity;
using ::com::sun::star::uno::Sequence;
//************ Class: java.io.Reader
jclass java_io_Reader::theClass = 0;
java_io_Reader::java_io_Reader( JNIEnv * pEnv, jobject myObj )
: java_lang_Object( pEnv, myObj )
{
SDBThreadAttach::addRef();
}
java_io_Reader::~java_io_Reader()
{
SDBThreadAttach::releaseRef();
}
jclass java_io_Reader::getMyClass() const
{
// the class must be fetched only once, therefore static
if( !theClass )
theClass = findMyClass("java/io/Reader");
return theClass;
}
sal_Int32 SAL_CALL java_io_Reader::readSomeBytes( ::com::sun::star::uno::Sequence< sal_Int8 >& aData, sal_Int32 nMaxBytesToRead ) throw(::com::sun::star::io::NotConnectedException, ::com::sun::star::io::BufferSizeExceededException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException, std::exception)
{
return readBytes(aData,nMaxBytesToRead);
}
void SAL_CALL java_io_Reader::skipBytes( sal_Int32 nBytesToSkip ) throw(::com::sun::star::io::NotConnectedException, ::com::sun::star::io::BufferSizeExceededException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException, std::exception)
{
static jmethodID mID(NULL);
if(nBytesToSkip <= 0)
return;
if(m_buf != boost::none)
{
m_buf = boost::none;
--nBytesToSkip;
}
static_assert(sizeof(jchar) == 2, "I thought Java characters were UTF16 code units?");
sal_Int32 nCharsToSkip = nBytesToSkip / sizeof(jchar);
callIntMethodWithIntArg_ThrowRuntime("skip",mID,nCharsToSkip);
if(nBytesToSkip % sizeof(jchar) != 0)
{
assert(nBytesToSkip % sizeof(jchar) == 1);
Sequence< sal_Int8 > aData(1);
assert(m_buf == boost::none);
readBytes(aData, 1);
}
}
sal_Int32 SAL_CALL java_io_Reader::available( ) throw(::com::sun::star::io::NotConnectedException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException, std::exception)
{
if(m_buf != boost::none)
return 1;
jboolean out;
SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment geloescht worden!");
{
static const char * cSignature = "()Z";
static const char * cMethodName = "ready";
// Java-Call
static jmethodID mID(NULL);
obtainMethodId_throwRuntime(t.pEnv, cMethodName,cSignature, mID);
out = t.pEnv->CallBooleanMethod( object, mID);
ThrowRuntimeException(t.pEnv,*this);
} //t.pEnv
return (m_buf != boost::none ? 1 : 0) + (out ? 1 : 0); // no way to tell *how much* is ready
}
void SAL_CALL java_io_Reader::closeInput( ) throw(::com::sun::star::io::NotConnectedException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException, std::exception)
{
static jmethodID mID(NULL);
callVoidMethod_ThrowRuntime("close", mID);
}
sal_Int32 SAL_CALL java_io_Reader::readBytes( ::com::sun::star::uno::Sequence< sal_Int8 >& aData, sal_Int32 nBytesToRead ) throw(::com::sun::star::io::NotConnectedException, ::com::sun::star::io::BufferSizeExceededException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException, std::exception)
{
OSL_ENSURE(aData.getLength() >= nBytesToRead," Sequence is smaller than BytesToRead");
if(nBytesToRead == 0)
return 0;
sal_Int8 *dst(aData.getArray());
sal_Int32 nBytesWritten(0);
if(m_buf != boost::none)
{
if(aData.getLength() == 0)
{
aData.realloc(1);
dst = aData.getArray();
}
*dst = *m_buf;
m_buf = boost::none;
++nBytesWritten;
++dst;
--nBytesToRead;
}
if(nBytesToRead == 0)
return 0;
sal_Int32 nCharsToRead = (nBytesToRead + 1)/2;
jint outChars(0);
SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment geloescht worden!");
{
jcharArray pCharArray = t.pEnv->NewCharArray(nCharsToRead);
static const char * cSignature = "([CII)I";
static const char * cMethodName = "read";
// Java-Call
static jmethodID mID(NULL);
obtainMethodId_throwRuntime(t.pEnv, cMethodName,cSignature, mID);
outChars = t.pEnv->CallIntMethod( object, mID, pCharArray, 0, nCharsToRead );
if ( !outChars )
{
if(nBytesWritten==0)
ThrowRuntimeException(t.pEnv,*this);
else
return 1;
}
if(outChars > 0)
{
static_assert(sizeof(jchar) == 2, "I thought Java characters were UTF16 code units?");
const sal_Int32 jcs = sizeof(jchar);
const sal_Int32 outBytes = std::min(nBytesToRead, outChars*jcs);
assert(outBytes == outChars*jcs || outBytes == outChars*jcs - 1);
jboolean p = JNI_FALSE;
if(aData.getLength() < nBytesWritten + outBytes)
{
aData.realloc(nBytesWritten + outBytes);
dst = aData.getArray() + nBytesWritten;
}
jchar *outBuf(t.pEnv->GetCharArrayElements(pCharArray,&p));
memcpy(dst, outBuf, outBytes);
nBytesWritten += outBytes;
if(outBytes < outChars*jcs)
{
assert(outChars*jcs - outBytes == 1);
assert(m_buf == boost::none);
m_buf = reinterpret_cast<char*>(outBuf)[outBytes];
}
}
t.pEnv->DeleteLocalRef(pCharArray);
} //t.pEnv
return nBytesWritten;
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: wrap_sqlbison.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: hr $ $Date: 2006-06-20 02:09:15 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#include "sqlbison.cxx"
<commit_msg>INTEGRATION: CWS pchfix02 (1.3.60); FILE MERGED 2006/09/01 17:22:35 kaib 1.3.60.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: wrap_sqlbison.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: obo $ $Date: 2006-09-17 03:09: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
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_connectivity.hxx"
#include "sqlbison.cxx"
<|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 "content/browser/speech/speech_recognizer.h"
#include "base/time.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/net/url_request_context_getter.h"
#include "content/browser/browser_thread.h"
using media::AudioInputController;
using std::string;
namespace {
// The following constants are related to the volume level indicator shown in
// the UI for recorded audio.
// Multiplier used when new volume is greater than previous level.
const float kUpSmoothingFactor = 1.0f;
// Multiplier used when new volume is lesser than previous level.
const float kDownSmoothingFactor = 0.7f;
// RMS dB value of a maximum (unclipped) sine wave for int16 samples.
const float kAudioMeterMaxDb = 90.31f;
// This value corresponds to RMS dB for int16 with 6 most-significant-bits = 0.
// Values lower than this will display as empty level-meter.
const float kAudioMeterMinDb = 30.0f;
const float kAudioMeterDbRange = kAudioMeterMaxDb - kAudioMeterMinDb;
// Maximum level to draw to display unclipped meter. (1.0f displays clipping.)
const float kAudioMeterRangeMaxUnclipped = 47.0f / 48.0f;
// Returns true if more than 5% of the samples are at min or max value.
bool Clipping(const int16* samples, int num_samples) {
int clipping_samples = 0;
const int kThreshold = num_samples / 20;
for (int i = 0; i < num_samples; ++i) {
if (samples[i] <= -32767 || samples[i] >= 32767) {
if (++clipping_samples > kThreshold)
return true;
}
}
return false;
}
} // namespace
namespace speech_input {
const int SpeechRecognizer::kAudioSampleRate = 16000;
const int SpeechRecognizer::kAudioPacketIntervalMs = 100;
const int SpeechRecognizer::kNumAudioChannels = 1;
const int SpeechRecognizer::kNumBitsPerAudioSample = 16;
const int SpeechRecognizer::kNoSpeechTimeoutSec = 8;
const int SpeechRecognizer::kEndpointerEstimationTimeMs = 300;
SpeechRecognizer::SpeechRecognizer(Delegate* delegate,
int caller_id,
const std::string& language,
const std::string& grammar,
const std::string& hardware_info,
const std::string& origin_url)
: delegate_(delegate),
caller_id_(caller_id),
language_(language),
grammar_(grammar),
hardware_info_(hardware_info),
origin_url_(origin_url),
codec_(AudioEncoder::CODEC_SPEEX),
encoder_(NULL),
endpointer_(kAudioSampleRate),
num_samples_recorded_(0),
audio_level_(0.0f) {
endpointer_.set_speech_input_complete_silence_length(
base::Time::kMicrosecondsPerSecond / 2);
endpointer_.set_long_speech_input_complete_silence_length(
base::Time::kMicrosecondsPerSecond);
endpointer_.set_long_speech_length(3 * base::Time::kMicrosecondsPerSecond);
endpointer_.StartSession();
}
SpeechRecognizer::~SpeechRecognizer() {
// Recording should have stopped earlier due to the endpointer or
// |StopRecording| being called.
DCHECK(!audio_controller_.get());
DCHECK(!request_.get() || !request_->HasPendingRequest());
DCHECK(!encoder_.get());
endpointer_.EndSession();
}
bool SpeechRecognizer::StartRecording() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
DCHECK(!audio_controller_.get());
DCHECK(!request_.get() || !request_->HasPendingRequest());
DCHECK(!encoder_.get());
// The endpointer needs to estimate the environment/background noise before
// starting to treat the audio as user input. In |HandleOnData| we wait until
// such time has passed before switching to user input mode.
endpointer_.SetEnvironmentEstimationMode();
encoder_.reset(AudioEncoder::Create(codec_, kAudioSampleRate,
kNumBitsPerAudioSample));
int samples_per_packet = (kAudioSampleRate * kAudioPacketIntervalMs) / 1000;
AudioParameters params(AudioParameters::AUDIO_PCM_LINEAR, kNumAudioChannels,
kAudioSampleRate, kNumBitsPerAudioSample,
samples_per_packet);
audio_controller_ = AudioInputController::Create(this, params);
DCHECK(audio_controller_.get());
VLOG(1) << "SpeechRecognizer starting record.";
num_samples_recorded_ = 0;
audio_controller_->Record();
return true;
}
void SpeechRecognizer::CancelRecognition() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
DCHECK(audio_controller_.get() || request_.get());
// Stop recording if required.
if (audio_controller_.get()) {
VLOG(1) << "SpeechRecognizer stopping record.";
audio_controller_->Close();
audio_controller_ = NULL; // Releases the ref ptr.
}
VLOG(1) << "SpeechRecognizer canceling recognition.";
encoder_.reset();
request_.reset();
}
void SpeechRecognizer::StopRecording() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
// If audio recording has already stopped and we are in recognition phase,
// silently ignore any more calls to stop recording.
if (!audio_controller_.get())
return;
VLOG(1) << "SpeechRecognizer stopping record.";
audio_controller_->Close();
audio_controller_ = NULL; // Releases the ref ptr.
delegate_->DidCompleteRecording(caller_id_);
// UploadAudioChunk requires a non-empty final buffer. So we encode a packet
// of silence in case encoder had no data already.
std::vector<short> samples((kAudioSampleRate * kAudioPacketIntervalMs) /
1000);
encoder_->Encode(&samples[0], samples.size());
encoder_->Flush();
string encoded_data;
encoder_->GetEncodedDataAndClear(&encoded_data);
DCHECK(!encoded_data.empty());
encoder_.reset();
// If we haven't got any audio yet end the recognition sequence here.
if (request_ == NULL) {
// Guard against the delegate freeing us until we finish our job.
scoped_refptr<SpeechRecognizer> me(this);
delegate_->DidCompleteRecognition(caller_id_);
} else {
request_->UploadAudioChunk(encoded_data, true /* is_last_chunk */);
}
}
// Invoked in the audio thread.
void SpeechRecognizer::OnError(AudioInputController* controller,
int error_code) {
BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
NewRunnableMethod(this,
&SpeechRecognizer::HandleOnError,
error_code));
}
void SpeechRecognizer::HandleOnError(int error_code) {
LOG(WARNING) << "SpeechRecognizer::HandleOnError, code=" << error_code;
// Check if we are still recording before canceling recognition, as
// recording might have been stopped after this error was posted to the queue
// by |OnError|.
if (!audio_controller_.get())
return;
InformErrorAndCancelRecognition(RECOGNIZER_ERROR_CAPTURE);
}
void SpeechRecognizer::OnData(AudioInputController* controller,
const uint8* data, uint32 size) {
if (size == 0) // This could happen when recording stops and is normal.
return;
string* str_data = new string(reinterpret_cast<const char*>(data), size);
BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
NewRunnableMethod(this,
&SpeechRecognizer::HandleOnData,
str_data));
}
void SpeechRecognizer::HandleOnData(string* data) {
// Check if we are still recording and if not discard this buffer, as
// recording might have been stopped after this buffer was posted to the queue
// by |OnData|.
if (!audio_controller_.get()) {
delete data;
return;
}
const short* samples = reinterpret_cast<const short*>(data->data());
DCHECK((data->length() % sizeof(short)) == 0);
int num_samples = data->length() / sizeof(short);
encoder_->Encode(samples, num_samples);
float rms;
endpointer_.ProcessAudio(samples, num_samples, &rms);
bool did_clip = Clipping(samples, num_samples);
delete data;
num_samples_recorded_ += num_samples;
if (request_ == NULL) {
// This was the first audio packet recorded, so start a request to the
// server to send the data.
request_.reset(new SpeechRecognitionRequest(
Profile::GetDefaultRequestContext(), this));
request_->Start(language_, grammar_, hardware_info_, origin_url_,
encoder_->mime_type());
}
string encoded_data;
encoder_->GetEncodedDataAndClear(&encoded_data);
DCHECK(!encoded_data.empty());
request_->UploadAudioChunk(encoded_data, false /* is_last_chunk */);
if (endpointer_.IsEstimatingEnvironment()) {
// Check if we have gathered enough audio for the endpointer to do
// environment estimation and should move on to detect speech/end of speech.
if (num_samples_recorded_ >= (kEndpointerEstimationTimeMs *
kAudioSampleRate) / 1000) {
endpointer_.SetUserInputMode();
delegate_->DidCompleteEnvironmentEstimation(caller_id_);
}
return; // No more processing since we are still estimating environment.
}
// Check if we have waited too long without hearing any speech.
if (!endpointer_.DidStartReceivingSpeech() &&
num_samples_recorded_ >= kNoSpeechTimeoutSec * kAudioSampleRate) {
InformErrorAndCancelRecognition(RECOGNIZER_ERROR_NO_SPEECH);
return;
}
// Calculate the input volume to display in the UI, smoothing towards the
// new level.
float level = (rms - kAudioMeterMinDb) /
(kAudioMeterDbRange / kAudioMeterRangeMaxUnclipped);
level = std::min(std::max(0.0f, level), kAudioMeterRangeMaxUnclipped);
if (level > audio_level_) {
audio_level_ += (level - audio_level_) * kUpSmoothingFactor;
} else {
audio_level_ += (level - audio_level_) * kDownSmoothingFactor;
}
float noise_level = (endpointer_.NoiseLevelDb() - kAudioMeterMinDb) /
(kAudioMeterDbRange / kAudioMeterRangeMaxUnclipped);
noise_level = std::min(std::max(0.0f, noise_level),
kAudioMeterRangeMaxUnclipped);
delegate_->SetInputVolume(caller_id_, did_clip ? 1.0f : audio_level_,
noise_level);
if (endpointer_.speech_input_complete()) {
StopRecording();
}
// TODO(satish): Once we have streaming POST, start sending the data received
// here as POST chunks.
}
void SpeechRecognizer::SetRecognitionResult(
bool error, const SpeechInputResultArray& result) {
if (error || result.empty()) {
InformErrorAndCancelRecognition(error ? RECOGNIZER_ERROR_NETWORK :
RECOGNIZER_ERROR_NO_RESULTS);
return;
}
delegate_->SetRecognitionResult(caller_id_, error, result);
// Guard against the delegate freeing us until we finish our job.
scoped_refptr<SpeechRecognizer> me(this);
delegate_->DidCompleteRecognition(caller_id_);
}
void SpeechRecognizer::InformErrorAndCancelRecognition(ErrorCode error) {
CancelRecognition();
// Guard against the delegate freeing us until we finish our job.
scoped_refptr<SpeechRecognizer> me(this);
delegate_->OnRecognizerError(caller_id_, error);
}
} // namespace speech_input
<commit_msg>Switch from using Speex to FLAC for speech input requests.<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 "content/browser/speech/speech_recognizer.h"
#include "base/time.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/net/url_request_context_getter.h"
#include "content/browser/browser_thread.h"
using media::AudioInputController;
using std::string;
namespace {
// The following constants are related to the volume level indicator shown in
// the UI for recorded audio.
// Multiplier used when new volume is greater than previous level.
const float kUpSmoothingFactor = 1.0f;
// Multiplier used when new volume is lesser than previous level.
const float kDownSmoothingFactor = 0.7f;
// RMS dB value of a maximum (unclipped) sine wave for int16 samples.
const float kAudioMeterMaxDb = 90.31f;
// This value corresponds to RMS dB for int16 with 6 most-significant-bits = 0.
// Values lower than this will display as empty level-meter.
const float kAudioMeterMinDb = 30.0f;
const float kAudioMeterDbRange = kAudioMeterMaxDb - kAudioMeterMinDb;
// Maximum level to draw to display unclipped meter. (1.0f displays clipping.)
const float kAudioMeterRangeMaxUnclipped = 47.0f / 48.0f;
// Returns true if more than 5% of the samples are at min or max value.
bool Clipping(const int16* samples, int num_samples) {
int clipping_samples = 0;
const int kThreshold = num_samples / 20;
for (int i = 0; i < num_samples; ++i) {
if (samples[i] <= -32767 || samples[i] >= 32767) {
if (++clipping_samples > kThreshold)
return true;
}
}
return false;
}
} // namespace
namespace speech_input {
const int SpeechRecognizer::kAudioSampleRate = 16000;
const int SpeechRecognizer::kAudioPacketIntervalMs = 100;
const int SpeechRecognizer::kNumAudioChannels = 1;
const int SpeechRecognizer::kNumBitsPerAudioSample = 16;
const int SpeechRecognizer::kNoSpeechTimeoutSec = 8;
const int SpeechRecognizer::kEndpointerEstimationTimeMs = 300;
SpeechRecognizer::SpeechRecognizer(Delegate* delegate,
int caller_id,
const std::string& language,
const std::string& grammar,
const std::string& hardware_info,
const std::string& origin_url)
: delegate_(delegate),
caller_id_(caller_id),
language_(language),
grammar_(grammar),
hardware_info_(hardware_info),
origin_url_(origin_url),
codec_(AudioEncoder::CODEC_FLAC),
encoder_(NULL),
endpointer_(kAudioSampleRate),
num_samples_recorded_(0),
audio_level_(0.0f) {
endpointer_.set_speech_input_complete_silence_length(
base::Time::kMicrosecondsPerSecond / 2);
endpointer_.set_long_speech_input_complete_silence_length(
base::Time::kMicrosecondsPerSecond);
endpointer_.set_long_speech_length(3 * base::Time::kMicrosecondsPerSecond);
endpointer_.StartSession();
}
SpeechRecognizer::~SpeechRecognizer() {
// Recording should have stopped earlier due to the endpointer or
// |StopRecording| being called.
DCHECK(!audio_controller_.get());
DCHECK(!request_.get() || !request_->HasPendingRequest());
DCHECK(!encoder_.get());
endpointer_.EndSession();
}
bool SpeechRecognizer::StartRecording() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
DCHECK(!audio_controller_.get());
DCHECK(!request_.get() || !request_->HasPendingRequest());
DCHECK(!encoder_.get());
// The endpointer needs to estimate the environment/background noise before
// starting to treat the audio as user input. In |HandleOnData| we wait until
// such time has passed before switching to user input mode.
endpointer_.SetEnvironmentEstimationMode();
encoder_.reset(AudioEncoder::Create(codec_, kAudioSampleRate,
kNumBitsPerAudioSample));
int samples_per_packet = (kAudioSampleRate * kAudioPacketIntervalMs) / 1000;
AudioParameters params(AudioParameters::AUDIO_PCM_LINEAR, kNumAudioChannels,
kAudioSampleRate, kNumBitsPerAudioSample,
samples_per_packet);
audio_controller_ = AudioInputController::Create(this, params);
DCHECK(audio_controller_.get());
VLOG(1) << "SpeechRecognizer starting record.";
num_samples_recorded_ = 0;
audio_controller_->Record();
return true;
}
void SpeechRecognizer::CancelRecognition() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
DCHECK(audio_controller_.get() || request_.get());
// Stop recording if required.
if (audio_controller_.get()) {
VLOG(1) << "SpeechRecognizer stopping record.";
audio_controller_->Close();
audio_controller_ = NULL; // Releases the ref ptr.
}
VLOG(1) << "SpeechRecognizer canceling recognition.";
encoder_.reset();
request_.reset();
}
void SpeechRecognizer::StopRecording() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
// If audio recording has already stopped and we are in recognition phase,
// silently ignore any more calls to stop recording.
if (!audio_controller_.get())
return;
VLOG(1) << "SpeechRecognizer stopping record.";
audio_controller_->Close();
audio_controller_ = NULL; // Releases the ref ptr.
delegate_->DidCompleteRecording(caller_id_);
// UploadAudioChunk requires a non-empty final buffer. So we encode a packet
// of silence in case encoder had no data already.
std::vector<short> samples((kAudioSampleRate * kAudioPacketIntervalMs) /
1000);
encoder_->Encode(&samples[0], samples.size());
encoder_->Flush();
string encoded_data;
encoder_->GetEncodedDataAndClear(&encoded_data);
DCHECK(!encoded_data.empty());
encoder_.reset();
// If we haven't got any audio yet end the recognition sequence here.
if (request_ == NULL) {
// Guard against the delegate freeing us until we finish our job.
scoped_refptr<SpeechRecognizer> me(this);
delegate_->DidCompleteRecognition(caller_id_);
} else {
request_->UploadAudioChunk(encoded_data, true /* is_last_chunk */);
}
}
// Invoked in the audio thread.
void SpeechRecognizer::OnError(AudioInputController* controller,
int error_code) {
BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
NewRunnableMethod(this,
&SpeechRecognizer::HandleOnError,
error_code));
}
void SpeechRecognizer::HandleOnError(int error_code) {
LOG(WARNING) << "SpeechRecognizer::HandleOnError, code=" << error_code;
// Check if we are still recording before canceling recognition, as
// recording might have been stopped after this error was posted to the queue
// by |OnError|.
if (!audio_controller_.get())
return;
InformErrorAndCancelRecognition(RECOGNIZER_ERROR_CAPTURE);
}
void SpeechRecognizer::OnData(AudioInputController* controller,
const uint8* data, uint32 size) {
if (size == 0) // This could happen when recording stops and is normal.
return;
string* str_data = new string(reinterpret_cast<const char*>(data), size);
BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
NewRunnableMethod(this,
&SpeechRecognizer::HandleOnData,
str_data));
}
void SpeechRecognizer::HandleOnData(string* data) {
// Check if we are still recording and if not discard this buffer, as
// recording might have been stopped after this buffer was posted to the queue
// by |OnData|.
if (!audio_controller_.get()) {
delete data;
return;
}
const short* samples = reinterpret_cast<const short*>(data->data());
DCHECK((data->length() % sizeof(short)) == 0);
int num_samples = data->length() / sizeof(short);
encoder_->Encode(samples, num_samples);
float rms;
endpointer_.ProcessAudio(samples, num_samples, &rms);
bool did_clip = Clipping(samples, num_samples);
delete data;
num_samples_recorded_ += num_samples;
if (request_ == NULL) {
// This was the first audio packet recorded, so start a request to the
// server to send the data.
request_.reset(new SpeechRecognitionRequest(
Profile::GetDefaultRequestContext(), this));
request_->Start(language_, grammar_, hardware_info_, origin_url_,
encoder_->mime_type());
}
string encoded_data;
encoder_->GetEncodedDataAndClear(&encoded_data);
DCHECK(!encoded_data.empty());
request_->UploadAudioChunk(encoded_data, false /* is_last_chunk */);
if (endpointer_.IsEstimatingEnvironment()) {
// Check if we have gathered enough audio for the endpointer to do
// environment estimation and should move on to detect speech/end of speech.
if (num_samples_recorded_ >= (kEndpointerEstimationTimeMs *
kAudioSampleRate) / 1000) {
endpointer_.SetUserInputMode();
delegate_->DidCompleteEnvironmentEstimation(caller_id_);
}
return; // No more processing since we are still estimating environment.
}
// Check if we have waited too long without hearing any speech.
if (!endpointer_.DidStartReceivingSpeech() &&
num_samples_recorded_ >= kNoSpeechTimeoutSec * kAudioSampleRate) {
InformErrorAndCancelRecognition(RECOGNIZER_ERROR_NO_SPEECH);
return;
}
// Calculate the input volume to display in the UI, smoothing towards the
// new level.
float level = (rms - kAudioMeterMinDb) /
(kAudioMeterDbRange / kAudioMeterRangeMaxUnclipped);
level = std::min(std::max(0.0f, level), kAudioMeterRangeMaxUnclipped);
if (level > audio_level_) {
audio_level_ += (level - audio_level_) * kUpSmoothingFactor;
} else {
audio_level_ += (level - audio_level_) * kDownSmoothingFactor;
}
float noise_level = (endpointer_.NoiseLevelDb() - kAudioMeterMinDb) /
(kAudioMeterDbRange / kAudioMeterRangeMaxUnclipped);
noise_level = std::min(std::max(0.0f, noise_level),
kAudioMeterRangeMaxUnclipped);
delegate_->SetInputVolume(caller_id_, did_clip ? 1.0f : audio_level_,
noise_level);
if (endpointer_.speech_input_complete()) {
StopRecording();
}
// TODO(satish): Once we have streaming POST, start sending the data received
// here as POST chunks.
}
void SpeechRecognizer::SetRecognitionResult(
bool error, const SpeechInputResultArray& result) {
if (error || result.empty()) {
InformErrorAndCancelRecognition(error ? RECOGNIZER_ERROR_NETWORK :
RECOGNIZER_ERROR_NO_RESULTS);
return;
}
delegate_->SetRecognitionResult(caller_id_, error, result);
// Guard against the delegate freeing us until we finish our job.
scoped_refptr<SpeechRecognizer> me(this);
delegate_->DidCompleteRecognition(caller_id_);
}
void SpeechRecognizer::InformErrorAndCancelRecognition(ErrorCode error) {
CancelRecognition();
// Guard against the delegate freeing us until we finish our job.
scoped_refptr<SpeechRecognizer> me(this);
delegate_->OnRecognizerError(caller_id_, error);
}
} // namespace speech_input
<|endoftext|>
|
<commit_before>#include "musicsongsearchonlinewidget.h"
#include "musictextdownloadthread.h"
#include "musicdatadownloadthread.h"
#include "musicdata2downloadthread.h"
#include "musicsongdownloadthread.h"
#include "musicbgthemedownload.h"
#include "musicnetworkthread.h"
#include "musicmydownloadrecordobject.h"
#include "musiclocalsongsearchrecordobject.h"
#include "musicmessagebox.h"
#include "musicconnectionpool.h"
#include <QDateTime>
#include <QVBoxLayout>
#include <QLabel>
#include <QPushButton>
#include <QCheckBox>
#include <QButtonGroup>
#include <QMediaPlayer>
MusicSongSearchOnlineTableWidget::MusicSongSearchOnlineTableWidget(QWidget *parent)
: MusicQueryTableWidget(parent), m_audition(NULL)
{
setColumnCount(6);
QHeaderView *headerview = horizontalHeader();
headerview->resizeSection(0,30);
headerview->resizeSection(1,215);
headerview->resizeSection(2,166);
headerview->resizeSection(3,50);
headerview->resizeSection(4,26);
headerview->resizeSection(5,26);
setTransparent(255);
m_previousAuditionRow = -1;
M_Connection->setValue("MusicSongSearchOnlineTableWidget", this);
}
MusicSongSearchOnlineTableWidget::~MusicSongSearchOnlineTableWidget()
{
delete m_audition;
clearAllItems();
}
void MusicSongSearchOnlineTableWidget::startSearchQuery(const QString &text)
{
////////////////////////////////////////////////
MusicSearchRecord record;
MusicLocalSongSearchRecordObject search(this);
if(!search.readSearchXMLConfig())
{
return;
}
search.readSearchConfig( record );
record.m_names.insert(0, text);
record.m_times.insert(0, QString::number(QDateTime::currentMSecsSinceEpoch()));
search.writeSearchConfig( record );
////////////////////////////////////////////////
QString currentQuality;
emit getQualityString(currentQuality);
if(!currentQuality.isEmpty())
{
m_downLoadManager->setSearchQuality(currentQuality);
}
m_downLoadManager->startSearchSong(MusicQuery, m_searchText = text);
}
void MusicSongSearchOnlineTableWidget::researchQueryByQuality()
{
startSearchQuery(m_searchText);
}
void MusicSongSearchOnlineTableWidget::clearAllItems()
{
MusicAbstractTableWidget::clear();
setColumnCount(6);
}
void MusicSongSearchOnlineTableWidget::creatSearchedItems(const QString &songname,
const QString &artistname, const QString &time)
{
int count;
setRowCount(count = m_downLoadManager->getSongIdIndex());
QTableWidgetItem *item = new QTableWidgetItem;
item->setData(Qt::DisplayRole, false);
item->setData(AUDITION_ROLE, AUDITION_STOP);
setItem(count - 1, 0, item);
item = new QTableWidgetItem(songname);
item->setTextColor(QColor(50,50,50));
item->setTextAlignment(Qt::AlignCenter);
item->setToolTip(songname);
setItem(count - 1, 1, item);
item = new QTableWidgetItem(artistname);
item->setTextColor(QColor(50,50,50));
item->setTextAlignment(Qt::AlignCenter);
item->setToolTip(artistname);
setItem(count - 1, 2, item);
item = new QTableWidgetItem(time);
item->setTextColor(QColor(50,50,50));
item->setTextAlignment(Qt::AlignCenter);
setItem(count - 1, 3, item);
item = new QTableWidgetItem(QIcon(QString::fromUtf8(":/image/addtoplaylist")),"");
item->setTextAlignment(Qt::AlignCenter);
setItem(count - 1, 4, item);
item = new QTableWidgetItem(QIcon(QString::fromUtf8(":/share/musicdownload")),"");
item->setTextAlignment(Qt::AlignCenter);
setItem(count - 1, 5, item);
}
void MusicSongSearchOnlineTableWidget::listCellClicked(int row, int col)
{
MusicQueryTableWidget::listCellClicked(row, col);
switch(col)
{
case 4:
addSearchMusicToPlayList(row);
break;
case 5:
musicDownloadLocal(row);
break;
default:
break;
}
emit auditionIsPlaying( item(row, 0)->data(AUDITION_ROLE).toInt() == AUDITION_STOP );
}
void MusicSongSearchOnlineTableWidget::contextMenuEvent(QContextMenuEvent *event)
{
MusicQueryTableWidget::contextMenuEvent(event);
QMenu rightClickMenu(this);
createContextMenu(rightClickMenu);
QAction *playAction = rightClickMenu.addAction(QIcon(":/contextMenu/play"), tr("musicPlay"));
QAction *addAction = rightClickMenu.addAction(tr("musicAdd"));
rightClickMenu.insertAction(rightClickMenu.actions().first(), addAction);
rightClickMenu.insertAction(addAction, playAction);
m_actionGroup->addAction( playAction );
m_actionGroup->addAction( addAction );
rightClickMenu.exec(QCursor::pos());
}
void MusicSongSearchOnlineTableWidget::actionGroupClick(QAction *action)
{
MusicQueryTableWidget::actionGroupClick(action);
int row = currentRow();
switch( findActionGroup(action) )
{
case 4: auditionToMusic(row); break;
case 5: addSearchMusicToPlayList(row); break;
}
}
void MusicSongSearchOnlineTableWidget::auditionToMusic(int row)
{
MStringLists musicSongInfo(m_downLoadManager->getMusicSongInfo());
if(musicSongInfo.isEmpty() || row < 0)
{
MusicMessageBox message;
message.setText(tr("Please Select One Item First!"));
message.exec();
return;
}
if(m_audition == NULL)
{
m_audition = new QMediaPlayer(this);
}
m_audition->setMedia(QUrl(musicSongInfo[row][0]));
m_audition->play();
if(m_previousAuditionRow != -1)
{
item(m_previousAuditionRow, 0)->setData(AUDITION_ROLE, AUDITION_STOP);
}
item(m_previousAuditionRow = row, 0)->setData(AUDITION_ROLE, AUDITION_PLAY);
emit auditionIsPlaying(false);
}
void MusicSongSearchOnlineTableWidget::auditionToMusicStop(int row)
{
if(m_audition)
{
m_audition->stop();
}
if(row < 0)
{
MusicMessageBox message;
message.setText(tr("Please Select One Item First!"));
message.exec();
return;
}
item(row, 0)->setData(AUDITION_ROLE, AUDITION_STOP);
emit auditionIsPlaying(true);
}
void MusicSongSearchOnlineTableWidget::addSearchMusicToPlayList(int row)
{
if(!M_NETWORK->isOnline())
{ //no network connection
emit showDownLoadInfoFor(MusicObject::DisConnection);
return;
}
if(row < 0)
{
MusicMessageBox message;
message.setText(tr("Please Select One Item First!"));
message.exec();
return;
}
emit showDownLoadInfoFor(MusicObject::Buffing);
musicDownloadLocal(row);
emit muiscSongToPlayListChanged( item(row, 2)->text() + " - " + item(row, 1)->text() );
}
void MusicSongSearchOnlineTableWidget::musicDownloadLocal(int row)
{
if(!M_NETWORK->isOnline())
{ //no network connection
emit showDownLoadInfoFor(MusicObject::DisConnection);
return;
}
if(row < 0)
{
MusicMessageBox message;
message.setText(tr("Please Select One Item First!"));
message.exec();
return;
}
emit showDownLoadInfoFor(MusicObject::DownLoading);
MStringLists musicSongInfo(m_downLoadManager->getMusicSongInfo());
QString musicSong = item(row, 2)->text() + " - " + item(row, 1)->text() ;
QString downloadName = MusicObject::getAppDir() + MUSIC_DOWNLOAD + musicSong + MUSIC_FILE;
////////////////////////////////////////////////
MusicDownloadRecord record;
MusicMyDownloadRecordObject down(this);
if(!down.readDownloadXMLConfig())
{
return;
}
down.readDownloadConfig( record );
record.m_names << musicSong;
record.m_paths << QFileInfo(downloadName).absoluteFilePath();
record.m_sizes << musicSongInfo[row][4];
down.writeDownloadConfig( record );
////////////////////////////////////////////////
MusicSongDownloadThread *downSong = new MusicSongDownloadThread( musicSongInfo[row][0],
downloadName, Download_Music, this);
downSong->startToDownload();
(new MusicTextDownLoadThread(musicSongInfo[row][1], MusicObject::getAppDir() + LRC_DOWNLOAD +
musicSong + LRC_FILE, Download_Lrc, this))->startToDownload();
(new MusicData2DownloadThread(musicSongInfo[row][2], MusicObject::getAppDir() +
ART_DOWNLOAD + musicSongInfo[row][3] + SKN_FILE, Download_SmlBG, this))->startToDownload();
///download big picture
new MusicBgThemeDownload(musicSongInfo[row][3], musicSongInfo[row][3], this);
}
void MusicSongSearchOnlineTableWidget::itemDoubleClicked(int row, int column)
{
if(column <= 0 || row < 0)
{
return;
}
addSearchMusicToPlayList(row);
}
MusicSongSearchOnlineWidget::MusicSongSearchOnlineWidget(QWidget *parent)
: QWidget(parent)
{
QVBoxLayout *boxLayout = new QVBoxLayout(this);
boxLayout->setMargin(0);
boxLayout->setSpacing(0);
QWidget *toolWidget = new QWidget(this);
toolWidget->setFixedHeight(65);
QPalette pal(palette());
pal.setColor(QPalette::Background, Qt::white);
toolWidget->setAutoFillBackground(true);
toolWidget->setPalette(pal);
m_searchTableWidget = new MusicSongSearchOnlineTableWidget(this);
boxLayout->addWidget(toolWidget);
boxLayout->addWidget(m_searchTableWidget);
setLayout(boxLayout);
createToolWidget();
connect(m_searchTableWidget, SIGNAL(auditionIsPlaying(bool)), SLOT(auditionIsPlaying(bool)));
}
MusicSongSearchOnlineWidget::~MusicSongSearchOnlineWidget()
{
delete m_playButton;
delete m_textLabel;
delete m_searchTableWidget;
}
void MusicSongSearchOnlineWidget::startSearchQuery(const QString &name) const
{
m_searchTableWidget->startSearchQuery(name);
m_textLabel->setText(tr(" find <font color=red> %1 </font> result")
.arg(QFontMetrics(font()).elidedText(name, Qt::ElideRight, 170)));
}
void MusicSongSearchOnlineWidget::createToolWidget()
{
m_textLabel = new QLabel(this);
m_textLabel->setGeometry(0, 0, 280, 30);
m_textLabel->setText(tr(" find no result"));
QLabel *colorLabel = new QLabel(this);
colorLabel->setStyleSheet(MusicUIObject::MCustomStyle17);
colorLabel->setGeometry(0, 30, width(), 35);
QCheckBox *label_checkBox = new QCheckBox(this);
label_checkBox->setStyleSheet(MusicUIObject::MCheckBoxStyle01);
label_checkBox->setGeometry(7, 40, 20, 20);
connect(label_checkBox, SIGNAL(clicked(bool)), m_searchTableWidget,
SLOT(setSelectedAllItems(bool)));
QLabel *Label1 = new QLabel(tr("Song"), this);
Label1->setStyleSheet(MusicUIObject::MCustomStyle18);
Label1->setGeometry(120, 40, 60, 20);
QLabel *Label2 = new QLabel(tr("Artist"), this);
Label2->setStyleSheet(MusicUIObject::MCustomStyle18);
Label2->setGeometry(310, 40, 60, 20);
QLabel *Label3 = new QLabel(tr("Operator"), this);
Label3->setStyleSheet(MusicUIObject::MCustomStyle18);
Label3->setGeometry(435, 40, 60, 20);
m_playButton = new QPushButton(tr("Play"), this);
m_playButton->setGeometry(295, 5, 70, 20);
m_playButton->setStyleSheet(MusicUIObject::MPushButtonStyle05);
m_playButton->setCursor(QCursor(Qt::PointingHandCursor));
QPushButton *addButton = new QPushButton(tr("Add"), this);
addButton->setGeometry(370, 5, 70, 20);
addButton->setStyleSheet(MusicUIObject::MPushButtonStyle05);
addButton->setCursor(QCursor(Qt::PointingHandCursor));
QPushButton *downloadButton = new QPushButton(tr("Download"), this);
downloadButton->setGeometry(445, 5, 70, 20);
downloadButton->setStyleSheet(MusicUIObject::MPushButtonStyle05);
downloadButton->setCursor(QCursor(Qt::PointingHandCursor));
QButtonGroup *buttonGroup = new QButtonGroup(this);
buttonGroup->addButton(m_playButton, 0);
buttonGroup->addButton(addButton, 1);
buttonGroup->addButton(downloadButton, 2);
connect(buttonGroup, SIGNAL(buttonClicked(int)), SLOT(buttonClicked(int)));
}
void MusicSongSearchOnlineWidget::buttonClicked(int index)
{
MIntList list = m_searchTableWidget->getSelectedItems();
if(list.isEmpty())
{
MusicMessageBox message;
message.setText(tr("Please Select One Item First!"));
message.exec();
return;
}
foreach(int row, list)
{
switch(index)
{
case 0:
m_playButton->text() == tr("Play") ? m_searchTableWidget->auditionToMusic(row)
: m_searchTableWidget->auditionToMusicStop(row);
break;
case 1:
m_searchTableWidget->listCellClicked(row, 4);
break;
case 2:
m_searchTableWidget->listCellClicked(row, 5);
break;
default:
break;
}
}
}
void MusicSongSearchOnlineWidget::auditionIsPlaying(bool play)
{
m_playButton->setText(play ? tr("Play") : tr("Stop"));
}
<commit_msg>clean code for musicsearchlinewidget[303259]<commit_after>#include "musicsongsearchonlinewidget.h"
#include "musictextdownloadthread.h"
#include "musicdatadownloadthread.h"
#include "musicdata2downloadthread.h"
#include "musicsongdownloadthread.h"
#include "musicbgthemedownload.h"
#include "musicnetworkthread.h"
#include "musicmydownloadrecordobject.h"
#include "musiclocalsongsearchrecordobject.h"
#include "musicmessagebox.h"
#include "musicconnectionpool.h"
#include <QDateTime>
#include <QVBoxLayout>
#include <QLabel>
#include <QPushButton>
#include <QCheckBox>
#include <QButtonGroup>
#include <QMediaPlayer>
MusicSongSearchOnlineTableWidget::MusicSongSearchOnlineTableWidget(QWidget *parent)
: MusicQueryTableWidget(parent), m_audition(NULL)
{
setColumnCount(6);
QHeaderView *headerview = horizontalHeader();
headerview->resizeSection(0, 30);
headerview->resizeSection(1, 215);
headerview->resizeSection(2, 166);
headerview->resizeSection(3, 50);
headerview->resizeSection(4, 26);
headerview->resizeSection(5, 26);
setTransparent(255);
m_previousAuditionRow = -1;
M_Connection->setValue("MusicSongSearchOnlineTableWidget", this);
}
MusicSongSearchOnlineTableWidget::~MusicSongSearchOnlineTableWidget()
{
delete m_audition;
clearAllItems();
}
void MusicSongSearchOnlineTableWidget::startSearchQuery(const QString &text)
{
////////////////////////////////////////////////
MusicSearchRecord record;
MusicLocalSongSearchRecordObject search(this);
if(!search.readSearchXMLConfig())
{
return;
}
search.readSearchConfig( record );
record.m_names.insert(0, text);
record.m_times.insert(0, QString::number(QDateTime::currentMSecsSinceEpoch()));
search.writeSearchConfig( record );
////////////////////////////////////////////////
QString currentQuality;
emit getQualityString(currentQuality);
if(!currentQuality.isEmpty())
{
m_downLoadManager->setSearchQuality(currentQuality);
}
m_downLoadManager->startSearchSong(MusicQuery, m_searchText = text);
}
void MusicSongSearchOnlineTableWidget::researchQueryByQuality()
{
startSearchQuery(m_searchText);
}
void MusicSongSearchOnlineTableWidget::clearAllItems()
{
MusicAbstractTableWidget::clear();
setColumnCount(6);
}
void MusicSongSearchOnlineTableWidget::creatSearchedItems(const QString &songname,
const QString &artistname, const QString &time)
{
int count;
setRowCount(count = m_downLoadManager->getSongIdIndex());
QTableWidgetItem *item = new QTableWidgetItem;
item->setData(Qt::DisplayRole, false);
item->setData(AUDITION_ROLE, AUDITION_STOP);
setItem(count - 1, 0, item);
item = new QTableWidgetItem(songname);
item->setTextColor(QColor(50, 50, 50));
item->setTextAlignment(Qt::AlignCenter);
item->setToolTip(songname);
setItem(count - 1, 1, item);
item = new QTableWidgetItem(artistname);
item->setTextColor(QColor(50, 50, 50));
item->setTextAlignment(Qt::AlignCenter);
item->setToolTip(artistname);
setItem(count - 1, 2, item);
item = new QTableWidgetItem(time);
item->setTextColor(QColor(50, 50, 50));
item->setTextAlignment(Qt::AlignCenter);
setItem(count - 1, 3, item);
item = new QTableWidgetItem(QIcon(QString::fromUtf8(":/image/addtoplaylist")),"");
item->setTextAlignment(Qt::AlignCenter);
setItem(count - 1, 4, item);
item = new QTableWidgetItem(QIcon(QString::fromUtf8(":/share/musicdownload")),"");
item->setTextAlignment(Qt::AlignCenter);
setItem(count - 1, 5, item);
}
void MusicSongSearchOnlineTableWidget::listCellClicked(int row, int col)
{
MusicQueryTableWidget::listCellClicked(row, col);
switch(col)
{
case 4:
addSearchMusicToPlayList(row);
break;
case 5:
musicDownloadLocal(row);
break;
default:
break;
}
emit auditionIsPlaying( item(row, 0)->data(AUDITION_ROLE).toInt() == AUDITION_STOP );
}
void MusicSongSearchOnlineTableWidget::contextMenuEvent(QContextMenuEvent *event)
{
MusicQueryTableWidget::contextMenuEvent(event);
QMenu rightClickMenu(this);
createContextMenu(rightClickMenu);
QAction *playAction = rightClickMenu.addAction(QIcon(":/contextMenu/play"), tr("musicPlay"));
QAction *addAction = rightClickMenu.addAction(tr("musicAdd"));
rightClickMenu.insertAction(rightClickMenu.actions().first(), addAction);
rightClickMenu.insertAction(addAction, playAction);
m_actionGroup->addAction( playAction );
m_actionGroup->addAction( addAction );
rightClickMenu.exec(QCursor::pos());
}
void MusicSongSearchOnlineTableWidget::actionGroupClick(QAction *action)
{
MusicQueryTableWidget::actionGroupClick(action);
int row = currentRow();
switch( findActionGroup(action) )
{
case 4: auditionToMusic(row); break;
case 5: addSearchMusicToPlayList(row); break;
}
}
void MusicSongSearchOnlineTableWidget::auditionToMusic(int row)
{
MStringLists musicSongInfo(m_downLoadManager->getMusicSongInfo());
if(musicSongInfo.isEmpty() || row < 0)
{
MusicMessageBox message;
message.setText(tr("Please Select One Item First!"));
message.exec();
return;
}
if(m_audition == NULL)
{
m_audition = new QMediaPlayer(this);
}
m_audition->setMedia(QUrl(musicSongInfo[row][0]));
m_audition->play();
if(m_previousAuditionRow != -1)
{
item(m_previousAuditionRow, 0)->setData(AUDITION_ROLE, AUDITION_STOP);
}
item(m_previousAuditionRow = row, 0)->setData(AUDITION_ROLE, AUDITION_PLAY);
emit auditionIsPlaying(false);
}
void MusicSongSearchOnlineTableWidget::auditionToMusicStop(int row)
{
if(m_audition)
{
m_audition->stop();
}
if(row < 0)
{
MusicMessageBox message;
message.setText(tr("Please Select One Item First!"));
message.exec();
return;
}
item(row, 0)->setData(AUDITION_ROLE, AUDITION_STOP);
emit auditionIsPlaying(true);
}
void MusicSongSearchOnlineTableWidget::addSearchMusicToPlayList(int row)
{
if(!M_NETWORK->isOnline())
{ //no network connection
emit showDownLoadInfoFor(MusicObject::DisConnection);
return;
}
if(row < 0)
{
MusicMessageBox message;
message.setText(tr("Please Select One Item First!"));
message.exec();
return;
}
emit showDownLoadInfoFor(MusicObject::Buffing);
musicDownloadLocal(row);
emit muiscSongToPlayListChanged( item(row, 2)->text() + " - " + item(row, 1)->text() );
}
void MusicSongSearchOnlineTableWidget::musicDownloadLocal(int row)
{
if(!M_NETWORK->isOnline())
{ //no network connection
emit showDownLoadInfoFor(MusicObject::DisConnection);
return;
}
if(row < 0)
{
MusicMessageBox message;
message.setText(tr("Please Select One Item First!"));
message.exec();
return;
}
emit showDownLoadInfoFor(MusicObject::DownLoading);
MStringLists musicSongInfo(m_downLoadManager->getMusicSongInfo());
QString musicSong = item(row, 2)->text() + " - " + item(row, 1)->text() ;
QString downloadName = MusicObject::getAppDir() + MUSIC_DOWNLOAD + musicSong + MUSIC_FILE;
////////////////////////////////////////////////
MusicDownloadRecord record;
MusicMyDownloadRecordObject down(this);
if(!down.readDownloadXMLConfig())
{
return;
}
down.readDownloadConfig( record );
record.m_names << musicSong;
record.m_paths << QFileInfo(downloadName).absoluteFilePath();
record.m_sizes << musicSongInfo[row][4];
down.writeDownloadConfig( record );
////////////////////////////////////////////////
MusicSongDownloadThread *downSong = new MusicSongDownloadThread( musicSongInfo[row][0],
downloadName, Download_Music, this);
downSong->startToDownload();
(new MusicTextDownLoadThread(musicSongInfo[row][1], MusicObject::getAppDir() + LRC_DOWNLOAD +
musicSong + LRC_FILE, Download_Lrc, this))->startToDownload();
(new MusicData2DownloadThread(musicSongInfo[row][2], MusicObject::getAppDir() +
ART_DOWNLOAD + musicSongInfo[row][3] + SKN_FILE, Download_SmlBG, this))->startToDownload();
///download big picture
new MusicBgThemeDownload(musicSongInfo[row][3], musicSongInfo[row][3], this);
}
void MusicSongSearchOnlineTableWidget::itemDoubleClicked(int row, int column)
{
if(column <= 0 || row < 0)
{
return;
}
addSearchMusicToPlayList(row);
}
MusicSongSearchOnlineWidget::MusicSongSearchOnlineWidget(QWidget *parent)
: QWidget(parent)
{
QVBoxLayout *boxLayout = new QVBoxLayout(this);
boxLayout->setMargin(0);
boxLayout->setSpacing(0);
QWidget *toolWidget = new QWidget(this);
toolWidget->setFixedHeight(65);
QPalette pal(palette());
pal.setColor(QPalette::Background, Qt::white);
toolWidget->setAutoFillBackground(true);
toolWidget->setPalette(pal);
m_searchTableWidget = new MusicSongSearchOnlineTableWidget(this);
boxLayout->addWidget(toolWidget);
boxLayout->addWidget(m_searchTableWidget);
setLayout(boxLayout);
createToolWidget();
connect(m_searchTableWidget, SIGNAL(auditionIsPlaying(bool)), SLOT(auditionIsPlaying(bool)));
}
MusicSongSearchOnlineWidget::~MusicSongSearchOnlineWidget()
{
delete m_playButton;
delete m_textLabel;
delete m_searchTableWidget;
}
void MusicSongSearchOnlineWidget::startSearchQuery(const QString &name) const
{
m_searchTableWidget->startSearchQuery(name);
m_textLabel->setText(tr(" find <font color=red> %1 </font> result")
.arg(QFontMetrics(font()).elidedText(name, Qt::ElideRight, 170)));
}
void MusicSongSearchOnlineWidget::createToolWidget()
{
m_textLabel = new QLabel(this);
m_textLabel->setGeometry(0, 0, 280, 30);
m_textLabel->setText(tr(" find no result"));
QLabel *colorLabel = new QLabel(this);
colorLabel->setStyleSheet(MusicUIObject::MCustomStyle17);
colorLabel->setGeometry(0, 30, width(), 35);
QCheckBox *label_checkBox = new QCheckBox(this);
label_checkBox->setStyleSheet(MusicUIObject::MCheckBoxStyle01);
label_checkBox->setGeometry(7, 40, 20, 20);
connect(label_checkBox, SIGNAL(clicked(bool)), m_searchTableWidget,
SLOT(setSelectedAllItems(bool)));
QLabel *Label1 = new QLabel(tr("Song"), this);
Label1->setStyleSheet(MusicUIObject::MCustomStyle18);
Label1->setGeometry(120, 40, 60, 20);
QLabel *Label2 = new QLabel(tr("Artist"), this);
Label2->setStyleSheet(MusicUIObject::MCustomStyle18);
Label2->setGeometry(310, 40, 60, 20);
QLabel *Label3 = new QLabel(tr("Operator"), this);
Label3->setStyleSheet(MusicUIObject::MCustomStyle18);
Label3->setGeometry(435, 40, 60, 20);
m_playButton = new QPushButton(tr("Play"), this);
m_playButton->setGeometry(295, 5, 70, 20);
m_playButton->setStyleSheet(MusicUIObject::MPushButtonStyle05);
m_playButton->setCursor(QCursor(Qt::PointingHandCursor));
QPushButton *addButton = new QPushButton(tr("Add"), this);
addButton->setGeometry(370, 5, 70, 20);
addButton->setStyleSheet(MusicUIObject::MPushButtonStyle05);
addButton->setCursor(QCursor(Qt::PointingHandCursor));
QPushButton *downloadButton = new QPushButton(tr("Download"), this);
downloadButton->setGeometry(445, 5, 70, 20);
downloadButton->setStyleSheet(MusicUIObject::MPushButtonStyle05);
downloadButton->setCursor(QCursor(Qt::PointingHandCursor));
QButtonGroup *buttonGroup = new QButtonGroup(this);
buttonGroup->addButton(m_playButton, 0);
buttonGroup->addButton(addButton, 1);
buttonGroup->addButton(downloadButton, 2);
connect(buttonGroup, SIGNAL(buttonClicked(int)), SLOT(buttonClicked(int)));
}
void MusicSongSearchOnlineWidget::buttonClicked(int index)
{
MIntList list = m_searchTableWidget->getSelectedItems();
if(list.isEmpty())
{
MusicMessageBox message;
message.setText(tr("Please Select One Item First!"));
message.exec();
return;
}
foreach(int row, list)
{
switch(index)
{
case 0:
m_playButton->text() == tr("Play") ? m_searchTableWidget->auditionToMusic(row)
: m_searchTableWidget->auditionToMusicStop(row);
break;
case 1:
m_searchTableWidget->listCellClicked(row, 4);
break;
case 2:
m_searchTableWidget->listCellClicked(row, 5);
break;
default:
break;
}
}
}
void MusicSongSearchOnlineWidget::auditionIsPlaying(bool play)
{
m_playButton->setText(play ? tr("Play") : tr("Stop"));
}
<|endoftext|>
|
<commit_before>#include <QString>
#include <QFileInfo>
#include <QVector>
#include <QUrl>
#include <QRegExp>
#include "ilwis.h"
#include "catalog.h"
#include "ilwiscontext.h"
#include "symboltable.h"
using namespace Ilwis;
quint64 SymbolTable::_symbolid = 0;
SymbolTable::SymbolTable() //:
//QHash<QString, Symbol>()
{
}
void SymbolTable::addSymbol(const QString &name, int scope, quint64 tp, const QVariant& v)
{
QVariant var = getValue(name,scope); // do we already have it?
if (var.isValid()){
_symbols[name]._var = v;
_symbols[name]._type = tp;
return;
}
if ( tp == 0) {
if ( isRealNumerical(v))
tp = itDOUBLE;
else if (isIntegerNumerical(v))
tp = itINT32;
else {
if ( v.type() == QMetaType::QString)
tp = itSTRING;
QString typname = v.typeName();
if ( typname == "Ilwis::Coordinate")
tp = itCOORDINATE;
}
}
Symbol sym(scope, tp, v);
_symbols[name] = sym;
}
QVariant SymbolTable::getValue(const QString &name, int scope) const
{
QHash<QString, Symbol>::const_iterator iter = _symbols.find(name);
while (iter != _symbols.end() && iter.key() == name) {
if ( iter.value()._scope == scope) {
return iter.value()._var;
}
++iter;
}
return QVariant();
}
Symbol SymbolTable::getSymbol(const QString &name, GetAction act, int scope)
{
QHash<QString, Symbol>::iterator iter = _symbols.find(name);
while (iter != _symbols.end() && iter.key() == name) {
if ( iter.value()._scope <= scope) {
Symbol sym = iter.value();
bool isAnonymous = name.indexOf(INTERNAL_PREFIX) == 0;
if ((isAnonymous && act == gaREMOVEIFANON) || act == gaREMOVE)
_symbols.erase(iter);
return sym;
}
++iter;
}
return Symbol();
}
Symbol SymbolTable::getSymbol(const QString &name, int scope) const
{
QHash<QString, Symbol>::const_iterator iter = _symbols.find(name);
while (iter != _symbols.end() && iter.key() == name) {
if ( iter.value()._scope == scope) {
return iter.value();
}
++iter;
}
return Symbol();
}
bool SymbolTable::isNumerical(const QVariant& var) {
return isRealNumerical(var) || isIntegerNumerical(var);
}
bool SymbolTable::isRealNumerical(const QVariant& var) {
QString tpname = var.typeName();
bool ok = var.type() == QMetaType::Float || var.type() == QMetaType::Double;
if ( ok)
return true;
var.toDouble(&ok);
return ok;
}
bool SymbolTable::isIntegerNumerical(const QVariant& var) {
QMetaType::Type tp = static_cast<QMetaType::Type>(var.type());
bool ok = tp == QMetaType::Int || tp == QMetaType::UInt ||
tp == QMetaType::LongLong || tp == QMetaType::ULongLong ||
tp == QMetaType::Long || tp == QMetaType::ULong ||
tp == QMetaType::Short || tp == QMetaType::UShort ||
tp == QMetaType::Char || tp == QMetaType::UChar;
if ( ok)
return true;
var.toLongLong(&ok);
if ( ok)
return true;
var.toULongLong(&ok);
return ok;
}
bool SymbolTable::isDataLink(const QVariant& value) {
QString resolvedv = value.toString();
if ( !resolvedv.contains(QRegExp("\\\\|/"))) {
resolvedv = Ilwis::context()->workingCatalog()->resolve(resolvedv);
if ( resolvedv == sUNDEF)
return false;
}
return true;
}
QString SymbolTable::newAnonym()
{
_symbolid++;
return QString("%1%2").arg(INTERNAL_PREFIX).arg(_symbolid);
}
Symbol::Symbol(int scope, quint64 tp, const QVariant &v) : _type(tp), _scope(scope), _var(v)
{
}
bool Symbol::isValid() const
{
return _var.isValid() && _scope != iUNDEF;
}
<commit_msg>improved type<commit_after>#include <QString>
#include <QFileInfo>
#include <QVector>
#include <QUrl>
#include <QRegExp>
#include "ilwis.h"
#include "catalog.h"
#include "ilwiscontext.h"
#include "symboltable.h"
using namespace Ilwis;
quint64 SymbolTable::_symbolid = 0;
SymbolTable::SymbolTable() //:
//QHash<QString, Symbol>()
{
}
void SymbolTable::addSymbol(const QString &name, int scope, quint64 tp, const QVariant& v)
{
QVariant var = getValue(name,scope); // do we already have it?
if (var.isValid()){
_symbols[name]._var = v;
_symbols[name]._type = tp;
return;
}
if ( tp == 0) {
if ( isRealNumerical(v))
tp = itDOUBLE;
else if (isIntegerNumerical(v))
tp = itINT32;
else {
if ( v.type() == QMetaType::QString)
tp = itSTRING;
QString typname = v.typeName();
if ( typname == "Coordinate")
tp = itCOORDINATE;
}
}
Symbol sym(scope, tp, v);
_symbols[name] = sym;
}
QVariant SymbolTable::getValue(const QString &name, int scope) const
{
QHash<QString, Symbol>::const_iterator iter = _symbols.find(name);
while (iter != _symbols.end() && iter.key() == name) {
if ( iter.value()._scope == scope) {
return iter.value()._var;
}
++iter;
}
return QVariant();
}
Symbol SymbolTable::getSymbol(const QString &name, GetAction act, int scope)
{
QHash<QString, Symbol>::iterator iter = _symbols.find(name);
while (iter != _symbols.end() && iter.key() == name) {
if ( iter.value()._scope <= scope) {
Symbol sym = iter.value();
bool isAnonymous = name.indexOf(INTERNAL_PREFIX) == 0;
if ((isAnonymous && act == gaREMOVEIFANON) || act == gaREMOVE)
_symbols.erase(iter);
return sym;
}
++iter;
}
return Symbol();
}
Symbol SymbolTable::getSymbol(const QString &name, int scope) const
{
QHash<QString, Symbol>::const_iterator iter = _symbols.find(name);
while (iter != _symbols.end() && iter.key() == name) {
if ( iter.value()._scope == scope) {
return iter.value();
}
++iter;
}
return Symbol();
}
bool SymbolTable::isNumerical(const QVariant& var) {
return isRealNumerical(var) || isIntegerNumerical(var);
}
bool SymbolTable::isRealNumerical(const QVariant& var) {
QString tpname = var.typeName();
bool ok = var.type() == QMetaType::Float || var.type() == QMetaType::Double;
if ( ok)
return true;
var.toDouble(&ok);
return ok;
}
bool SymbolTable::isIntegerNumerical(const QVariant& var) {
QMetaType::Type tp = static_cast<QMetaType::Type>(var.type());
bool ok = tp == QMetaType::Int || tp == QMetaType::UInt ||
tp == QMetaType::LongLong || tp == QMetaType::ULongLong ||
tp == QMetaType::Long || tp == QMetaType::ULong ||
tp == QMetaType::Short || tp == QMetaType::UShort ||
tp == QMetaType::Char || tp == QMetaType::UChar;
if ( ok)
return true;
var.toLongLong(&ok);
if ( ok)
return true;
var.toULongLong(&ok);
return ok;
}
bool SymbolTable::isDataLink(const QVariant& value) {
QString resolvedv = value.toString();
if ( !resolvedv.contains(QRegExp("\\\\|/"))) {
resolvedv = Ilwis::context()->workingCatalog()->resolve(resolvedv);
if ( resolvedv == sUNDEF)
return false;
}
return true;
}
QString SymbolTable::newAnonym()
{
_symbolid++;
return QString("%1%2").arg(INTERNAL_PREFIX).arg(_symbolid);
}
Symbol::Symbol(int scope, quint64 tp, const QVariant &v) : _type(tp), _scope(scope), _var(v)
{
}
bool Symbol::isValid() const
{
return _var.isValid() && _scope != iUNDEF;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: basegfxfactory.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2004-11-26 20:58:35 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef INCLUDED_RTL_INSTANCE_HXX
#include <rtl/instance.hxx>
#endif
#ifndef INCLUDED_OSL_GETGLOBALMUTEX_HXX
#include <osl/getglobalmutex.hxx>
#endif
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#ifndef _DRAFTS_COM_SUN_STAR_RENDERING_INTERPOLATIONMODE_HPP_
#include <drafts/com/sun/star/rendering/InterpolationMode.hpp>
#endif
#ifndef _BGFX_POLYGON_B2DPOLYGON_HXX
#include <basegfx/polygon/b2dpolygon.hxx>
#endif
#ifndef _BGFX_POLYGON_B2DPOLYPOLYGON_HXX
#include <basegfx/polygon/b2dpolypolygon.hxx>
#endif
#ifndef _BGFX_TOOLS_CANVASTOOLS_HXX
#include <basegfx/tools/canvastools.hxx>
#endif
#include <cppcanvas/basegfxfactory.hxx>
#include <implpolypolygon.hxx>
#include <implbitmap.hxx>
#include <impltext.hxx>
using namespace ::drafts::com::sun::star;
using namespace ::com::sun::star;
namespace cppcanvas
{
/* Singleton handling */
struct InitInstance2
{
BaseGfxFactory* operator()()
{
return new BaseGfxFactory();
}
};
BaseGfxFactory& BaseGfxFactory::getInstance()
{
return *rtl_Instance< BaseGfxFactory, InitInstance2, ::osl::MutexGuard,
::osl::GetGlobalMutex >::create(
InitInstance2(), ::osl::GetGlobalMutex());
}
BaseGfxFactory::BaseGfxFactory()
{
}
BaseGfxFactory::~BaseGfxFactory()
{
}
PolyPolygonSharedPtr BaseGfxFactory::createPolyPolygon( const CanvasSharedPtr& rCanvas,
const ::basegfx::B2DPolygon& rPoly ) const
{
OSL_ENSURE( rCanvas.get() != NULL &&
rCanvas->getUNOCanvas().is(),
"BaseGfxFactory::createPolyPolygon(): Invalid canvas" );
if( rCanvas.get() == NULL )
return PolyPolygonSharedPtr();
uno::Reference< rendering::XCanvas > xCanvas( rCanvas->getUNOCanvas() );
if( !xCanvas.is() )
return PolyPolygonSharedPtr();
return PolyPolygonSharedPtr(
new internal::ImplPolyPolygon( rCanvas,
::basegfx::unotools::xPolyPolygonFromB2DPolygon(
xCanvas->getDevice(),
rPoly) ) );
}
PolyPolygonSharedPtr BaseGfxFactory::createPolyPolygon( const CanvasSharedPtr& rCanvas,
const ::basegfx::B2DPolyPolygon& rPolyPoly ) const
{
OSL_ENSURE( rCanvas.get() != NULL &&
rCanvas->getUNOCanvas().is(),
"BaseGfxFactory::createPolyPolygon(): Invalid canvas" );
if( rCanvas.get() == NULL )
return PolyPolygonSharedPtr();
uno::Reference< rendering::XCanvas > xCanvas( rCanvas->getUNOCanvas() );
if( !xCanvas.is() )
return PolyPolygonSharedPtr();
return PolyPolygonSharedPtr(
new internal::ImplPolyPolygon( rCanvas,
::basegfx::unotools::xPolyPolygonFromB2DPolyPolygon(
xCanvas->getDevice(),
rPolyPoly) ) );
}
BitmapSharedPtr BaseGfxFactory::createBitmap( const CanvasSharedPtr& rCanvas,
const ::basegfx::B2ISize& rSize ) const
{
OSL_ENSURE( rCanvas.get() != NULL &&
rCanvas->getUNOCanvas().is(),
"BaseGfxFactory::createBitmap(): Invalid canvas" );
if( rCanvas.get() == NULL )
return BitmapSharedPtr();
uno::Reference< rendering::XCanvas > xCanvas( rCanvas->getUNOCanvas() );
if( !xCanvas.is() )
return BitmapSharedPtr();
return BitmapSharedPtr(
new internal::ImplBitmap( rCanvas,
xCanvas->getDevice()->createCompatibleBitmap(
::basegfx::unotools::integerSize2DFromB2ISize(rSize) ) ) );
}
BitmapSharedPtr BaseGfxFactory::createAlphaBitmap( const CanvasSharedPtr& rCanvas,
const ::basegfx::B2ISize& rSize ) const
{
OSL_ENSURE( rCanvas.get() != NULL &&
rCanvas->getUNOCanvas().is(),
"BaseGfxFactory::createBitmap(): Invalid canvas" );
if( rCanvas.get() == NULL )
return BitmapSharedPtr();
uno::Reference< rendering::XCanvas > xCanvas( rCanvas->getUNOCanvas() );
if( !xCanvas.is() )
return BitmapSharedPtr();
return BitmapSharedPtr(
new internal::ImplBitmap( rCanvas,
xCanvas->getDevice()->createCompatibleAlphaBitmap(
::basegfx::unotools::integerSize2DFromB2ISize(rSize) ) ) );
}
TextSharedPtr BaseGfxFactory::createText( const CanvasSharedPtr& rCanvas, const ::rtl::OUString& rText ) const
{
return TextSharedPtr( new internal::ImplText( rCanvas,
rText ) );
}
}
<commit_msg>INTEGRATION: CWS presfixes01 (1.3.6); FILE MERGED 2005/02/16 11:14:34 fs 1.3.6.1: #i42558# drafts.com.sun.star.drawing/rendering/geometry moved to com.sun.star.*<commit_after>/*************************************************************************
*
* $RCSfile: basegfxfactory.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: vg $ $Date: 2005-03-10 13:27:52 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef INCLUDED_RTL_INSTANCE_HXX
#include <rtl/instance.hxx>
#endif
#ifndef INCLUDED_OSL_GETGLOBALMUTEX_HXX
#include <osl/getglobalmutex.hxx>
#endif
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#ifndef _COM_SUN_STAR_RENDERING_INTERPOLATIONMODE_HPP_
#include <com/sun/star/rendering/InterpolationMode.hpp>
#endif
#ifndef _BGFX_POLYGON_B2DPOLYGON_HXX
#include <basegfx/polygon/b2dpolygon.hxx>
#endif
#ifndef _BGFX_POLYGON_B2DPOLYPOLYGON_HXX
#include <basegfx/polygon/b2dpolypolygon.hxx>
#endif
#ifndef _BGFX_TOOLS_CANVASTOOLS_HXX
#include <basegfx/tools/canvastools.hxx>
#endif
#include <cppcanvas/basegfxfactory.hxx>
#include <implpolypolygon.hxx>
#include <implbitmap.hxx>
#include <impltext.hxx>
using namespace ::com::sun::star;
using namespace ::com::sun::star;
namespace cppcanvas
{
/* Singleton handling */
struct InitInstance2
{
BaseGfxFactory* operator()()
{
return new BaseGfxFactory();
}
};
BaseGfxFactory& BaseGfxFactory::getInstance()
{
return *rtl_Instance< BaseGfxFactory, InitInstance2, ::osl::MutexGuard,
::osl::GetGlobalMutex >::create(
InitInstance2(), ::osl::GetGlobalMutex());
}
BaseGfxFactory::BaseGfxFactory()
{
}
BaseGfxFactory::~BaseGfxFactory()
{
}
PolyPolygonSharedPtr BaseGfxFactory::createPolyPolygon( const CanvasSharedPtr& rCanvas,
const ::basegfx::B2DPolygon& rPoly ) const
{
OSL_ENSURE( rCanvas.get() != NULL &&
rCanvas->getUNOCanvas().is(),
"BaseGfxFactory::createPolyPolygon(): Invalid canvas" );
if( rCanvas.get() == NULL )
return PolyPolygonSharedPtr();
uno::Reference< rendering::XCanvas > xCanvas( rCanvas->getUNOCanvas() );
if( !xCanvas.is() )
return PolyPolygonSharedPtr();
return PolyPolygonSharedPtr(
new internal::ImplPolyPolygon( rCanvas,
::basegfx::unotools::xPolyPolygonFromB2DPolygon(
xCanvas->getDevice(),
rPoly) ) );
}
PolyPolygonSharedPtr BaseGfxFactory::createPolyPolygon( const CanvasSharedPtr& rCanvas,
const ::basegfx::B2DPolyPolygon& rPolyPoly ) const
{
OSL_ENSURE( rCanvas.get() != NULL &&
rCanvas->getUNOCanvas().is(),
"BaseGfxFactory::createPolyPolygon(): Invalid canvas" );
if( rCanvas.get() == NULL )
return PolyPolygonSharedPtr();
uno::Reference< rendering::XCanvas > xCanvas( rCanvas->getUNOCanvas() );
if( !xCanvas.is() )
return PolyPolygonSharedPtr();
return PolyPolygonSharedPtr(
new internal::ImplPolyPolygon( rCanvas,
::basegfx::unotools::xPolyPolygonFromB2DPolyPolygon(
xCanvas->getDevice(),
rPolyPoly) ) );
}
BitmapSharedPtr BaseGfxFactory::createBitmap( const CanvasSharedPtr& rCanvas,
const ::basegfx::B2ISize& rSize ) const
{
OSL_ENSURE( rCanvas.get() != NULL &&
rCanvas->getUNOCanvas().is(),
"BaseGfxFactory::createBitmap(): Invalid canvas" );
if( rCanvas.get() == NULL )
return BitmapSharedPtr();
uno::Reference< rendering::XCanvas > xCanvas( rCanvas->getUNOCanvas() );
if( !xCanvas.is() )
return BitmapSharedPtr();
return BitmapSharedPtr(
new internal::ImplBitmap( rCanvas,
xCanvas->getDevice()->createCompatibleBitmap(
::basegfx::unotools::integerSize2DFromB2ISize(rSize) ) ) );
}
BitmapSharedPtr BaseGfxFactory::createAlphaBitmap( const CanvasSharedPtr& rCanvas,
const ::basegfx::B2ISize& rSize ) const
{
OSL_ENSURE( rCanvas.get() != NULL &&
rCanvas->getUNOCanvas().is(),
"BaseGfxFactory::createBitmap(): Invalid canvas" );
if( rCanvas.get() == NULL )
return BitmapSharedPtr();
uno::Reference< rendering::XCanvas > xCanvas( rCanvas->getUNOCanvas() );
if( !xCanvas.is() )
return BitmapSharedPtr();
return BitmapSharedPtr(
new internal::ImplBitmap( rCanvas,
xCanvas->getDevice()->createCompatibleAlphaBitmap(
::basegfx::unotools::integerSize2DFromB2ISize(rSize) ) ) );
}
TextSharedPtr BaseGfxFactory::createText( const CanvasSharedPtr& rCanvas, const ::rtl::OUString& rText ) const
{
return TextSharedPtr( new internal::ImplText( rCanvas,
rText ) );
}
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2012-2013 Plenluno All rights reserved.
#include <gtest/gtest.h>
#include <float.h>
#include <libj/array_list.h>
#include <libj/error.h>
#include <libj/json.h>
#include <libj/js_array.h>
#include <libj/js_object.h>
#include <libj/map.h>
#include <libj/string_builder.h>
namespace libj {
TEST(GTestJson, TestStringify) {
ASSERT_FALSE(json::stringify(UNDEFINED));
ASSERT_TRUE(json::stringify(static_cast<Byte>(3))
->equals(String::create("3")));
ASSERT_TRUE(json::stringify(static_cast<Short>(4))
->equals(String::create("4")));
ASSERT_TRUE(json::stringify(static_cast<Int>(5))
->equals(String::create("5")));
ASSERT_TRUE(json::stringify(static_cast<Long>(6))
->equals(String::create("6")));
ASSERT_TRUE(json::stringify(static_cast<Float>(2.5))
->equals(String::create("2.5")));
ASSERT_TRUE(json::stringify(static_cast<Double>(3.5))
->equals(String::create("3.5")));
ASSERT_TRUE(json::stringify(DBL_MAX)
->equals(String::create("1.7976931348623157e+308")));
ASSERT_TRUE(json::stringify(-DBL_MIN)
->equals(String::create("-2.2250738585072014e-308")));
ASSERT_TRUE(json::stringify(true)
->equals(String::create("true")));
ASSERT_TRUE(json::stringify(false)
->equals(String::create("false")));
ASSERT_TRUE(json::stringify(Object::null())
->equals(String::create("null")));
ASSERT_TRUE(json::stringify(String::create("456"))
->equals(String::create("\"456\"")));
ASSERT_TRUE(json::stringify(Map::create())
->equals(String::create("{}")));
ASSERT_TRUE(json::stringify(ArrayList::create())
->equals(String::create("[]")));
Map::Ptr m = Map::create();
m->put(3, false);
m->put(String::create("w"), UNDEFINED);
m->put(String::create("x"), 123);
m->put(String::create("y"), String::create("456"));
m->put(String::create("z"), String::null());
ASSERT_TRUE(json::stringify(m)
->equals(String::create("{\"x\":123,\"y\":\"456\",\"z\":null}")));
ArrayList::Ptr a = ArrayList::create();
a->add(3);
a->add(UNDEFINED);
a->add(false);
ASSERT_TRUE(json::stringify(a)
->equals(String::create("[3,null,false]")));
}
TEST(GTestJson, TestRecursiveStringify) {
Map::Ptr m = Map::create();
m->put(String::create("x"), 123);
m->put(String::create("y"), ArrayList::create());
JsObject::Ptr jo = JsObject::create();
jo->put(3, false);
jo->put(Object::null(), m);
ASSERT_TRUE(json::stringify(jo)->equals(
String::create("{\"3\":false,\"null\":{\"x\":123,\"y\":[]}}")));
ArrayList::Ptr a = ArrayList::create();
a->add(3);
a->add(m);
JsArray::Ptr ja = JsArray::create();
ja->add(UNDEFINED);
ja->add(Object::null());
ja->add(a);
ASSERT_TRUE(json::stringify(ja)->equals(
String::create("[null,null,[3,{\"x\":123,\"y\":[]}]]")));
}
TEST(GTestJson, TestParse) {
String::CPtr json =
String::create("{\"x\":123,\"y\":[3.5,false],\"z\":null}");
Value v = json::parse(json);
ASSERT_TRUE(v.instanceof(Type<Map>::id()));
JsObject::CPtr m = toCPtr<JsObject>(v);
ASSERT_EQ(3, m->size());
Value xv = m->get(String::create("x"));
ASSERT_EQ(Type<Long>::id(), xv.type());
Long l;
to<Long>(xv, &l);
ASSERT_EQ(123, l);
Value yv = m->get(String::create("y"));
ASSERT_TRUE(yv.instanceof(Type<ArrayList>::id()));
JsArray::CPtr a = toCPtr<JsArray>(yv);
Value a0 = a->get(0);
ASSERT_EQ(Type<Double>::id(), a0.type());
Double d;
to<Double>(a0, &d);
ASSERT_EQ(3.5, d);
Value a1 = a->get(1);
ASSERT_EQ(Type<Boolean>::id(), a1.type());
Boolean b;
to<Boolean>(a1, &b);
ASSERT_FALSE(b);
Value zv = m->get(String::create("z"));
ASSERT_TRUE(zv.equals(Object::null()));
}
TEST(GTestJson, TestParseString) {
String::CPtr s = String::create("\"\\u0026\"");
ASSERT_TRUE(json::parse(s).equals(String::create("&")));
String::CPtr s1 = String::create("\"\\ud84c\\udfd0\"");
#ifdef LIBJ_USE_UTF32
String::CPtr s2 = String::create(0x233d0);
#else
std::u16string s16;
s16 += static_cast<char16_t>(0xd84c);
s16 += static_cast<char16_t>(0xdfd0);
String::CPtr s2 = String::create(s16);
#endif
ASSERT_TRUE(json::parse(s1).equals(s2));
std::u32string s32;
s32 += 0x3042;
s32 += 0x2000b;
s = String::create(s32);
StringBuilder::Ptr sb = StringBuilder::create();
sb->appendCStr("\"");
sb->append(s);
sb->appendCStr("\"");
ASSERT_TRUE(json::parse(sb->toString()).equals(s));
}
TEST(GTestJson, TestParseNumber) {
String::CPtr s1 = String::create("1.0");
Value v1 = json::parse(s1);
ASSERT_EQ(Type<Long>::id(), v1.type());
ASSERT_TRUE(v1.equals(1LL));
String::CPtr s2 = String::create("9007199254740990");
Value v2 = json::parse(s2);
ASSERT_TRUE(v2.equals(9007199254740990LL));
String::CPtr s3 = String::create("9007199254740991");
Value v3 = json::parse(s3);
ASSERT_TRUE(v3.equals(9007199254740991LL));
String::CPtr s4 = String::create("9007199254740992");
Value v4 = json::parse(s4);
ASSERT_TRUE(v4.equals(9007199254740992.0));
String::CPtr s5 = String::create("9007199254740993");
Value v5 = json::parse(s5);
ASSERT_TRUE(v5.equals(9007199254740992.0));
String::CPtr s6 = String::create("-9007199254740990");
Value v6 = json::parse(s6);
ASSERT_TRUE(v6.equals(-9007199254740990LL));
String::CPtr s7 = String::create("-9007199254740991");
Value v7 = json::parse(s7);
ASSERT_TRUE(v7.equals(-9007199254740991LL));
String::CPtr s8 = String::create("-9007199254740992");
Value v8 = json::parse(s8);
ASSERT_TRUE(v8.equals(-9007199254740992.0));
String::CPtr s9 = String::create("-9007199254740993");
Value v9 = json::parse(s9);
ASSERT_TRUE(v9.equals(-9007199254740992.0));
String::CPtr s10 = String::create("1.7976931348623157e+308");
Value v10 = json::parse(s10);
ASSERT_TRUE(v10.equals(1.7976931348623157e+308));
}
TEST(GTestJson, TestParseError) {
Value v1 = json::parse(String::null());
ASSERT_TRUE(v1.instanceof(Type<Error>::id()));
Value v2 = json::parse(String::create("\""));
ASSERT_TRUE(v2.instanceof(Type<Error>::id()));
}
TEST(GTestJson, TestEscape) {
String::CPtr str = String::create("\b\f\n\r\t'\"\\");
String::CPtr json = String::create("\"\\b\\f\\n\\r\\t'\\\"\\\\\"");
String::CPtr s = toCPtr<String>(json::parse(json));
ASSERT_TRUE(s->equals(str));
s = json::stringify(str);
ASSERT_TRUE(s->equals(json));
}
} // namespace libj
<commit_msg>add tests of instanceof<commit_after>// Copyright (c) 2012-2013 Plenluno All rights reserved.
#include <gtest/gtest.h>
#include <float.h>
#include <libj/array_list.h>
#include <libj/error.h>
#include <libj/json.h>
#include <libj/js_array.h>
#include <libj/js_object.h>
#include <libj/map.h>
#include <libj/string_builder.h>
namespace libj {
TEST(GTestJson, TestStringify) {
ASSERT_FALSE(json::stringify(UNDEFINED));
ASSERT_TRUE(json::stringify(static_cast<Byte>(3))
->equals(String::create("3")));
ASSERT_TRUE(json::stringify(static_cast<Short>(4))
->equals(String::create("4")));
ASSERT_TRUE(json::stringify(static_cast<Int>(5))
->equals(String::create("5")));
ASSERT_TRUE(json::stringify(static_cast<Long>(6))
->equals(String::create("6")));
ASSERT_TRUE(json::stringify(static_cast<Float>(2.5))
->equals(String::create("2.5")));
ASSERT_TRUE(json::stringify(static_cast<Double>(3.5))
->equals(String::create("3.5")));
ASSERT_TRUE(json::stringify(DBL_MAX)
->equals(String::create("1.7976931348623157e+308")));
ASSERT_TRUE(json::stringify(-DBL_MIN)
->equals(String::create("-2.2250738585072014e-308")));
ASSERT_TRUE(json::stringify(true)
->equals(String::create("true")));
ASSERT_TRUE(json::stringify(false)
->equals(String::create("false")));
ASSERT_TRUE(json::stringify(Object::null())
->equals(String::create("null")));
ASSERT_TRUE(json::stringify(String::create("456"))
->equals(String::create("\"456\"")));
ASSERT_TRUE(json::stringify(Map::create())
->equals(String::create("{}")));
ASSERT_TRUE(json::stringify(ArrayList::create())
->equals(String::create("[]")));
Map::Ptr m = Map::create();
m->put(3, false);
m->put(String::create("w"), UNDEFINED);
m->put(String::create("x"), 123);
m->put(String::create("y"), String::create("456"));
m->put(String::create("z"), String::null());
ASSERT_TRUE(json::stringify(m)
->equals(String::create("{\"x\":123,\"y\":\"456\",\"z\":null}")));
ArrayList::Ptr a = ArrayList::create();
a->add(3);
a->add(UNDEFINED);
a->add(false);
ASSERT_TRUE(json::stringify(a)
->equals(String::create("[3,null,false]")));
}
TEST(GTestJson, TestRecursiveStringify) {
Map::Ptr m = Map::create();
m->put(String::create("x"), 123);
m->put(String::create("y"), ArrayList::create());
JsObject::Ptr jo = JsObject::create();
jo->put(3, false);
jo->put(Object::null(), m);
ASSERT_TRUE(json::stringify(jo)->equals(
String::create("{\"3\":false,\"null\":{\"x\":123,\"y\":[]}}")));
ArrayList::Ptr a = ArrayList::create();
a->add(3);
a->add(m);
JsArray::Ptr ja = JsArray::create();
ja->add(UNDEFINED);
ja->add(Object::null());
ja->add(a);
ASSERT_TRUE(json::stringify(ja)->equals(
String::create("[null,null,[3,{\"x\":123,\"y\":[]}]]")));
}
TEST(GTestJson, TestParse) {
String::CPtr json =
String::create("{\"x\":123,\"y\":[3.5,false],\"z\":null}");
Value v = json::parse(json);
ASSERT_TRUE(v.instanceof(Type<Map>::id()));
ASSERT_TRUE(v.instanceof(Type<JsObject>::id()));
JsObject::CPtr m = toCPtr<JsObject>(v);
ASSERT_EQ(3, m->size());
Value xv = m->get(String::create("x"));
ASSERT_EQ(Type<Long>::id(), xv.type());
Long l;
to<Long>(xv, &l);
ASSERT_EQ(123, l);
Value yv = m->get(String::create("y"));
ASSERT_TRUE(yv.instanceof(Type<ArrayList>::id()));
ASSERT_TRUE(yv.instanceof(Type<JsArray>::id()));
JsArray::CPtr a = toCPtr<JsArray>(yv);
Value a0 = a->get(0);
ASSERT_EQ(Type<Double>::id(), a0.type());
Double d;
to<Double>(a0, &d);
ASSERT_EQ(3.5, d);
Value a1 = a->get(1);
ASSERT_EQ(Type<Boolean>::id(), a1.type());
Boolean b;
to<Boolean>(a1, &b);
ASSERT_FALSE(b);
Value zv = m->get(String::create("z"));
ASSERT_TRUE(zv.equals(Object::null()));
}
TEST(GTestJson, TestParseString) {
String::CPtr s = String::create("\"\\u0026\"");
ASSERT_TRUE(json::parse(s).equals(String::create("&")));
String::CPtr s1 = String::create("\"\\ud84c\\udfd0\"");
#ifdef LIBJ_USE_UTF32
String::CPtr s2 = String::create(0x233d0);
#else
std::u16string s16;
s16 += static_cast<char16_t>(0xd84c);
s16 += static_cast<char16_t>(0xdfd0);
String::CPtr s2 = String::create(s16);
#endif
ASSERT_TRUE(json::parse(s1).equals(s2));
std::u32string s32;
s32 += 0x3042;
s32 += 0x2000b;
s = String::create(s32);
StringBuilder::Ptr sb = StringBuilder::create();
sb->appendCStr("\"");
sb->append(s);
sb->appendCStr("\"");
ASSERT_TRUE(json::parse(sb->toString()).equals(s));
}
TEST(GTestJson, TestParseNumber) {
String::CPtr s1 = String::create("1.0");
Value v1 = json::parse(s1);
ASSERT_EQ(Type<Long>::id(), v1.type());
ASSERT_TRUE(v1.equals(1LL));
String::CPtr s2 = String::create("9007199254740990");
Value v2 = json::parse(s2);
ASSERT_TRUE(v2.equals(9007199254740990LL));
String::CPtr s3 = String::create("9007199254740991");
Value v3 = json::parse(s3);
ASSERT_TRUE(v3.equals(9007199254740991LL));
String::CPtr s4 = String::create("9007199254740992");
Value v4 = json::parse(s4);
ASSERT_TRUE(v4.equals(9007199254740992.0));
String::CPtr s5 = String::create("9007199254740993");
Value v5 = json::parse(s5);
ASSERT_TRUE(v5.equals(9007199254740992.0));
String::CPtr s6 = String::create("-9007199254740990");
Value v6 = json::parse(s6);
ASSERT_TRUE(v6.equals(-9007199254740990LL));
String::CPtr s7 = String::create("-9007199254740991");
Value v7 = json::parse(s7);
ASSERT_TRUE(v7.equals(-9007199254740991LL));
String::CPtr s8 = String::create("-9007199254740992");
Value v8 = json::parse(s8);
ASSERT_TRUE(v8.equals(-9007199254740992.0));
String::CPtr s9 = String::create("-9007199254740993");
Value v9 = json::parse(s9);
ASSERT_TRUE(v9.equals(-9007199254740992.0));
String::CPtr s10 = String::create("1.7976931348623157e+308");
Value v10 = json::parse(s10);
ASSERT_TRUE(v10.equals(1.7976931348623157e+308));
}
TEST(GTestJson, TestParseError) {
Value v1 = json::parse(String::null());
ASSERT_TRUE(v1.instanceof(Type<Error>::id()));
Value v2 = json::parse(String::create("\""));
ASSERT_TRUE(v2.instanceof(Type<Error>::id()));
}
TEST(GTestJson, TestEscape) {
String::CPtr str = String::create("\b\f\n\r\t'\"\\");
String::CPtr json = String::create("\"\\b\\f\\n\\r\\t'\\\"\\\\\"");
String::CPtr s = toCPtr<String>(json::parse(json));
ASSERT_TRUE(s->equals(str));
s = json::stringify(str);
ASSERT_TRUE(s->equals(json));
}
} // namespace libj
<|endoftext|>
|
<commit_before>#include "HttpStream.hpp"
BEGIN_INANITY_NET
http_parser_settings HttpStream::settings = {
HttpStream::OnMessageBegin,
HttpStream::OnUrl,
HttpStream::OnStatus,
HttpStream::OnHeaderField,
HttpStream::OnHeaderValue,
HttpStream::OnHeadersComplete,
HttpStream::OnBody,
HttpStream::OnMessageComplete
};
HttpStream::HttpStream(ptr<OutputStream> outputStream, enum http_parser_type type) :
outputStream(outputStream), lastWasHeaderField(false), completed(false)
{
parser.data = this;
http_parser_init(&parser, type);
}
ptr<HttpStream> HttpStream::CreateRequestStream(ptr<OutputStream> outputStream)
{
return NEW(HttpStream(outputStream, HTTP_REQUEST));
}
ptr<HttpStream> HttpStream::CreateResponseStream(ptr<OutputStream> outputStream)
{
return NEW(HttpStream(outputStream, HTTP_RESPONSE));
}
void HttpStream::Write(const void* data, size_t size)
{
http_parser_execute(&parser, &settings, (const char*)data, size);
}
void HttpStream::End()
{
http_parser_execute(&parser, &settings, 0, 0);
}
bool HttpStream::IsCompleted() const
{
return completed;
}
const HttpStream::Headers& HttpStream::GetHeaders() const
{
return headers;
}
int HttpStream::OnMessageBegin(http_parser* parser)
{
return 0;
}
int HttpStream::OnUrl(http_parser* parser, const char* data, size_t size)
{
return 0;
}
int HttpStream::OnStatus(http_parser* parser, const char* data, size_t size)
{
return 0;
}
int HttpStream::OnHeaderField(http_parser* parser, const char* data, size_t size)
{
HttpStream* stream = (HttpStream*)parser->data;
if(stream->lastWasHeaderField)
stream->headers.back().first += String(data, size);
else
stream->headers.push_back(std::make_pair(String(data, size), String()));
return 0;
}
int HttpStream::OnHeaderValue(http_parser* parser, const char* data, size_t size)
{
HttpStream* stream = (HttpStream*)parser->data;
stream->headers.back().second += String(data, size);
return 0;
}
int HttpStream::OnHeadersComplete(http_parser* parser)
{
return 0;
}
int HttpStream::OnBody(http_parser* parser, const char* data, size_t size)
{
HttpStream* stream = (HttpStream*)parser->data;
stream->outputStream->Write(data, size);
return 0;
}
int HttpStream::OnMessageComplete(http_parser* parser)
{
HttpStream* stream = (HttpStream*)parser->data;
stream->completed = true;
return 0;
}
END_INANITY_NET
<commit_msg>fail HttpStream if status code is not 2**<commit_after>#include "HttpStream.hpp"
BEGIN_INANITY_NET
http_parser_settings HttpStream::settings = {
HttpStream::OnMessageBegin,
HttpStream::OnUrl,
HttpStream::OnStatus,
HttpStream::OnHeaderField,
HttpStream::OnHeaderValue,
HttpStream::OnHeadersComplete,
HttpStream::OnBody,
HttpStream::OnMessageComplete
};
HttpStream::HttpStream(ptr<OutputStream> outputStream, enum http_parser_type type) :
outputStream(outputStream), lastWasHeaderField(false), completed(false)
{
parser.data = this;
http_parser_init(&parser, type);
}
ptr<HttpStream> HttpStream::CreateRequestStream(ptr<OutputStream> outputStream)
{
return NEW(HttpStream(outputStream, HTTP_REQUEST));
}
ptr<HttpStream> HttpStream::CreateResponseStream(ptr<OutputStream> outputStream)
{
return NEW(HttpStream(outputStream, HTTP_RESPONSE));
}
void HttpStream::Write(const void* data, size_t size)
{
http_parser_execute(&parser, &settings, (const char*)data, size);
}
void HttpStream::End()
{
http_parser_execute(&parser, &settings, 0, 0);
}
bool HttpStream::IsCompleted() const
{
return completed;
}
const HttpStream::Headers& HttpStream::GetHeaders() const
{
return headers;
}
int HttpStream::OnMessageBegin(http_parser* parser)
{
return 0;
}
int HttpStream::OnUrl(http_parser* parser, const char* data, size_t size)
{
return 0;
}
int HttpStream::OnStatus(http_parser* parser, const char* data, size_t size)
{
return (parser->status_code >= 200 && parser->status_code <= 299) ? 0 : 1;
}
int HttpStream::OnHeaderField(http_parser* parser, const char* data, size_t size)
{
HttpStream* stream = (HttpStream*)parser->data;
if(stream->lastWasHeaderField)
stream->headers.back().first += String(data, size);
else
stream->headers.push_back(std::make_pair(String(data, size), String()));
return 0;
}
int HttpStream::OnHeaderValue(http_parser* parser, const char* data, size_t size)
{
HttpStream* stream = (HttpStream*)parser->data;
stream->headers.back().second += String(data, size);
return 0;
}
int HttpStream::OnHeadersComplete(http_parser* parser)
{
return 0;
}
int HttpStream::OnBody(http_parser* parser, const char* data, size_t size)
{
HttpStream* stream = (HttpStream*)parser->data;
stream->outputStream->Write(data, size);
return 0;
}
int HttpStream::OnMessageComplete(http_parser* parser)
{
HttpStream* stream = (HttpStream*)parser->data;
stream->completed = true;
return 0;
}
END_INANITY_NET
<|endoftext|>
|
<commit_before>#include "search.hpp"
#include "idastar.hpp"
#include "astar.hpp"
#include "astar-dump.hpp"
#include "wastar.hpp"
#include "greedy.hpp"
#include "bugsy.hpp"
#include "bugsy-slim.hpp"
#include "arastar.hpp"
#include "rtastar.hpp"
#include "speediest.hpp"
#include "flrtastar.hpp"
#include "lrtastar.hpp"
#include "lsslrtastar.hpp"
#include <cstddef>
#include <cstdio>
// Functions for conveniently defining a new main
// function for a domain.
void dfheader(FILE*);
void dffooter(FILE*);
void dfpair(FILE *, const char *, const char *, ...);
void dfprocstatus(FILE*);
void fatal(const char*, ...);
template<class D> SearchAlgorithm<D> *getsearch(int argc, const char *argv[]);
template<class D> Result<D> search(D &d, int argc, const char *argv[]) {
SearchAlgorithm<D> *srch = getsearch<D>(argc, argv);
if (!srch && argc > 1)
fatal("Unknow search algorithm: %s", argv[1]);
if (!srch)
fatal("Must specify a search algorithm");
typename D::State s0 = d.initialstate();
dfpair(stdout, "initial heuristic", "%f", (double) d.h(s0));
dfpair(stdout, "initial distance", "%f", (double) d.d(s0));
dfpair(stdout, "algorithm", argv[1]);
try {
srch->search(d, s0);
} catch (std::bad_alloc&) {
dfpair(stdout, "out of memory", "%s", "true");
srch->res.path.clear();
srch->res.ops.clear();
srch->finish();
}
if (srch->res.path.size() > 0) {
dfpair(stdout, "final sol cost", "%f",
(double) d.pathcost(srch->res.path, srch->res.ops));
} else {
dfpair(stdout, "final sol cost", "%f", -1.0);
}
srch->output(stdout);
Result<D> res = srch->res;
delete srch;
return res;
}
template<class D> SearchAlgorithm<D> *getsearch(int argc, const char *argv[]) {
if (argc < 2)
fatal("No algorithm specified");
if (strcmp(argv[1], "idastar") == 0)
return new Idastar<D>(argc, argv);
else if (strcmp(argv[1], "astar-dump") == 0)
return new Astar_dump<D>(argc, argv);
else if (strcmp(argv[1], "astar") == 0)
return new Astar<D>(argc, argv);
else if (strcmp(argv[1], "wastar") == 0)
return new Wastar<D>(argc, argv);
else if (strcmp(argv[1], "greedy") == 0)
return new Greedy<D>(argc, argv);
else if (strcmp(argv[1], "speedy") == 0)
return new Greedy<D, true>(argc, argv);
else if (strcmp(argv[1], "bugsy") == 0)
return new Bugsy<D>(argc, argv);
else if (strcmp(argv[1], "bugsy-slim") == 0)
return new Bugsy_slim<D>(argc, argv);
else if (strcmp(argv[1], "arastar") == 0)
return new Arastar<D>(argc, argv);
else if (strcmp(argv[1], "arastarmon") == 0)
return new ArastarMon<D>(argc, argv);
else if (strcmp(argv[1], "rtastar") == 0)
return new Rtastar<D>(argc, argv);
else if (strcmp(argv[1], "speediest") == 0)
return new Speediest<D>(argc, argv);
else if (strcmp(argv[1], "lrtastar") == 0)
return new Lrtastar<D>(argc, argv);
else if (strcmp(argv[1], "lsslrtastar") == 0)
return new Lsslrtastar<D>(argc, argv);
else if (strcmp(argv[1], "flrtastar") == 0)
return new Flrtastar<D>(argc, argv);
fatal("Unknown algorithm: %s", argv[1]);
return NULL; // Unreachable
}
<commit_msg>added lrtastar<commit_after>#include "search.hpp"
#include "idastar.hpp"
#include "astar.hpp"
#include "astar-dump.hpp"
#include "wastar.hpp"
#include "greedy.hpp"
#include "bugsy.hpp"
#include "bugsy-slim.hpp"
#include "arastar.hpp"
#include "rtastar.hpp"
#include "speediest.hpp"
#include "lrtastar.hpp"
#include <cstddef>
#include <cstdio>
// Functions for conveniently defining a new main
// function for a domain.
void dfheader(FILE*);
void dffooter(FILE*);
void dfpair(FILE *, const char *, const char *, ...);
void dfprocstatus(FILE*);
void fatal(const char*, ...);
template<class D> SearchAlgorithm<D> *getsearch(int argc, const char *argv[]);
template<class D> Result<D> search(D &d, int argc, const char *argv[]) {
SearchAlgorithm<D> *srch = getsearch<D>(argc, argv);
if (!srch && argc > 1)
fatal("Unknow search algorithm: %s", argv[1]);
if (!srch)
fatal("Must specify a search algorithm");
typename D::State s0 = d.initialstate();
dfpair(stdout, "initial heuristic", "%f", (double) d.h(s0));
dfpair(stdout, "initial distance", "%f", (double) d.d(s0));
dfpair(stdout, "algorithm", argv[1]);
try {
srch->search(d, s0);
} catch (std::bad_alloc&) {
dfpair(stdout, "out of memory", "%s", "true");
srch->res.path.clear();
srch->res.ops.clear();
srch->finish();
}
if (srch->res.path.size() > 0) {
dfpair(stdout, "final sol cost", "%f",
(double) d.pathcost(srch->res.path, srch->res.ops));
} else {
dfpair(stdout, "final sol cost", "%f", -1.0);
}
srch->output(stdout);
Result<D> res = srch->res;
delete srch;
return res;
}
template<class D> SearchAlgorithm<D> *getsearch(int argc, const char *argv[]) {
if (argc < 2)
fatal("No algorithm specified");
if (strcmp(argv[1], "idastar") == 0)
return new Idastar<D>(argc, argv);
else if (strcmp(argv[1], "astar-dump") == 0)
return new Astar_dump<D>(argc, argv);
else if (strcmp(argv[1], "astar") == 0)
return new Astar<D>(argc, argv);
else if (strcmp(argv[1], "wastar") == 0)
return new Wastar<D>(argc, argv);
else if (strcmp(argv[1], "greedy") == 0)
return new Greedy<D>(argc, argv);
else if (strcmp(argv[1], "speedy") == 0)
return new Greedy<D, true>(argc, argv);
else if (strcmp(argv[1], "bugsy") == 0)
return new Bugsy<D>(argc, argv);
else if (strcmp(argv[1], "bugsy-slim") == 0)
return new Bugsy_slim<D>(argc, argv);
else if (strcmp(argv[1], "arastar") == 0)
return new Arastar<D>(argc, argv);
else if (strcmp(argv[1], "arastarmon") == 0)
return new ArastarMon<D>(argc, argv);
else if (strcmp(argv[1], "rtastar") == 0)
return new Rtastar<D>(argc, argv);
else if (strcmp(argv[1], "speediest") == 0)
return new Speediest<D>(argc, argv);
else if (strcmp(argv[1], "lrtastar") == 0)
return new Lrtastar<D>(argc, argv);
fatal("Unknown algorithm: %s", argv[1]);
return NULL; // Unreachable
}
<|endoftext|>
|
<commit_before>/*
+----------------------------------------------------------------------+
| PHP Version 5 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2012 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: Jani Taskinen <[email protected]> |
| Author: Patrick Reilly <[email protected]> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
extern "C" {
#include "php.h"
}
#include "php_v8js_macros.h"
#include <v8.h>
#include <map>
#include <vector>
/* global.exit - terminate execution */
V8JS_METHOD(exit) /* {{{ */
{
v8::V8::TerminateExecution();
return v8::Undefined();
}
/* }}} */
/* global.sleep - sleep for passed seconds */
V8JS_METHOD(sleep) /* {{{ */
{
php_sleep(args[0]->Int32Value());
return v8::Undefined();
}
/* }}} */
/* global.print - php print() */
V8JS_METHOD(print) /* {{{ */
{
int ret = 0;
TSRMLS_FETCH();
for (int i = 0; i < args.Length(); i++) {
v8::String::Utf8Value str(args[i]);
const char *cstr = ToCString(str);
ret = PHPWRITE(cstr, strlen(cstr));
}
return V8JS_INT(ret);
}
/* }}} */
static void _php_v8js_dumper(v8::Local<v8::Value> var, int level TSRMLS_DC) /* {{{ */
{
v8::String::Utf8Value str(var->ToDetailString());
const char *valstr = ToCString(str);
size_t valstr_len = (valstr) ? strlen(valstr) : 0;
if (level > 1) {
php_printf("%*c", (level - 1) * 2, ' ');
}
if (var->IsString())
{
php_printf("string(%d) \"%s\"\n", valstr_len, valstr);
}
else if (var->IsBoolean())
{
php_printf("bool(%s)\n", valstr);
}
else if (var->IsInt32() || var->IsUint32())
{
php_printf("int(%s)\n", valstr);
}
else if (var->IsNumber())
{
php_printf("float(%s)\n", valstr);
}
else if (var->IsDate())
{
php_printf("Date(%s)\n", valstr);
}
#if PHP_V8_API_VERSION >= 2003007
else if (var->IsRegExp())
{
php_printf("RegExp(%s)\n", valstr);
}
#endif
else if (var->IsArray())
{
v8::Local<v8::Array> array = v8::Local<v8::Array>::Cast(var);
uint32_t length = array->Length();
php_printf("array(%d) {\n", length);
for (unsigned i = 0; i < length; i++) {
php_printf("%*c[%d] =>\n", level * 2, ' ', i);
_php_v8js_dumper(array->Get(i), level + 1 TSRMLS_CC);
}
if (level > 1) {
php_printf("%*c", (level - 1) * 2, ' ');
}
ZEND_PUTS("}\n");
}
else if (var->IsObject())
{
v8::Local<v8::Object> object = v8::Local<v8::Object>::Cast(var);
V8JS_GET_CLASS_NAME(cname, object);
if (var->IsFunction())
{
v8::String::Utf8Value csource(object->ToString());
php_printf("object(%s)#%d {\n%*c%s\n", ToCString(cname), object->GetIdentityHash(), level * 2 + 2, ' ', ToCString(csource));
}
else
{
v8::Local<v8::Array> keys = object->GetPropertyNames();
uint32_t length = keys->Length();
php_printf("object(%s)#%d (%d) {\n", ToCString(cname), object->GetIdentityHash(), length);
for (unsigned i = 0; i < length; i++) {
v8::Local<v8::String> key = keys->Get(i)->ToString();
v8::String::Utf8Value kname(key);
php_printf("%*c[\"%s\"] =>\n", level * 2, ' ', ToCString(kname));
_php_v8js_dumper(object->Get(key), level + 1 TSRMLS_CC);
}
}
if (level > 1) {
php_printf("%*c", (level - 1) * 2, ' ');
}
ZEND_PUTS("}\n");
}
else /* null, undefined, etc. */
{
php_printf("<%s>\n", valstr);
}
}
/* }}} */
/* global.var_dump - Dump JS values */
V8JS_METHOD(var_dump) /* {{{ */
{
int i;
TSRMLS_FETCH();
for (int i = 0; i < args.Length(); i++) {
_php_v8js_dumper(args[i], 1 TSRMLS_CC);
}
return V8JS_NULL;
}
/* }}} */
// TODO: Put this in php_v8js_context
std::map<char *, v8::Handle<v8::Object> > modules_loaded;
std::vector<char *> modules_stack;
void split_terms(char *identifier, std::vector<char *> &terms)
{
char *term = (char *)malloc(PATH_MAX), *ptr = term;
// Initialise the term string
*term = 0;
while (*identifier > 0) {
if (*identifier == '/') {
if (strlen(term) > 0) {
// Terminate term string and add to terms vector
*ptr++ = 0;
terms.push_back(strdup(term));
// Reset term string
memset(term, 0, strlen(term));
ptr = term;
}
} else {
*ptr++ = *identifier;
}
identifier++;
}
if (strlen(term) > 0) {
// Terminate term string and add to terms vector
*ptr++ = 0;
terms.push_back(strdup(term));
}
if (term > 0) {
free(term);
}
}
void normalize_identifier(char *identifier, char *normalised)
{
std::vector<char *> terms;
split_terms(identifier, terms);
std::vector<char *> normalised_terms;
for (std::vector<char *>::iterator it = terms.begin(); it != terms.end(); it++) {
char *term = *it;
if (!strcmp(term, "..")) {
normalised_terms.pop_back();
} else if (strcmp(term, ".")) {
normalised_terms.push_back(term);
}
}
// Initialise the normalised string
*normalised = 0;
for (std::vector<char *>::iterator it = normalised_terms.begin(); it != normalised_terms.end(); it++) {
char *term = *it;
if (strlen(normalised) > 0) {
strcat(normalised, "/");
}
strcat(normalised, term);
}
}
V8JS_METHOD(require)
{
v8::String::Utf8Value module_name_v8(args[0]);
// Make sure to duplicate the module name string so it doesn't get freed by the V8 garbage collector
char *module_name = strdup(ToCString(module_name_v8));
char *normalised_module_identifier = (char *)malloc(strlen(module_name));
normalize_identifier(module_name, normalised_module_identifier);
// Check for module cyclic dependencies
for (std::vector<char *>::iterator it = modules_stack.begin(); it != modules_stack.end(); ++it)
{
if (!strcmp(*it, normalised_module_identifier)) {
return v8::ThrowException(v8::String::New("Module cyclic dependency"));
}
}
// If we have already loaded and cached this module then use it
if (modules_loaded.count(normalised_module_identifier) > 0) {
return modules_loaded[normalised_module_identifier];
}
// Get the extension context
v8::Handle<v8::External> data = v8::Handle<v8::External>::Cast(args.Data());
php_v8js_ctx *c = static_cast<php_v8js_ctx*>(data->Value());
// Check that we have a module loader
if (c->module_loader == NULL) {
return v8::ThrowException(v8::String::New("No module loader"));
}
// Callback to PHP to load the module code
zval module_code;
zval *module_name_zend;
MAKE_STD_ZVAL(module_name_zend);
ZVAL_STRING(module_name_zend, normalised_module_identifier, 1);
zval* params[] = { module_name_zend };
if (FAILURE == call_user_function(EG(function_table), NULL, c->module_loader, &module_code, 1, params TSRMLS_CC)) {
return v8::ThrowException(v8::String::New("Module loader callback failed"));
}
// Convert the return value to string
if (Z_TYPE(module_code) != IS_STRING) {
convert_to_string(&module_code);
}
// Check that some code has been returned
if (!strlen(Z_STRVAL(module_code))) {
return v8::ThrowException(v8::String::New("Module loader callback did not return code"));
}
// Create a template for the global object and set the built-in global functions
v8::Handle<v8::ObjectTemplate> global = v8::ObjectTemplate::New();
global->Set(v8::String::New("print"), v8::FunctionTemplate::New(V8JS_MN(print)), v8::ReadOnly);
global->Set(v8::String::New("require"), v8::FunctionTemplate::New(V8JS_MN(require), v8::External::New(c)), v8::ReadOnly);
// Add the exports object in which the module returns its API
v8::Handle<v8::ObjectTemplate> exports_template = v8::ObjectTemplate::New();
v8::Handle<v8::Object> exports = exports_template->NewInstance();
global->Set(v8::String::New("exports"), exports);
// Each module gets its own context so different modules do not affect each other
v8::Persistent<v8::Context> context = v8::Context::New(NULL, global);
// Catch JS exceptions
v8::TryCatch try_catch;
// Enter the module context
v8::Context::Scope scope(context);
v8::HandleScope handle_scope;
// Set script identifier
v8::Local<v8::String> sname = V8JS_SYM("require");
v8::Local<v8::String> source = v8::String::New(Z_STRVAL(module_code));
// Create and compile script
v8::Local<v8::Script> script = v8::Script::New(source, sname);
// The script will be empty if there are compile errors
if (script.IsEmpty()) {
return v8::ThrowException(v8::String::New("Module script compile failed"));
}
// Add this module to the stack
modules_stack.push_back(normalised_module_identifier);
// Run script
v8::Local<v8::Value> result = script->Run();
// Remove this module from the stack
modules_stack.pop_back();
// Script possibly terminated, return immediately
if (!try_catch.CanContinue()) {
return v8::ThrowException(v8::String::New("Module script compile failed"));
}
// Handle runtime JS exceptions
if (try_catch.HasCaught()) {
// Rethrow the exception back to JS
return try_catch.ReThrow();
}
// Cache the module so it doesn't need to be compiled and run again
modules_loaded[normalised_module_identifier] = handle_scope.Close(exports);
return modules_loaded[normalised_module_identifier];
}
void php_v8js_register_methods(v8::Handle<v8::ObjectTemplate> global, php_v8js_ctx *c) /* {{{ */
{
global->Set(V8JS_SYM("exit"), v8::FunctionTemplate::New(V8JS_MN(exit)), v8::ReadOnly);
global->Set(V8JS_SYM("sleep"), v8::FunctionTemplate::New(V8JS_MN(sleep)), v8::ReadOnly);
global->Set(V8JS_SYM("print"), v8::FunctionTemplate::New(V8JS_MN(print)), v8::ReadOnly);
global->Set(V8JS_SYM("var_dump"), v8::FunctionTemplate::New(V8JS_MN(var_dump)), v8::ReadOnly);
global->Set(V8JS_SYM("require"), v8::FunctionTemplate::New(V8JS_MN(require), v8::External::New(c)), v8::ReadOnly);
}
/* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
<commit_msg>Handle exceptions throw from module loader callback.<commit_after>/*
+----------------------------------------------------------------------+
| PHP Version 5 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2012 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: Jani Taskinen <[email protected]> |
| Author: Patrick Reilly <[email protected]> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
extern "C" {
#include "php.h"
#include "zend_exceptions.h"
}
#include "php_v8js_macros.h"
#include <v8.h>
#include <map>
#include <vector>
/* global.exit - terminate execution */
V8JS_METHOD(exit) /* {{{ */
{
v8::V8::TerminateExecution();
return v8::Undefined();
}
/* }}} */
/* global.sleep - sleep for passed seconds */
V8JS_METHOD(sleep) /* {{{ */
{
php_sleep(args[0]->Int32Value());
return v8::Undefined();
}
/* }}} */
/* global.print - php print() */
V8JS_METHOD(print) /* {{{ */
{
int ret = 0;
TSRMLS_FETCH();
for (int i = 0; i < args.Length(); i++) {
v8::String::Utf8Value str(args[i]);
const char *cstr = ToCString(str);
ret = PHPWRITE(cstr, strlen(cstr));
}
return V8JS_INT(ret);
}
/* }}} */
static void _php_v8js_dumper(v8::Local<v8::Value> var, int level TSRMLS_DC) /* {{{ */
{
v8::String::Utf8Value str(var->ToDetailString());
const char *valstr = ToCString(str);
size_t valstr_len = (valstr) ? strlen(valstr) : 0;
if (level > 1) {
php_printf("%*c", (level - 1) * 2, ' ');
}
if (var->IsString())
{
php_printf("string(%d) \"%s\"\n", valstr_len, valstr);
}
else if (var->IsBoolean())
{
php_printf("bool(%s)\n", valstr);
}
else if (var->IsInt32() || var->IsUint32())
{
php_printf("int(%s)\n", valstr);
}
else if (var->IsNumber())
{
php_printf("float(%s)\n", valstr);
}
else if (var->IsDate())
{
php_printf("Date(%s)\n", valstr);
}
#if PHP_V8_API_VERSION >= 2003007
else if (var->IsRegExp())
{
php_printf("RegExp(%s)\n", valstr);
}
#endif
else if (var->IsArray())
{
v8::Local<v8::Array> array = v8::Local<v8::Array>::Cast(var);
uint32_t length = array->Length();
php_printf("array(%d) {\n", length);
for (unsigned i = 0; i < length; i++) {
php_printf("%*c[%d] =>\n", level * 2, ' ', i);
_php_v8js_dumper(array->Get(i), level + 1 TSRMLS_CC);
}
if (level > 1) {
php_printf("%*c", (level - 1) * 2, ' ');
}
ZEND_PUTS("}\n");
}
else if (var->IsObject())
{
v8::Local<v8::Object> object = v8::Local<v8::Object>::Cast(var);
V8JS_GET_CLASS_NAME(cname, object);
if (var->IsFunction())
{
v8::String::Utf8Value csource(object->ToString());
php_printf("object(%s)#%d {\n%*c%s\n", ToCString(cname), object->GetIdentityHash(), level * 2 + 2, ' ', ToCString(csource));
}
else
{
v8::Local<v8::Array> keys = object->GetPropertyNames();
uint32_t length = keys->Length();
php_printf("object(%s)#%d (%d) {\n", ToCString(cname), object->GetIdentityHash(), length);
for (unsigned i = 0; i < length; i++) {
v8::Local<v8::String> key = keys->Get(i)->ToString();
v8::String::Utf8Value kname(key);
php_printf("%*c[\"%s\"] =>\n", level * 2, ' ', ToCString(kname));
_php_v8js_dumper(object->Get(key), level + 1 TSRMLS_CC);
}
}
if (level > 1) {
php_printf("%*c", (level - 1) * 2, ' ');
}
ZEND_PUTS("}\n");
}
else /* null, undefined, etc. */
{
php_printf("<%s>\n", valstr);
}
}
/* }}} */
/* global.var_dump - Dump JS values */
V8JS_METHOD(var_dump) /* {{{ */
{
int i;
TSRMLS_FETCH();
for (int i = 0; i < args.Length(); i++) {
_php_v8js_dumper(args[i], 1 TSRMLS_CC);
}
return V8JS_NULL;
}
/* }}} */
// TODO: Put this in php_v8js_context
std::map<char *, v8::Handle<v8::Object> > modules_loaded;
std::vector<char *> modules_stack;
void split_terms(char *identifier, std::vector<char *> &terms)
{
char *term = (char *)malloc(PATH_MAX), *ptr = term;
// Initialise the term string
*term = 0;
while (*identifier > 0) {
if (*identifier == '/') {
if (strlen(term) > 0) {
// Terminate term string and add to terms vector
*ptr++ = 0;
terms.push_back(strdup(term));
// Reset term string
memset(term, 0, strlen(term));
ptr = term;
}
} else {
*ptr++ = *identifier;
}
identifier++;
}
if (strlen(term) > 0) {
// Terminate term string and add to terms vector
*ptr++ = 0;
terms.push_back(strdup(term));
}
if (term > 0) {
free(term);
}
}
void normalize_identifier(char *identifier, char *normalised)
{
std::vector<char *> terms;
split_terms(identifier, terms);
std::vector<char *> normalised_terms;
for (std::vector<char *>::iterator it = terms.begin(); it != terms.end(); it++) {
char *term = *it;
if (!strcmp(term, "..")) {
normalised_terms.pop_back();
} else if (strcmp(term, ".")) {
normalised_terms.push_back(term);
}
}
// Initialise the normalised string
*normalised = 0;
for (std::vector<char *>::iterator it = normalised_terms.begin(); it != normalised_terms.end(); it++) {
char *term = *it;
if (strlen(normalised) > 0) {
strcat(normalised, "/");
}
strcat(normalised, term);
}
}
V8JS_METHOD(require)
{
v8::String::Utf8Value module_name_v8(args[0]);
// Make sure to duplicate the module name string so it doesn't get freed by the V8 garbage collector
char *module_name = strdup(ToCString(module_name_v8));
char *normalised_module_identifier = (char *)malloc(strlen(module_name));
normalize_identifier(module_name, normalised_module_identifier);
// Check for module cyclic dependencies
for (std::vector<char *>::iterator it = modules_stack.begin(); it != modules_stack.end(); ++it)
{
if (!strcmp(*it, normalised_module_identifier)) {
return v8::ThrowException(v8::String::New("Module cyclic dependency"));
}
}
// If we have already loaded and cached this module then use it
if (modules_loaded.count(normalised_module_identifier) > 0) {
return modules_loaded[normalised_module_identifier];
}
// Get the extension context
v8::Handle<v8::External> data = v8::Handle<v8::External>::Cast(args.Data());
php_v8js_ctx *c = static_cast<php_v8js_ctx*>(data->Value());
// Check that we have a module loader
if (c->module_loader == NULL) {
return v8::ThrowException(v8::String::New("No module loader"));
}
// Callback to PHP to load the module code
zval module_code;
zval *module_name_zend;
MAKE_STD_ZVAL(module_name_zend);
ZVAL_STRING(module_name_zend, normalised_module_identifier, 1);
zval* params[] = { module_name_zend };
if (FAILURE == call_user_function(EG(function_table), NULL, c->module_loader, &module_code, 1, params TSRMLS_CC)) {
return v8::ThrowException(v8::String::New("Module loader callback failed"));
}
// Check if an exception was thrown
if (EG(exception)) {
// Clear the PHP exception and throw it in V8 instead
zend_clear_exception(TSRMLS_CC);
return v8::ThrowException(v8::String::New("Module loader callback exception 456"));
}
// Convert the return value to string
if (Z_TYPE(module_code) != IS_STRING) {
convert_to_string(&module_code);
}
// Check that some code has been returned
if (!strlen(Z_STRVAL(module_code))) {
return v8::ThrowException(v8::String::New("Module loader callback did not return code"));
}
// Create a template for the global object and set the built-in global functions
v8::Handle<v8::ObjectTemplate> global = v8::ObjectTemplate::New();
global->Set(v8::String::New("print"), v8::FunctionTemplate::New(V8JS_MN(print)), v8::ReadOnly);
global->Set(v8::String::New("require"), v8::FunctionTemplate::New(V8JS_MN(require), v8::External::New(c)), v8::ReadOnly);
// Add the exports object in which the module returns its API
v8::Handle<v8::ObjectTemplate> exports_template = v8::ObjectTemplate::New();
v8::Handle<v8::Object> exports = exports_template->NewInstance();
global->Set(v8::String::New("exports"), exports);
// Each module gets its own context so different modules do not affect each other
v8::Persistent<v8::Context> context = v8::Context::New(NULL, global);
// Catch JS exceptions
v8::TryCatch try_catch;
// Enter the module context
v8::Context::Scope scope(context);
v8::HandleScope handle_scope;
// Set script identifier
v8::Local<v8::String> sname = V8JS_SYM("require");
v8::Local<v8::String> source = v8::String::New(Z_STRVAL(module_code));
// Create and compile script
v8::Local<v8::Script> script = v8::Script::New(source, sname);
// The script will be empty if there are compile errors
if (script.IsEmpty()) {
return v8::ThrowException(v8::String::New("Module script compile failed"));
}
// Add this module to the stack
modules_stack.push_back(normalised_module_identifier);
// Run script
v8::Local<v8::Value> result = script->Run();
// Remove this module from the stack
modules_stack.pop_back();
// Script possibly terminated, return immediately
if (!try_catch.CanContinue()) {
return v8::ThrowException(v8::String::New("Module script compile failed"));
}
// Handle runtime JS exceptions
if (try_catch.HasCaught()) {
// Rethrow the exception back to JS
return try_catch.ReThrow();
}
// Cache the module so it doesn't need to be compiled and run again
modules_loaded[normalised_module_identifier] = handle_scope.Close(exports);
return modules_loaded[normalised_module_identifier];
}
void php_v8js_register_methods(v8::Handle<v8::ObjectTemplate> global, php_v8js_ctx *c) /* {{{ */
{
global->Set(V8JS_SYM("exit"), v8::FunctionTemplate::New(V8JS_MN(exit)), v8::ReadOnly);
global->Set(V8JS_SYM("sleep"), v8::FunctionTemplate::New(V8JS_MN(sleep)), v8::ReadOnly);
global->Set(V8JS_SYM("print"), v8::FunctionTemplate::New(V8JS_MN(print)), v8::ReadOnly);
global->Set(V8JS_SYM("var_dump"), v8::FunctionTemplate::New(V8JS_MN(var_dump)), v8::ReadOnly);
global->Set(V8JS_SYM("require"), v8::FunctionTemplate::New(V8JS_MN(require), v8::External::New(c)), v8::ReadOnly);
}
/* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
<|endoftext|>
|
<commit_before>/*
* Copyright 2019-2022 Diligent Graphics LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* In no event and under no legal theory, whether in tort (including negligence),
* contract, or otherwise, unless required by applicable law (such as deliberate
* and grossly negligent acts) or agreed to in writing, shall any Contributor be
* liable for any damages, including any direct, indirect, special, incidental,
* or consequential damages of any character arising as a result of this License or
* out of the use or inability to use the software (including but not limited to damages
* for loss of goodwill, work stoppage, computer failure or malfunction, or any and
* all other commercial damages or losses), even if such Contributor has been advised
* of the possibility of such damages.
*/
#include <bitset>
#include "SerializedPipelineStateImpl.hpp"
#include "Constants.h"
#include "SerializationDeviceImpl.hpp"
#include "SerializedResourceSignatureImpl.hpp"
#include "PSOSerializer.hpp"
#include "Align.hpp"
namespace Diligent
{
DeviceObjectArchiveBase::DeviceType ArchiveDeviceDataFlagToArchiveDeviceType(ARCHIVE_DEVICE_DATA_FLAGS DataTypeFlag);
namespace
{
#define LOG_PSO_ERROR_AND_THROW(...) LOG_ERROR_AND_THROW("Description of PSO is invalid: ", ##__VA_ARGS__)
#define VERIFY_PSO(Expr, ...) \
do \
{ \
if (!(Expr)) \
{ \
LOG_PSO_ERROR_AND_THROW(__VA_ARGS__); \
} \
} while (false)
void ValidatePipelineStateArchiveInfo(const PipelineStateCreateInfo& PSOCreateInfo,
const PipelineStateArchiveInfo& ArchiveInfo,
const ARCHIVE_DEVICE_DATA_FLAGS ValidDeviceFlags) noexcept(false)
{
VERIFY_PSO(ArchiveInfo.DeviceFlags != ARCHIVE_DEVICE_DATA_FLAG_NONE, "At least one bit must be set in DeviceFlags");
VERIFY_PSO((ArchiveInfo.DeviceFlags & ValidDeviceFlags) == ArchiveInfo.DeviceFlags, "DeviceFlags contain unsupported device type");
VERIFY_PSO(PSOCreateInfo.PSODesc.Name != nullptr, "Pipeline name in PSOCreateInfo.PSODesc.Name must not be null");
VERIFY_PSO((PSOCreateInfo.ResourceSignaturesCount != 0) == (PSOCreateInfo.ppResourceSignatures != nullptr),
"ppResourceSignatures must not be null if ResourceSignaturesCount is not zero");
std::bitset<MAX_RESOURCE_SIGNATURES> PRSExists{0};
for (Uint32 i = 0; i < PSOCreateInfo.ResourceSignaturesCount; ++i)
{
VERIFY_PSO(PSOCreateInfo.ppResourceSignatures[i] != nullptr, "ppResourceSignatures[", i, "] must not be null");
const auto& Desc = PSOCreateInfo.ppResourceSignatures[i]->GetDesc();
VERIFY_EXPR(Desc.BindingIndex < PRSExists.size());
VERIFY_PSO(!PRSExists[Desc.BindingIndex], "PRS binding index must be unique");
PRSExists[Desc.BindingIndex] = true;
}
}
#undef LOG_PSO_ERROR_AND_THROW
template <SerializerMode Mode>
void SerializePSOCreateInfo(Serializer<Mode>& Ser,
const GraphicsPipelineStateCreateInfo& PSOCreateInfo,
std::array<const char*, MAX_RESOURCE_SIGNATURES>& PRSNames)
{
const char* RPName = PSOCreateInfo.GraphicsPipeline.pRenderPass != nullptr ? PSOCreateInfo.GraphicsPipeline.pRenderPass->GetDesc().Name : "";
PSOSerializer<Mode>::SerializeCreateInfo(Ser, PSOCreateInfo, PRSNames, nullptr, RPName);
}
template <SerializerMode Mode>
void SerializePSOCreateInfo(Serializer<Mode>& Ser,
const ComputePipelineStateCreateInfo& PSOCreateInfo,
std::array<const char*, MAX_RESOURCE_SIGNATURES>& PRSNames)
{
PSOSerializer<Mode>::SerializeCreateInfo(Ser, PSOCreateInfo, PRSNames, nullptr);
}
template <SerializerMode Mode>
void SerializePSOCreateInfo(Serializer<Mode>& Ser,
const TilePipelineStateCreateInfo& PSOCreateInfo,
std::array<const char*, MAX_RESOURCE_SIGNATURES>& PRSNames)
{
PSOSerializer<Mode>::SerializeCreateInfo(Ser, PSOCreateInfo, PRSNames, nullptr);
}
template <SerializerMode Mode>
void SerializePSOCreateInfo(Serializer<Mode>& Ser,
const RayTracingPipelineStateCreateInfo& PSOCreateInfo,
std::array<const char*, MAX_RESOURCE_SIGNATURES>& PRSNames)
{
using RayTracingShaderMapType = SerializedPipelineStateImpl::RayTracingShaderMapType;
RayTracingShaderMapType ShaderMapVk;
RayTracingShaderMapType ShaderMapD3D12;
#if VULKAN_SUPPORTED
SerializedPipelineStateImpl::ExtractShadersVk(PSOCreateInfo, ShaderMapVk);
VERIFY_EXPR(!ShaderMapVk.empty());
#endif
#if D3D12_SUPPORTED
SerializedPipelineStateImpl::ExtractShadersD3D12(PSOCreateInfo, ShaderMapD3D12);
VERIFY_EXPR(!ShaderMapD3D12.empty());
#endif
VERIFY(ShaderMapVk.empty() || ShaderMapD3D12.empty() || ShaderMapVk == ShaderMapD3D12,
"Ray tracing shader map must be same for Vulkan and Direct3D12 backends");
RayTracingShaderMapType ShaderMap;
if (!ShaderMapVk.empty())
std::swap(ShaderMap, ShaderMapVk);
else if (!ShaderMapD3D12.empty())
std::swap(ShaderMap, ShaderMapD3D12);
else
return;
auto RemapShaders = [&ShaderMap](Uint32& outIndex, IShader* const& inShader) //
{
auto Iter = ShaderMap.find(inShader);
if (Iter != ShaderMap.end())
outIndex = Iter->second;
else
outIndex = ~0u;
};
PSOSerializer<Mode>::SerializeCreateInfo(Ser, PSOCreateInfo, PRSNames, nullptr, RemapShaders);
}
template <typename PSOCreateInfoType>
IRenderPass* RenderPassFromCI(const PSOCreateInfoType& CreateInfo)
{
return nullptr;
}
template <>
IRenderPass* RenderPassFromCI(const GraphicsPipelineStateCreateInfo& CreateInfo)
{
return CreateInfo.GraphicsPipeline.pRenderPass;
}
} // namespace
template <typename PSOCreateInfoType>
SerializedPipelineStateImpl::SerializedPipelineStateImpl(IReferenceCounters* pRefCounters,
SerializationDeviceImpl* pDevice,
const PSOCreateInfoType& CreateInfo,
const PipelineStateArchiveInfo& ArchiveInfo) :
TBase{pRefCounters},
m_pSerializationDevice{pDevice},
m_Name{CreateInfo.PSODesc.Name != nullptr ? CreateInfo.PSODesc.Name : ""},
m_Desc //
{
[this](PipelineStateDesc Desc) //
{
Desc.Name = m_Name.c_str();
// We don't need resource layout and we dont' copy variables and immutable samplers
Desc.ResourceLayout = {};
return Desc;
}(CreateInfo.PSODesc) //
},
m_pRenderPass{RenderPassFromCI(CreateInfo)}
{
if (CreateInfo.PSODesc.Name == nullptr || CreateInfo.PSODesc.Name[0] == '\0')
LOG_ERROR_AND_THROW("Serialized pipeline state name can't be null or empty");
ValidatePipelineStateArchiveInfo(CreateInfo, ArchiveInfo, pDevice->GetValidDeviceFlags());
ValidatePSOCreateInfo(pDevice, CreateInfo);
auto DeviceBits = ArchiveInfo.DeviceFlags;
if ((DeviceBits & ARCHIVE_DEVICE_DATA_FLAG_GL) != 0 && (DeviceBits & ARCHIVE_DEVICE_DATA_FLAG_GLES) != 0)
{
// OpenGL and GLES use the same device data. Clear one flag to avoid shader duplication.
DeviceBits &= ~ARCHIVE_DEVICE_DATA_FLAG_GLES;
}
m_Data.Aux.NoShaderReflection = (ArchiveInfo.PSOFlags & PSO_ARCHIVE_FLAG_STRIP_REFLECTION) != 0;
while (DeviceBits != 0)
{
const auto Flag = ExtractLSB(DeviceBits);
static_assert(ARCHIVE_DEVICE_DATA_FLAG_LAST == ARCHIVE_DEVICE_DATA_FLAG_METAL_IOS, "Please update the switch below to handle the new data type");
switch (Flag)
{
#if D3D11_SUPPORTED
case ARCHIVE_DEVICE_DATA_FLAG_D3D11:
PatchShadersD3D11(CreateInfo);
break;
#endif
#if D3D12_SUPPORTED
case ARCHIVE_DEVICE_DATA_FLAG_D3D12:
PatchShadersD3D12(CreateInfo);
break;
#endif
#if GL_SUPPORTED || GLES_SUPPORTED
case ARCHIVE_DEVICE_DATA_FLAG_GL:
case ARCHIVE_DEVICE_DATA_FLAG_GLES:
PatchShadersGL(CreateInfo);
break;
#endif
#if VULKAN_SUPPORTED
case ARCHIVE_DEVICE_DATA_FLAG_VULKAN:
PatchShadersVk(CreateInfo);
break;
#endif
#if METAL_SUPPORTED
case ARCHIVE_DEVICE_DATA_FLAG_METAL_MACOS:
case ARCHIVE_DEVICE_DATA_FLAG_METAL_IOS:
PatchShadersMtl(CreateInfo, ArchiveDeviceDataFlagToArchiveDeviceType(Flag));
break;
#endif
case ARCHIVE_DEVICE_DATA_FLAG_NONE:
UNEXPECTED("ARCHIVE_DEVICE_DATA_FLAG_NONE (0) should never occur");
break;
default:
LOG_ERROR_MESSAGE("Unexpected render device type");
break;
}
}
if (!m_Data.Common)
{
if (CreateInfo.ResourceSignaturesCount == 0)
{
#if GL_SUPPORTED || GLES_SUPPORTED
if (ArchiveInfo.DeviceFlags & (ARCHIVE_DEVICE_DATA_FLAG_GL | ARCHIVE_DEVICE_DATA_FLAG_GLES))
{
// We must add empty device signature for OpenGL after all other devices are processed,
// otherwise this empty description will be used as common signature description.
PrepareDefaultSignatureGL(CreateInfo);
}
#endif
}
auto SignaturesCount = CreateInfo.ResourceSignaturesCount;
auto** ppSignatures = CreateInfo.ppResourceSignatures;
IPipelineResourceSignature* DefaultSignatures[1] = {};
if (m_pDefaultSignature)
{
DefaultSignatures[0] = m_pDefaultSignature;
ppSignatures = DefaultSignatures;
SignaturesCount = 1;
}
TPRSNames PRSNames = {};
m_Signatures.resize(SignaturesCount);
for (Uint32 i = 0; i < SignaturesCount; ++i)
{
auto* pSignature = ppSignatures[i];
VERIFY(pSignature != nullptr, "This error should've been caught by ValidatePipelineResourceSignatures");
m_Signatures[i] = pSignature;
PRSNames[i] = pSignature->GetDesc().Name;
}
auto SerializePsoCI = [&](auto& Ser) //
{
SerializePSOCreateInfo(Ser, CreateInfo, PRSNames);
constexpr auto SerMode = std::remove_reference<decltype(Ser)>::type::GetMode();
PSOSerializer<SerMode>::SerializeAuxData(Ser, m_Data.Aux, nullptr);
};
{
Serializer<SerializerMode::Measure> Ser;
SerializePsoCI(Ser);
m_Data.Common = Ser.AllocateData(GetRawAllocator());
}
{
Serializer<SerializerMode::Write> Ser{m_Data.Common};
SerializePsoCI(Ser);
VERIFY_EXPR(Ser.IsEnded());
}
}
}
INSTANTIATE_SERIALIZED_PSO_CTOR(GraphicsPipelineStateCreateInfo);
INSTANTIATE_SERIALIZED_PSO_CTOR(ComputePipelineStateCreateInfo);
INSTANTIATE_SERIALIZED_PSO_CTOR(TilePipelineStateCreateInfo);
INSTANTIATE_SERIALIZED_PSO_CTOR(RayTracingPipelineStateCreateInfo);
SerializedPipelineStateImpl::~SerializedPipelineStateImpl()
{}
void DILIGENT_CALL_TYPE SerializedPipelineStateImpl::QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface)
{
if (ppInterface == nullptr)
return;
if (IID == IID_SerializedPipelineState || IID == IID_PipelineState)
{
*ppInterface = this;
(*ppInterface)->AddRef();
}
else
{
TBase::QueryInterface(IID, ppInterface);
}
}
void SerializedPipelineStateImpl::SerializeShaderCreateInfo(DeviceType Type,
const ShaderCreateInfo& CI)
{
Data::ShaderInfo ShaderData;
{
Serializer<SerializerMode::Measure> Ser;
ShaderSerializer<SerializerMode::Measure>::SerializeCI(Ser, CI);
ShaderData.Data = Ser.AllocateData(GetRawAllocator());
}
{
Serializer<SerializerMode::Write> Ser{ShaderData.Data};
ShaderSerializer<SerializerMode::Write>::SerializeCI(Ser, CI);
VERIFY_EXPR(Ser.IsEnded());
}
ShaderData.Stage = CI.Desc.ShaderType;
ShaderData.Hash = ComputeHashRaw(ShaderData.Data.Ptr(), ShaderData.Data.Size());
#ifdef DILIGENT_DEBUG
for (const auto& Data : m_Data.Shaders[static_cast<size_t>(Type)])
VERIFY(Data.Hash != ShaderData.Hash, "Shader with the same hash is already in the list.");
#endif
m_Data.Shaders[static_cast<size_t>(Type)].emplace_back(std::move(ShaderData));
}
Uint32 DILIGENT_CALL_TYPE SerializedPipelineStateImpl::GetPatchedShaderCount(ARCHIVE_DEVICE_DATA_FLAGS DeviceType) const
{
DEV_CHECK_ERR(IsPowerOfTwo(DeviceType), "Only single device data flag is expected");
const auto Type = ArchiveDeviceDataFlagToArchiveDeviceType(DeviceType);
const auto& Shaders = m_Data.Shaders[static_cast<size_t>(Type)];
return StaticCast<Uint32>(Shaders.size());
}
ShaderCreateInfo DILIGENT_CALL_TYPE SerializedPipelineStateImpl::GetPatchedShaderCreateInfo(
ARCHIVE_DEVICE_DATA_FLAGS DeviceType,
Uint32 ShaderIndex) const
{
DEV_CHECK_ERR(IsPowerOfTwo(DeviceType), "Only single device data flag is expected");
ShaderCreateInfo ShaderCI;
const auto Type = ArchiveDeviceDataFlagToArchiveDeviceType(DeviceType);
const auto& Shaders = m_Data.Shaders[static_cast<size_t>(Type)];
if (ShaderIndex < Shaders.size())
{
Serializer<SerializerMode::Read> Ser{Shaders[ShaderIndex].Data};
ShaderSerializer<SerializerMode::Read>::SerializeCI(Ser, ShaderCI);
}
else
{
DEV_ERROR("Shader index (", ShaderIndex, ") is out of range. Call GetPatchedShaderCount() to get the shader count.");
}
return ShaderCI;
}
} // namespace Diligent
<commit_msg>Serialized pipeline state: fixed GetPatchedShaderCreateInfo for Metal bytecode<commit_after>/*
* Copyright 2019-2022 Diligent Graphics LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* In no event and under no legal theory, whether in tort (including negligence),
* contract, or otherwise, unless required by applicable law (such as deliberate
* and grossly negligent acts) or agreed to in writing, shall any Contributor be
* liable for any damages, including any direct, indirect, special, incidental,
* or consequential damages of any character arising as a result of this License or
* out of the use or inability to use the software (including but not limited to damages
* for loss of goodwill, work stoppage, computer failure or malfunction, or any and
* all other commercial damages or losses), even if such Contributor has been advised
* of the possibility of such damages.
*/
#include <bitset>
#include "SerializedPipelineStateImpl.hpp"
#include "Constants.h"
#include "SerializationDeviceImpl.hpp"
#include "SerializedResourceSignatureImpl.hpp"
#include "PSOSerializer.hpp"
#include "Align.hpp"
namespace Diligent
{
DeviceObjectArchiveBase::DeviceType ArchiveDeviceDataFlagToArchiveDeviceType(ARCHIVE_DEVICE_DATA_FLAGS DataTypeFlag);
namespace
{
#define LOG_PSO_ERROR_AND_THROW(...) LOG_ERROR_AND_THROW("Description of PSO is invalid: ", ##__VA_ARGS__)
#define VERIFY_PSO(Expr, ...) \
do \
{ \
if (!(Expr)) \
{ \
LOG_PSO_ERROR_AND_THROW(__VA_ARGS__); \
} \
} while (false)
void ValidatePipelineStateArchiveInfo(const PipelineStateCreateInfo& PSOCreateInfo,
const PipelineStateArchiveInfo& ArchiveInfo,
const ARCHIVE_DEVICE_DATA_FLAGS ValidDeviceFlags) noexcept(false)
{
VERIFY_PSO(ArchiveInfo.DeviceFlags != ARCHIVE_DEVICE_DATA_FLAG_NONE, "At least one bit must be set in DeviceFlags");
VERIFY_PSO((ArchiveInfo.DeviceFlags & ValidDeviceFlags) == ArchiveInfo.DeviceFlags, "DeviceFlags contain unsupported device type");
VERIFY_PSO(PSOCreateInfo.PSODesc.Name != nullptr, "Pipeline name in PSOCreateInfo.PSODesc.Name must not be null");
VERIFY_PSO((PSOCreateInfo.ResourceSignaturesCount != 0) == (PSOCreateInfo.ppResourceSignatures != nullptr),
"ppResourceSignatures must not be null if ResourceSignaturesCount is not zero");
std::bitset<MAX_RESOURCE_SIGNATURES> PRSExists{0};
for (Uint32 i = 0; i < PSOCreateInfo.ResourceSignaturesCount; ++i)
{
VERIFY_PSO(PSOCreateInfo.ppResourceSignatures[i] != nullptr, "ppResourceSignatures[", i, "] must not be null");
const auto& Desc = PSOCreateInfo.ppResourceSignatures[i]->GetDesc();
VERIFY_EXPR(Desc.BindingIndex < PRSExists.size());
VERIFY_PSO(!PRSExists[Desc.BindingIndex], "PRS binding index must be unique");
PRSExists[Desc.BindingIndex] = true;
}
}
#undef LOG_PSO_ERROR_AND_THROW
template <SerializerMode Mode>
void SerializePSOCreateInfo(Serializer<Mode>& Ser,
const GraphicsPipelineStateCreateInfo& PSOCreateInfo,
std::array<const char*, MAX_RESOURCE_SIGNATURES>& PRSNames)
{
const char* RPName = PSOCreateInfo.GraphicsPipeline.pRenderPass != nullptr ? PSOCreateInfo.GraphicsPipeline.pRenderPass->GetDesc().Name : "";
PSOSerializer<Mode>::SerializeCreateInfo(Ser, PSOCreateInfo, PRSNames, nullptr, RPName);
}
template <SerializerMode Mode>
void SerializePSOCreateInfo(Serializer<Mode>& Ser,
const ComputePipelineStateCreateInfo& PSOCreateInfo,
std::array<const char*, MAX_RESOURCE_SIGNATURES>& PRSNames)
{
PSOSerializer<Mode>::SerializeCreateInfo(Ser, PSOCreateInfo, PRSNames, nullptr);
}
template <SerializerMode Mode>
void SerializePSOCreateInfo(Serializer<Mode>& Ser,
const TilePipelineStateCreateInfo& PSOCreateInfo,
std::array<const char*, MAX_RESOURCE_SIGNATURES>& PRSNames)
{
PSOSerializer<Mode>::SerializeCreateInfo(Ser, PSOCreateInfo, PRSNames, nullptr);
}
template <SerializerMode Mode>
void SerializePSOCreateInfo(Serializer<Mode>& Ser,
const RayTracingPipelineStateCreateInfo& PSOCreateInfo,
std::array<const char*, MAX_RESOURCE_SIGNATURES>& PRSNames)
{
using RayTracingShaderMapType = SerializedPipelineStateImpl::RayTracingShaderMapType;
RayTracingShaderMapType ShaderMapVk;
RayTracingShaderMapType ShaderMapD3D12;
#if VULKAN_SUPPORTED
SerializedPipelineStateImpl::ExtractShadersVk(PSOCreateInfo, ShaderMapVk);
VERIFY_EXPR(!ShaderMapVk.empty());
#endif
#if D3D12_SUPPORTED
SerializedPipelineStateImpl::ExtractShadersD3D12(PSOCreateInfo, ShaderMapD3D12);
VERIFY_EXPR(!ShaderMapD3D12.empty());
#endif
VERIFY(ShaderMapVk.empty() || ShaderMapD3D12.empty() || ShaderMapVk == ShaderMapD3D12,
"Ray tracing shader map must be same for Vulkan and Direct3D12 backends");
RayTracingShaderMapType ShaderMap;
if (!ShaderMapVk.empty())
std::swap(ShaderMap, ShaderMapVk);
else if (!ShaderMapD3D12.empty())
std::swap(ShaderMap, ShaderMapD3D12);
else
return;
auto RemapShaders = [&ShaderMap](Uint32& outIndex, IShader* const& inShader) //
{
auto Iter = ShaderMap.find(inShader);
if (Iter != ShaderMap.end())
outIndex = Iter->second;
else
outIndex = ~0u;
};
PSOSerializer<Mode>::SerializeCreateInfo(Ser, PSOCreateInfo, PRSNames, nullptr, RemapShaders);
}
template <typename PSOCreateInfoType>
IRenderPass* RenderPassFromCI(const PSOCreateInfoType& CreateInfo)
{
return nullptr;
}
template <>
IRenderPass* RenderPassFromCI(const GraphicsPipelineStateCreateInfo& CreateInfo)
{
return CreateInfo.GraphicsPipeline.pRenderPass;
}
} // namespace
template <typename PSOCreateInfoType>
SerializedPipelineStateImpl::SerializedPipelineStateImpl(IReferenceCounters* pRefCounters,
SerializationDeviceImpl* pDevice,
const PSOCreateInfoType& CreateInfo,
const PipelineStateArchiveInfo& ArchiveInfo) :
TBase{pRefCounters},
m_pSerializationDevice{pDevice},
m_Name{CreateInfo.PSODesc.Name != nullptr ? CreateInfo.PSODesc.Name : ""},
m_Desc //
{
[this](PipelineStateDesc Desc) //
{
Desc.Name = m_Name.c_str();
// We don't need resource layout and we dont' copy variables and immutable samplers
Desc.ResourceLayout = {};
return Desc;
}(CreateInfo.PSODesc) //
},
m_pRenderPass{RenderPassFromCI(CreateInfo)}
{
if (CreateInfo.PSODesc.Name == nullptr || CreateInfo.PSODesc.Name[0] == '\0')
LOG_ERROR_AND_THROW("Serialized pipeline state name can't be null or empty");
ValidatePipelineStateArchiveInfo(CreateInfo, ArchiveInfo, pDevice->GetValidDeviceFlags());
ValidatePSOCreateInfo(pDevice, CreateInfo);
auto DeviceBits = ArchiveInfo.DeviceFlags;
if ((DeviceBits & ARCHIVE_DEVICE_DATA_FLAG_GL) != 0 && (DeviceBits & ARCHIVE_DEVICE_DATA_FLAG_GLES) != 0)
{
// OpenGL and GLES use the same device data. Clear one flag to avoid shader duplication.
DeviceBits &= ~ARCHIVE_DEVICE_DATA_FLAG_GLES;
}
m_Data.Aux.NoShaderReflection = (ArchiveInfo.PSOFlags & PSO_ARCHIVE_FLAG_STRIP_REFLECTION) != 0;
while (DeviceBits != 0)
{
const auto Flag = ExtractLSB(DeviceBits);
static_assert(ARCHIVE_DEVICE_DATA_FLAG_LAST == ARCHIVE_DEVICE_DATA_FLAG_METAL_IOS, "Please update the switch below to handle the new data type");
switch (Flag)
{
#if D3D11_SUPPORTED
case ARCHIVE_DEVICE_DATA_FLAG_D3D11:
PatchShadersD3D11(CreateInfo);
break;
#endif
#if D3D12_SUPPORTED
case ARCHIVE_DEVICE_DATA_FLAG_D3D12:
PatchShadersD3D12(CreateInfo);
break;
#endif
#if GL_SUPPORTED || GLES_SUPPORTED
case ARCHIVE_DEVICE_DATA_FLAG_GL:
case ARCHIVE_DEVICE_DATA_FLAG_GLES:
PatchShadersGL(CreateInfo);
break;
#endif
#if VULKAN_SUPPORTED
case ARCHIVE_DEVICE_DATA_FLAG_VULKAN:
PatchShadersVk(CreateInfo);
break;
#endif
#if METAL_SUPPORTED
case ARCHIVE_DEVICE_DATA_FLAG_METAL_MACOS:
case ARCHIVE_DEVICE_DATA_FLAG_METAL_IOS:
PatchShadersMtl(CreateInfo, ArchiveDeviceDataFlagToArchiveDeviceType(Flag));
break;
#endif
case ARCHIVE_DEVICE_DATA_FLAG_NONE:
UNEXPECTED("ARCHIVE_DEVICE_DATA_FLAG_NONE (0) should never occur");
break;
default:
LOG_ERROR_MESSAGE("Unexpected render device type");
break;
}
}
if (!m_Data.Common)
{
if (CreateInfo.ResourceSignaturesCount == 0)
{
#if GL_SUPPORTED || GLES_SUPPORTED
if (ArchiveInfo.DeviceFlags & (ARCHIVE_DEVICE_DATA_FLAG_GL | ARCHIVE_DEVICE_DATA_FLAG_GLES))
{
// We must add empty device signature for OpenGL after all other devices are processed,
// otherwise this empty description will be used as common signature description.
PrepareDefaultSignatureGL(CreateInfo);
}
#endif
}
auto SignaturesCount = CreateInfo.ResourceSignaturesCount;
auto** ppSignatures = CreateInfo.ppResourceSignatures;
IPipelineResourceSignature* DefaultSignatures[1] = {};
if (m_pDefaultSignature)
{
DefaultSignatures[0] = m_pDefaultSignature;
ppSignatures = DefaultSignatures;
SignaturesCount = 1;
}
TPRSNames PRSNames = {};
m_Signatures.resize(SignaturesCount);
for (Uint32 i = 0; i < SignaturesCount; ++i)
{
auto* pSignature = ppSignatures[i];
VERIFY(pSignature != nullptr, "This error should've been caught by ValidatePipelineResourceSignatures");
m_Signatures[i] = pSignature;
PRSNames[i] = pSignature->GetDesc().Name;
}
auto SerializePsoCI = [&](auto& Ser) //
{
SerializePSOCreateInfo(Ser, CreateInfo, PRSNames);
constexpr auto SerMode = std::remove_reference<decltype(Ser)>::type::GetMode();
PSOSerializer<SerMode>::SerializeAuxData(Ser, m_Data.Aux, nullptr);
};
{
Serializer<SerializerMode::Measure> Ser;
SerializePsoCI(Ser);
m_Data.Common = Ser.AllocateData(GetRawAllocator());
}
{
Serializer<SerializerMode::Write> Ser{m_Data.Common};
SerializePsoCI(Ser);
VERIFY_EXPR(Ser.IsEnded());
}
}
}
INSTANTIATE_SERIALIZED_PSO_CTOR(GraphicsPipelineStateCreateInfo);
INSTANTIATE_SERIALIZED_PSO_CTOR(ComputePipelineStateCreateInfo);
INSTANTIATE_SERIALIZED_PSO_CTOR(TilePipelineStateCreateInfo);
INSTANTIATE_SERIALIZED_PSO_CTOR(RayTracingPipelineStateCreateInfo);
SerializedPipelineStateImpl::~SerializedPipelineStateImpl()
{}
void DILIGENT_CALL_TYPE SerializedPipelineStateImpl::QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface)
{
if (ppInterface == nullptr)
return;
if (IID == IID_SerializedPipelineState || IID == IID_PipelineState)
{
*ppInterface = this;
(*ppInterface)->AddRef();
}
else
{
TBase::QueryInterface(IID, ppInterface);
}
}
void SerializedPipelineStateImpl::SerializeShaderCreateInfo(DeviceType Type,
const ShaderCreateInfo& CI)
{
Data::ShaderInfo ShaderData;
{
Serializer<SerializerMode::Measure> Ser;
ShaderSerializer<SerializerMode::Measure>::SerializeCI(Ser, CI);
ShaderData.Data = Ser.AllocateData(GetRawAllocator());
}
{
Serializer<SerializerMode::Write> Ser{ShaderData.Data};
ShaderSerializer<SerializerMode::Write>::SerializeCI(Ser, CI);
VERIFY_EXPR(Ser.IsEnded());
}
ShaderData.Stage = CI.Desc.ShaderType;
ShaderData.Hash = ComputeHashRaw(ShaderData.Data.Ptr(), ShaderData.Data.Size());
#ifdef DILIGENT_DEBUG
for (const auto& Data : m_Data.Shaders[static_cast<size_t>(Type)])
VERIFY(Data.Hash != ShaderData.Hash, "Shader with the same hash is already in the list.");
#endif
m_Data.Shaders[static_cast<size_t>(Type)].emplace_back(std::move(ShaderData));
}
Uint32 DILIGENT_CALL_TYPE SerializedPipelineStateImpl::GetPatchedShaderCount(ARCHIVE_DEVICE_DATA_FLAGS DeviceType) const
{
DEV_CHECK_ERR(IsPowerOfTwo(DeviceType), "Only single device data flag is expected");
const auto Type = ArchiveDeviceDataFlagToArchiveDeviceType(DeviceType);
const auto& Shaders = m_Data.Shaders[static_cast<size_t>(Type)];
return StaticCast<Uint32>(Shaders.size());
}
ShaderCreateInfo DILIGENT_CALL_TYPE SerializedPipelineStateImpl::GetPatchedShaderCreateInfo(
ARCHIVE_DEVICE_DATA_FLAGS DeviceType,
Uint32 ShaderIndex) const
{
DEV_CHECK_ERR(IsPowerOfTwo(DeviceType), "Only single device data flag is expected");
ShaderCreateInfo ShaderCI;
const auto Type = ArchiveDeviceDataFlagToArchiveDeviceType(DeviceType);
const auto& Shaders = m_Data.Shaders[static_cast<size_t>(Type)];
if (ShaderIndex < Shaders.size())
{
{
Serializer<SerializerMode::Read> Ser{Shaders[ShaderIndex].Data};
ShaderSerializer<SerializerMode::Read>::SerializeCI(Ser, ShaderCI);
}
if (Type == DeviceType::Metal_MacOS || Type == DeviceType::Metal_iOS)
{
// See DeviceObjectArchiveMtlImpl::UnpackShader
Serializer<SerializerMode::Read> Ser{SerializedData{const_cast<void*>(ShaderCI.ByteCode), ShaderCI.ByteCodeSize}};
Ser.SerializeBytes(ShaderCI.ByteCode, ShaderCI.ByteCodeSize);
}
}
else
{
DEV_ERROR("Shader index (", ShaderIndex, ") is out of range. Call GetPatchedShaderCount() to get the shader count.");
}
return ShaderCI;
}
} // namespace Diligent
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: TestHyperOctreeContourFilter.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm 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 notice for more information.
=========================================================================*/
// This example demonstrates how to use a vtkHyperOctreeSampleFunction and
// apply a vtkHyperOctreeCutter filter on it.
//
// The command line arguments are:
// -I => run in interactive mode; unless this is used, the program will
// not allow interaction and exit
// -D <path> => path to the data; the data should be in <path>/Data/
// If WRITE_RESULT is defined, the result of the surface filter is saved.
//#define WRITE_RESULT
#include "vtkActor.h"
#include "vtkCellData.h"
#include "vtkTestUtilities.h"
#include "vtkRegressionTestImage.h"
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include <assert.h>
#include "vtkLookupTable.h"
#include "vtkPolyData.h"
#include "vtkXMLPolyDataWriter.h"
#include "vtkHyperOctreeContourFilter.h"
#include "vtkPolyDataMapper.h"
#include "vtkTimerLog.h"
#include "vtkHyperOctreeSampleFunction.h"
#include "vtkSphere.h"
#include "vtkCamera.h"
int TestHyperOctreeContourFilter(int argc, char* argv[])
{
// Standard rendering classes
vtkRenderer *renderer = vtkRenderer::New();
vtkRenderWindow *renWin = vtkRenderWindow::New();
renWin->AddRenderer(renderer);
vtkRenderWindowInteractor *iren = vtkRenderWindowInteractor::New();
iren->SetRenderWindow(renWin);
vtkTimerLog *timer=vtkTimerLog::New();
// 3D
vtkHyperOctreeSampleFunction *source3d=vtkHyperOctreeSampleFunction::New();
vtkSphere *f3d=vtkSphere::New();
f3d->SetRadius(1);
f3d->SetCenter(1,1,0);
source3d->SetImplicitFunction(f3d);
source3d->SetThreshold(0.2);
f3d->Delete();
source3d->SetDimension(3);
source3d->SetWidth(2);
source3d->SetHeight(3);
source3d->SetDepth(4);
source3d->SetLevels(6); // 10
source3d->SetMinLevels(0);
cout<<"update source3d..."<<endl;
timer->StartTimer();
source3d->Update(); // Update now, make things easier with a debugger
timer->StopTimer();
cout<<"source updated3d"<<endl;
cout<<"source3d time="<<timer->GetElapsedTime()<<" s"<<endl;
vtkHyperOctreeContourFilter *contour3d=vtkHyperOctreeContourFilter::New();
contour3d->SetNumberOfContours(3);
contour3d->SetValue(0,0.5);
contour3d->SetValue(1,4.0);
contour3d->SetValue(2,8.0);
contour3d->SetInputConnection(0,source3d->GetOutputPort(0));
source3d->Delete();
cout<<"update contour3d..."<<endl;
timer->StartTimer();
contour3d->Update(); // Update now, make things easier with a debugger
timer->StopTimer();
cout<<"contour3d updated"<<endl;
cout<<"contour3d time="<<timer->GetElapsedTime()<<" s"<<endl;
// This creates a blue to red lut.
vtkLookupTable *lut3d = vtkLookupTable::New();
lut3d->SetHueRange (0.667, 0.0);
vtkPolyDataMapper *mapper3d = vtkPolyDataMapper::New();
mapper3d->SetInputConnection(0, contour3d->GetOutputPort(0) );
contour3d->Delete();
mapper3d->SetLookupTable(lut3d);
if(contour3d->GetOutput()->GetCellData()!=0)
{
if(contour3d->GetOutput()->GetCellData()->GetScalars()!=0)
{
mapper3d->SetScalarRange( contour3d->GetOutput()->GetCellData()->
GetScalars()->GetRange());
}
}
vtkActor *actor3d = vtkActor::New();
actor3d->SetMapper(mapper3d);
renderer->AddActor(actor3d);
#ifdef WRITE_RESULT
// Save the result of the filter in a file
vtkXMLPolyDataWriter *writer3d=vtkXMLPolyDataWriter::New();
writer3d->SetInputConnection(0,contour3d->GetOutputPort(0));
writer3d->SetFileName("contour3d.vtp");
writer3d->SetDataModeToAscii();
writer3d->Write();
writer3d->Delete();
#endif // #ifdef WRITE_RESULT
// 2D
vtkHyperOctreeSampleFunction *source2d=vtkHyperOctreeSampleFunction::New();
vtkSphere *f2d=vtkSphere::New();
f2d->SetRadius(1);
f2d->SetCenter(1,1,0);
source2d->SetImplicitFunction(f2d);
source2d->SetThreshold(0.2);
f2d->Delete();
source2d->SetDimension(2);
source2d->SetWidth(2);
source2d->SetHeight(3);
source2d->SetDepth(4);
source2d->SetLevels(10); // 7
source2d->SetMinLevels(0);
cout<<"update source2d..."<<endl;
timer->StartTimer();
source2d->Update(); // Update now, make things easier with a debugger
timer->StopTimer();
cout<<"source updated2d"<<endl;
cout<<"source2d time="<<timer->GetElapsedTime()<<" s"<<endl;
vtkHyperOctreeContourFilter *contour2d=vtkHyperOctreeContourFilter::New();
contour2d->SetNumberOfContours(3);
contour2d->SetValue(0,0.5);
contour2d->SetValue(1,4.0);
contour2d->SetValue(2,8.0);
contour2d->SetInputConnection(0,source2d->GetOutputPort(0));
source2d->Delete();
cout<<"update contour2d..."<<endl;
timer->StartTimer();
contour2d->Update(); // Update now, make things easier with a debugger
timer->StopTimer();
cout<<"contour2d updated"<<endl;
cout<<"contour2d time="<<timer->GetElapsedTime()<<" s"<<endl;
// This creates a blue to red lut.
vtkLookupTable *lut2d = vtkLookupTable::New();
lut2d->SetHueRange (0.667, 0.0);
vtkPolyDataMapper *mapper2d = vtkPolyDataMapper::New();
mapper2d->SetInputConnection(0,contour2d->GetOutputPort(0));
mapper2d->SetLookupTable(lut2d);
if(contour2d->GetOutput()->GetCellData()!=0)
{
if(contour2d->GetOutput()->GetCellData()->GetScalars()!=0)
{
mapper2d->SetScalarRange( contour2d->GetOutput()->GetCellData()->
GetScalars()->GetRange());
}
}
vtkActor *actor2d = vtkActor::New();
actor2d->SetPosition(5,0,0);
actor2d->SetMapper(mapper2d);
renderer->AddActor(actor2d);
#ifdef WRITE_RESULT
// Save the result of the filter in a file
vtkXMLPolyDataWriter *writer2d=vtkXMLPolyDataWriter::New();
writer2d->SetInputConnection(0,contour2d->GetOutputPort(0));
writer2d->SetFileName("contour2d.vtp");
writer2d->SetDataModeToAscii();
writer2d->Write();
writer2d->Delete();
#endif // #ifdef WRITE_RESULT
// 1D
vtkHyperOctreeSampleFunction *source1d=vtkHyperOctreeSampleFunction::New();
vtkSphere *f1d=vtkSphere::New();
f1d->SetRadius(1);
f1d->SetCenter(1,1,0);
source1d->SetImplicitFunction(f1d);
source1d->SetThreshold(0.2);
f1d->Delete();
source1d->SetDimension(1);
source1d->SetWidth(2);
source1d->SetHeight(3);
source1d->SetDepth(4);
source1d->SetLevels(10); // 7
source1d->SetMinLevels(0);
cout<<"update source1d..."<<endl;
timer->StartTimer();
source1d->Update(); // Update now, make things easier with a debugger
timer->StopTimer();
cout<<"source updated1d"<<endl;
cout<<"source1d time="<<timer->GetElapsedTime()<<" s"<<endl;
vtkHyperOctreeContourFilter *contour1d=vtkHyperOctreeContourFilter::New();
contour1d->SetNumberOfContours(3);
contour1d->SetValue(0,0.5);
contour1d->SetValue(1,4.0);
contour1d->SetValue(2,8.0);
contour1d->SetInputConnection(0,source1d->GetOutputPort(0));
source1d->Delete();
cout<<"update contour1d..."<<endl;
timer->StartTimer();
contour1d->Update(); // Update now, make things easier with a debugger
timer->StopTimer();
cout<<"contour1d updated"<<endl;
cout<<"contour1d time="<<timer->GetElapsedTime()<<" s"<<endl;
// This creates a blue to red lut.
vtkLookupTable *lut1d = vtkLookupTable::New();
lut1d->SetHueRange (0.667, 0.0);
vtkPolyDataMapper *mapper1d = vtkPolyDataMapper::New();
mapper1d->SetInputConnection(0,contour1d->GetOutputPort(0));
mapper1d->SetLookupTable(lut1d);
if(contour1d->GetOutput()->GetCellData()!=0)
{
if(contour1d->GetOutput()->GetCellData()->GetScalars()!=0)
{
mapper1d->SetScalarRange( contour1d->GetOutput()->GetCellData()->
GetScalars()->GetRange());
}
}
vtkActor *actor1d = vtkActor::New();
actor1d->SetPosition(10,0,0);
actor1d->SetMapper(mapper1d);
renderer->AddActor(actor1d);
#ifdef WRITE_RESULT
// Save the result of the filter in a file
vtkXMLPolyDataWriter *writer1d=vtkXMLPolyDataWriter::New();
writer1d->SetInputConnection(0,contour1d->GetOutputPort(0));
writer1d->SetFileName("contour1d.vtp");
writer1d->SetDataModeToAscii();
writer1d->Write();
writer1d->Delete();
#endif // #ifdef WRITE_RESULT
// Standard testing code.
renderer->SetBackground(0.5,0.5,0.5);
renWin->SetSize(300,300);
vtkCamera *cam=renderer->GetActiveCamera();
renderer->ResetCamera();
cam->Azimuth(180);
renWin->Render();
int retVal = vtkRegressionTestImage( renWin );
if ( retVal == vtkRegressionTester::DO_INTERACTOR)
{
iren->Start();
}
// Cleanup
renderer->Delete();
renWin->Delete();
iren->Delete();
mapper3d->Delete();
actor3d->Delete();
lut3d->Delete();
mapper2d->Delete();
actor2d->Delete();
lut2d->Delete();
contour2d->Delete();
mapper1d->Delete();
actor1d->Delete();
lut1d->Delete();
contour1d->Delete();
timer->Delete();
return !retVal;
}
<commit_msg>BUG: 1d is colored by cell data.<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: TestHyperOctreeContourFilter.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm 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 notice for more information.
=========================================================================*/
// This example demonstrates how to use a vtkHyperOctreeSampleFunction and
// apply a vtkHyperOctreeCutter filter on it.
//
// The command line arguments are:
// -I => run in interactive mode; unless this is used, the program will
// not allow interaction and exit
// -D <path> => path to the data; the data should be in <path>/Data/
// If WRITE_RESULT is defined, the result of the surface filter is saved.
//#define WRITE_RESULT
#include "vtkActor.h"
#include "vtkCellData.h"
#include "vtkTestUtilities.h"
#include "vtkRegressionTestImage.h"
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include <assert.h>
#include "vtkLookupTable.h"
#include "vtkPolyData.h"
#include "vtkXMLPolyDataWriter.h"
#include "vtkHyperOctreeContourFilter.h"
#include "vtkPolyDataMapper.h"
#include "vtkTimerLog.h"
#include "vtkHyperOctreeSampleFunction.h"
#include "vtkSphere.h"
#include "vtkCamera.h"
int TestHyperOctreeContourFilter(int argc, char* argv[])
{
// Standard rendering classes
vtkRenderer *renderer = vtkRenderer::New();
vtkRenderWindow *renWin = vtkRenderWindow::New();
renWin->AddRenderer(renderer);
vtkRenderWindowInteractor *iren = vtkRenderWindowInteractor::New();
iren->SetRenderWindow(renWin);
vtkTimerLog *timer=vtkTimerLog::New();
// 3D
vtkHyperOctreeSampleFunction *source3d=vtkHyperOctreeSampleFunction::New();
vtkSphere *f3d=vtkSphere::New();
f3d->SetRadius(1);
f3d->SetCenter(1,1,0);
source3d->SetImplicitFunction(f3d);
source3d->SetThreshold(0.2);
f3d->Delete();
source3d->SetDimension(3);
source3d->SetWidth(2);
source3d->SetHeight(3);
source3d->SetDepth(4);
source3d->SetLevels(6); // 10
source3d->SetMinLevels(0);
cout<<"update source3d..."<<endl;
timer->StartTimer();
source3d->Update(); // Update now, make things easier with a debugger
timer->StopTimer();
cout<<"source updated3d"<<endl;
cout<<"source3d time="<<timer->GetElapsedTime()<<" s"<<endl;
vtkHyperOctreeContourFilter *contour3d=vtkHyperOctreeContourFilter::New();
contour3d->SetNumberOfContours(3);
contour3d->SetValue(0,0.5);
contour3d->SetValue(1,4.0);
contour3d->SetValue(2,8.0);
contour3d->SetInputConnection(0,source3d->GetOutputPort(0));
source3d->Delete();
cout<<"update contour3d..."<<endl;
timer->StartTimer();
contour3d->Update(); // Update now, make things easier with a debugger
timer->StopTimer();
cout<<"contour3d updated"<<endl;
cout<<"contour3d time="<<timer->GetElapsedTime()<<" s"<<endl;
// This creates a blue to red lut.
vtkLookupTable *lut3d = vtkLookupTable::New();
lut3d->SetHueRange (0.667, 0.0);
vtkPolyDataMapper *mapper3d = vtkPolyDataMapper::New();
mapper3d->SetInputConnection(0, contour3d->GetOutputPort(0) );
contour3d->Delete();
mapper3d->SetLookupTable(lut3d);
if(contour3d->GetOutput()->GetCellData()!=0)
{
if(contour3d->GetOutput()->GetCellData()->GetScalars()!=0)
{
mapper3d->SetScalarRange( contour3d->GetOutput()->GetCellData()->
GetScalars()->GetRange());
}
}
vtkActor *actor3d = vtkActor::New();
actor3d->SetMapper(mapper3d);
renderer->AddActor(actor3d);
#ifdef WRITE_RESULT
// Save the result of the filter in a file
vtkXMLPolyDataWriter *writer3d=vtkXMLPolyDataWriter::New();
writer3d->SetInputConnection(0,contour3d->GetOutputPort(0));
writer3d->SetFileName("contour3d.vtp");
writer3d->SetDataModeToAscii();
writer3d->Write();
writer3d->Delete();
#endif // #ifdef WRITE_RESULT
// 2D
vtkHyperOctreeSampleFunction *source2d=vtkHyperOctreeSampleFunction::New();
vtkSphere *f2d=vtkSphere::New();
f2d->SetRadius(1);
f2d->SetCenter(1,1,0);
source2d->SetImplicitFunction(f2d);
source2d->SetThreshold(0.2);
f2d->Delete();
source2d->SetDimension(2);
source2d->SetWidth(2);
source2d->SetHeight(3);
source2d->SetDepth(4);
source2d->SetLevels(10); // 7
source2d->SetMinLevels(0);
cout<<"update source2d..."<<endl;
timer->StartTimer();
source2d->Update(); // Update now, make things easier with a debugger
timer->StopTimer();
cout<<"source updated2d"<<endl;
cout<<"source2d time="<<timer->GetElapsedTime()<<" s"<<endl;
vtkHyperOctreeContourFilter *contour2d=vtkHyperOctreeContourFilter::New();
contour2d->SetNumberOfContours(3);
contour2d->SetValue(0,0.5);
contour2d->SetValue(1,4.0);
contour2d->SetValue(2,8.0);
contour2d->SetInputConnection(0,source2d->GetOutputPort(0));
source2d->Delete();
cout<<"update contour2d..."<<endl;
timer->StartTimer();
contour2d->Update(); // Update now, make things easier with a debugger
timer->StopTimer();
cout<<"contour2d updated"<<endl;
cout<<"contour2d time="<<timer->GetElapsedTime()<<" s"<<endl;
// This creates a blue to red lut.
vtkLookupTable *lut2d = vtkLookupTable::New();
lut2d->SetHueRange (0.667, 0.0);
vtkPolyDataMapper *mapper2d = vtkPolyDataMapper::New();
mapper2d->SetInputConnection(0,contour2d->GetOutputPort(0));
mapper2d->SetLookupTable(lut2d);
mapper2d->SetScalarModeToUseCellData();
if(contour2d->GetOutput()->GetCellData()!=0)
{
if(contour2d->GetOutput()->GetCellData()->GetScalars()!=0)
{
mapper2d->SetScalarRange( contour2d->GetOutput()->GetCellData()->
GetScalars()->GetRange());
}
}
vtkActor *actor2d = vtkActor::New();
actor2d->SetPosition(5,0,0);
actor2d->SetMapper(mapper2d);
renderer->AddActor(actor2d);
#ifdef WRITE_RESULT
// Save the result of the filter in a file
vtkXMLPolyDataWriter *writer2d=vtkXMLPolyDataWriter::New();
writer2d->SetInputConnection(0,contour2d->GetOutputPort(0));
writer2d->SetFileName("contour2d.vtp");
writer2d->SetDataModeToAscii();
writer2d->Write();
writer2d->Delete();
#endif // #ifdef WRITE_RESULT
// 1D
vtkHyperOctreeSampleFunction *source1d=vtkHyperOctreeSampleFunction::New();
vtkSphere *f1d=vtkSphere::New();
f1d->SetRadius(1);
f1d->SetCenter(1,1,0);
source1d->SetImplicitFunction(f1d);
source1d->SetThreshold(0.2);
f1d->Delete();
source1d->SetDimension(1);
source1d->SetWidth(2);
source1d->SetHeight(3);
source1d->SetDepth(4);
source1d->SetLevels(10); // 7
source1d->SetMinLevels(0);
cout<<"update source1d..."<<endl;
timer->StartTimer();
source1d->Update(); // Update now, make things easier with a debugger
timer->StopTimer();
cout<<"source updated1d"<<endl;
cout<<"source1d time="<<timer->GetElapsedTime()<<" s"<<endl;
vtkHyperOctreeContourFilter *contour1d=vtkHyperOctreeContourFilter::New();
contour1d->SetNumberOfContours(3);
contour1d->SetValue(0,0.5);
contour1d->SetValue(1,4.0);
contour1d->SetValue(2,8.0);
contour1d->SetInputConnection(0,source1d->GetOutputPort(0));
source1d->Delete();
cout<<"update contour1d..."<<endl;
timer->StartTimer();
contour1d->Update(); // Update now, make things easier with a debugger
timer->StopTimer();
cout<<"contour1d updated"<<endl;
cout<<"contour1d time="<<timer->GetElapsedTime()<<" s"<<endl;
// This creates a blue to red lut.
vtkLookupTable *lut1d = vtkLookupTable::New();
lut1d->SetHueRange (0.667, 0.0);
vtkPolyDataMapper *mapper1d = vtkPolyDataMapper::New();
mapper1d->SetInputConnection(0,contour1d->GetOutputPort(0));
mapper1d->SetLookupTable(lut1d);
if(contour1d->GetOutput()->GetCellData()!=0)
{
if(contour1d->GetOutput()->GetCellData()->GetScalars()!=0)
{
mapper1d->SetScalarRange( contour1d->GetOutput()->GetCellData()->
GetScalars()->GetRange());
}
}
vtkActor *actor1d = vtkActor::New();
actor1d->SetPosition(10,0,0);
actor1d->SetMapper(mapper1d);
renderer->AddActor(actor1d);
#ifdef WRITE_RESULT
// Save the result of the filter in a file
vtkXMLPolyDataWriter *writer1d=vtkXMLPolyDataWriter::New();
writer1d->SetInputConnection(0,contour1d->GetOutputPort(0));
writer1d->SetFileName("contour1d.vtp");
writer1d->SetDataModeToAscii();
writer1d->Write();
writer1d->Delete();
#endif // #ifdef WRITE_RESULT
// Standard testing code.
renderer->SetBackground(0.5,0.5,0.5);
renWin->SetSize(300,300);
vtkCamera *cam=renderer->GetActiveCamera();
renderer->ResetCamera();
cam->Azimuth(180);
renWin->Render();
int retVal = vtkRegressionTestImage( renWin );
if ( retVal == vtkRegressionTester::DO_INTERACTOR)
{
iren->Start();
}
// Cleanup
renderer->Delete();
renWin->Delete();
iren->Delete();
mapper3d->Delete();
actor3d->Delete();
lut3d->Delete();
mapper2d->Delete();
actor2d->Delete();
lut2d->Delete();
contour2d->Delete();
mapper1d->Delete();
actor1d->Delete();
lut1d->Delete();
contour1d->Delete();
timer->Delete();
return !retVal;
}
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: TestRandomPOrderStatisticsMPI.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm 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 notice for more information.
=========================================================================*/
/*
* Copyright 2011 Sandia Corporation.
* Under the terms of Contract DE-AC04-94AL85000, there is a non-exclusive
* license for use of this work by or on behalf of the
* U.S. Government. Redistribution and use in source and binary forms, with
* or without modification, are permitted provided that this Notice and any
* statement of authorship are reproduced on all copies.
*/
// .SECTION Thanks
// Thanks to Philippe Pebay for implementing this test.
#include <mpi.h>
#include "vtkOrderStatistics.h"
#include "vtkPOrderStatistics.h"
#include "vtkIdTypeArray.h"
#include "vtkIntArray.h"
#include "vtkMath.h"
#include "vtkMPIController.h"
#include "vtkMultiBlockDataSet.h"
#include "vtkStdString.h"
#include "vtkStringArray.h"
#include "vtkTable.h"
#include "vtkTimerLog.h"
#include "vtkVariantArray.h"
#include "vtksys/CommandLineArguments.hxx"
struct RandomOrderStatisticsArgs
{
int nVals;
double stdev;
bool quantize;
int maxHistoSize;
double absTol;
int* retVal;
int ioRank;
};
// This will be called by all processes
void RandomOrderStatistics( vtkMultiProcessController* controller, void* arg )
{
// Get test parameters
RandomOrderStatisticsArgs* args = reinterpret_cast<RandomOrderStatisticsArgs*>( arg );
*(args->retVal) = 0;
// Get MPI communicator
vtkMPICommunicator* com = vtkMPICommunicator::SafeDownCast( controller->GetCommunicator() );
// Get local rank
int myRank = com->GetLocalProcessId();
// Seed random number generator
vtkMath::RandomSeed( static_cast<int>( vtkTimerLog::GetUniversalTime() ) * ( myRank + 1 ) );
// Generate an input table that contains samples of:
// 1. A truncated Gaussian pseudo-random variable (vtkIntArray)
// 2. A uniform pseudo-random variable of characters (vtkStringArray)
vtkStdString columnNames[] = { "Rounded Normal Integer", "Uniform Character" };
int nVariables = 2;
// Prepare column of integers
vtkIntArray* intArray = vtkIntArray::New();
intArray->SetNumberOfComponents( 1 );
intArray->SetName( columnNames[0] );
// Prepare column of strings
vtkStringArray* strArray = vtkStringArray::New();
strArray->SetNumberOfComponents( 1 );
strArray->SetName( columnNames[1] );
// Store first values
int v[2];
v[0] = static_cast<int>( vtkMath::Round( vtkMath::Gaussian() * args->stdev ) );
intArray->InsertNextValue( v[0] );
v[1] = 96 + vtkMath::Ceil( vtkMath::Random() * 26 );
char c = static_cast<char>( v[1] );
vtkStdString s( &c, 1 );
strArray->InsertNextValue( s );
// Initialize local extrema
int min_l[] = { v[0], v[1] };
int max_l[] = { v[0], v[1] };
// Continue up to nVals values have been generated
for ( int r = 1; r < args->nVals; ++ r )
{
// Store new values
v[0] = static_cast<int>( vtkMath::Round( vtkMath::Gaussian() * args->stdev ) );
intArray->InsertNextValue( v[0] );
v[1] = 96 + vtkMath::Ceil( vtkMath::Random() * 26 );
c = static_cast<char>( v[1] );
s = vtkStdString( &c, 1 );
strArray->InsertNextValue( s );
// Update local extrema
for ( int i = 0; i < nVariables; ++ i )
{
if ( v[i] < min_l[i] )
{
min_l[i] = v[i];
}
else if ( v[i] > max_l[i] )
{
max_l[i] = v[i];
}
} // i
} // r
// Create input table
vtkTable* inputData = vtkTable::New();
inputData->AddColumn( intArray );
inputData->AddColumn( strArray );
// Clean up
intArray->Delete();
strArray->Delete();
// Reduce extrema for all variables
int min_g[2];
int max_g[2];
for ( int i = 0; i < nVariables; ++ i )
{
com->AllReduce( &min_l[i],
&min_g[i],
1,
vtkCommunicator::MIN_OP );
com->AllReduce( &max_l[i],
&max_g[i],
1,
vtkCommunicator::MAX_OP );
} // i
if ( com->GetLocalProcessId() == args->ioRank )
{
cout << "\n## Generated pseudo-random samples with following ranges:"
<< "\n "
<< columnNames[0]
<< ": "
<< min_g[0]
<< " to "
<< max_g[0]
<< "\n "
<< columnNames[1]
<< ": "
<< static_cast<char>( min_g[1] )
<< " to "
<< static_cast<char>( max_g[1] )
<< "\n";
}
// ************************** Order Statistics **************************
// Synchronize and start clock
com->Barrier();
vtkTimerLog *timer=vtkTimerLog::New();
timer->StartTimer();
// Instantiate a parallel order statistics engine and set its ports
vtkPOrderStatistics* pos = vtkPOrderStatistics::New();
pos->SetInput( vtkStatisticsAlgorithm::INPUT_DATA, inputData );
vtkMultiBlockDataSet* outputModelDS = vtkMultiBlockDataSet::SafeDownCast( pos->GetOutputDataObject( vtkStatisticsAlgorithm::OUTPUT_MODEL ) );
// Select columns of interest
pos->AddColumn( columnNames[0] );
pos->AddColumn( columnNames[1] );
// Test (in parallel) with Learn, Derive, and Assess options turned on
pos->SetLearnOption( true );
pos->SetDeriveOption( true );
pos->SetAssessOption( false );
pos->SetTestOption( false );
pos->SetQuantize( args->quantize );
pos->SetMaximumHistogramSize( args->maxHistoSize );
pos->Update();
// Synchronize and stop clock
com->Barrier();
timer->StopTimer();
if ( com->GetLocalProcessId() == args->ioRank )
{
cout << "\n## Completed parallel calculation of order statistics (with assessment):\n"
<< " Wall time: "
<< timer->GetElapsedTime()
<< " sec.\n";
}
// Now perform verifications
vtkTable* outputHistogram = vtkTable::SafeDownCast( outputModelDS->GetBlock( 0 ) );
unsigned nbq = outputModelDS->GetNumberOfBlocks() - 1;
vtkTable* outputCard = vtkTable::SafeDownCast( outputModelDS->GetBlock( nbq - 1 ) );
vtkTable* outputQuantiles = vtkTable::SafeDownCast( outputModelDS->GetBlock( nbq ) );
// Verify that all processes have the same grand total and histograms size
if ( com->GetLocalProcessId() == args->ioRank )
{
cout << "\n## Verifying that all processes have the same grand total and histograms size.\n";
}
// Gather all cardinalities
int numProcs = controller->GetNumberOfProcesses();
int card_l = outputCard->GetValueByName( 0, "Cardinality" ).ToInt();
int* card_g = new int[numProcs];
com->AllGather( &card_l,
card_g,
1 );
// Known global cardinality
int testIntValue = args->nVals * numProcs;
// Print out and verify all cardinalities
if ( com->GetLocalProcessId() == args->ioRank )
{
for ( int i = 0; i < numProcs; ++ i )
{
cout << " On process "
<< i
<< ", cardinality = "
<< card_g[i]
<< ", histogram size = "
<< outputHistogram->GetNumberOfRows()
<< "\n";
if ( card_g[i] != testIntValue )
{
vtkGenericWarningMacro("Incorrect cardinality:"
<< card_g[i]
<< " <> "
<< testIntValue
<< ")");
*(args->retVal) = 1;
}
}
}
// Print out and verify global extrema
if ( com->GetLocalProcessId() == args->ioRank )
{
cout << "\n## Verifying that calculated global extrema are correct (within "
<< args->absTol
<< " absolute tolerance).\n";
double min_c = outputQuantiles->GetValueByName( 0,
columnNames[0] ).ToDouble();
double max_c = outputQuantiles->GetValueByName( outputQuantiles->GetNumberOfRows() - 1 ,
columnNames[0] ).ToDouble();
cout << " Calculated minimum = "
<< min_c
<< ", maximum = "
<< max_c
<< "\n";
if ( fabs( min_c - min_g[0] ) > args->absTol )
{
vtkGenericWarningMacro("Incorrect minimum.");
*(args->retVal) = 1;
}
if ( fabs( max_c - max_g[0] ) > args->absTol )
{
vtkGenericWarningMacro("Incorrect maximum.");
*(args->retVal) = 1;
}
}
// Clean up
delete [] card_g;
pos->Delete();
inputData->Delete();
timer->Delete();
}
//----------------------------------------------------------------------------
int main( int argc, char** argv )
{
// **************************** MPI Initialization ***************************
vtkMPIController* controller = vtkMPIController::New();
controller->Initialize( &argc, &argv );
// If an MPI controller was not created, terminate in error.
if ( ! controller->IsA( "vtkMPIController" ) )
{
vtkGenericWarningMacro("Failed to initialize a MPI controller.");
controller->Delete();
return 1;
}
vtkMPICommunicator* com = vtkMPICommunicator::SafeDownCast( controller->GetCommunicator() );
// ************************** Find an I/O node ********************************
int* ioPtr;
int ioRank;
int flag;
MPI_Attr_get( MPI_COMM_WORLD,
MPI_IO,
&ioPtr,
&flag );
if ( ( ! flag ) || ( *ioPtr == MPI_PROC_NULL ) )
{
// Getting MPI attributes did not return any I/O node found.
ioRank = MPI_PROC_NULL;
vtkGenericWarningMacro("No MPI I/O nodes found.");
// As no I/O node was found, we need an unambiguous way to report the problem.
// This is the only case when a testValue of -1 will be returned
controller->Finalize();
controller->Delete();
return -1;
}
else
{
if ( *ioPtr == MPI_ANY_SOURCE )
{
// Anyone can do the I/O trick--just pick node 0.
ioRank = 0;
}
else
{
// Only some nodes can do I/O. Make sure everyone agrees on the choice (min).
com->AllReduce( ioPtr,
&ioRank,
1,
vtkCommunicator::MIN_OP );
}
}
// **************************** Parse command line ***************************
// Set default argument values
int nVals = 100000;
double stdev = 50.;
bool quantize = false;
int maxHistoSize = 500;
double absTol = 1.e-6;
// Initialize command line argument parser
vtksys::CommandLineArguments clArgs;
clArgs.Initialize( argc, argv );
clArgs.StoreUnusedArguments( false );
// Parse per-process cardinality of each pseudo-random sample
clArgs.AddArgument("--n-per-proc",
vtksys::CommandLineArguments::SPACE_ARGUMENT,
&nVals, "Per-process cardinality of each pseudo-random sample");
// Parse standard deviation of each pseudo-random sample
clArgs.AddArgument("--std-dev",
vtksys::CommandLineArguments::SPACE_ARGUMENT,
&stdev, "Standard deviation of each pseudo-random sample");
// Parse maximum histogram size
clArgs.AddArgument("--max-histo-size",
vtksys::CommandLineArguments::SPACE_ARGUMENT,
&maxHistoSize, "Maximum histogram size (when re-quantizing is allowed)");
// Parse whether quantization should be used (to reduce histogram size)
clArgs.AddArgument("--quantize",
vtksys::CommandLineArguments::NO_ARGUMENT,
&quantize, "Allow re-quantizing");
// Parse absolute tolerance to verify extrema
clArgs.AddArgument("--abs-tol",
vtksys::CommandLineArguments::SPACE_ARGUMENT,
&absTol, "Absolute tolerance to verify extrema");
// If incorrect arguments were provided, provide some help and terminate in error.
if ( ! clArgs.Parse() )
{
if ( com->GetLocalProcessId() == ioRank )
{
cerr << "Usage: "
<< clArgs.GetHelp()
<< "\n";
}
controller->Finalize();
controller->Delete();
return 1;
}
// ************************** Initialize test *********************************
if ( com->GetLocalProcessId() == ioRank )
{
cout << "\n# Process "
<< ioRank
<< " will be the I/O node.\n";
}
// Parameters for regression test.
int testValue = 0;
RandomOrderStatisticsArgs args;
args.nVals = nVals;
args.stdev = stdev;
args.quantize = quantize;
args.maxHistoSize = maxHistoSize;
args.retVal = &testValue;
args.ioRank = ioRank;
args.absTol = absTol;
// Check how many processes have been made available
int numProcs = controller->GetNumberOfProcesses();
if ( controller->GetLocalProcessId() == ioRank )
{
cout << "\n# Running test with "
<< numProcs
<< " processes and standard deviation = "
<< args.stdev
<< ".\n";
}
// Execute the function named "process" on both processes
controller->SetSingleMethod( RandomOrderStatistics, &args );
controller->SingleMethodExecute();
// Clean up and exit
if ( com->GetLocalProcessId() == ioRank )
{
cout << "\n# Test completed.\n\n";
}
controller->Finalize();
controller->Delete();
return testValue;
}
<commit_msg>No need for a tolerance when verifying integer value<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: TestRandomPOrderStatisticsMPI.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm 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 notice for more information.
=========================================================================*/
/*
* Copyright 2011 Sandia Corporation.
* Under the terms of Contract DE-AC04-94AL85000, there is a non-exclusive
* license for use of this work by or on behalf of the
* U.S. Government. Redistribution and use in source and binary forms, with
* or without modification, are permitted provided that this Notice and any
* statement of authorship are reproduced on all copies.
*/
// .SECTION Thanks
// Thanks to Philippe Pebay for implementing this test.
#include <mpi.h>
#include "vtkOrderStatistics.h"
#include "vtkPOrderStatistics.h"
#include "vtkIdTypeArray.h"
#include "vtkIntArray.h"
#include "vtkMath.h"
#include "vtkMPIController.h"
#include "vtkMultiBlockDataSet.h"
#include "vtkStdString.h"
#include "vtkStringArray.h"
#include "vtkTable.h"
#include "vtkTimerLog.h"
#include "vtkVariantArray.h"
#include "vtksys/CommandLineArguments.hxx"
struct RandomOrderStatisticsArgs
{
int nVals;
double stdev;
bool quantize;
int maxHistoSize;
int* retVal;
int ioRank;
};
// This will be called by all processes
void RandomOrderStatistics( vtkMultiProcessController* controller, void* arg )
{
// Get test parameters
RandomOrderStatisticsArgs* args = reinterpret_cast<RandomOrderStatisticsArgs*>( arg );
*(args->retVal) = 0;
// Get MPI communicator
vtkMPICommunicator* com = vtkMPICommunicator::SafeDownCast( controller->GetCommunicator() );
// Get local rank
int myRank = com->GetLocalProcessId();
// Seed random number generator
vtkMath::RandomSeed( static_cast<int>( vtkTimerLog::GetUniversalTime() ) * ( myRank + 1 ) );
// Generate an input table that contains samples of:
// 1. A truncated Gaussian pseudo-random variable (vtkIntArray)
// 2. A uniform pseudo-random variable of characters (vtkStringArray)
vtkStdString columnNames[] = { "Rounded Normal Integer", "Uniform Character" };
int nVariables = 2;
// Prepare column of integers
vtkIntArray* intArray = vtkIntArray::New();
intArray->SetNumberOfComponents( 1 );
intArray->SetName( columnNames[0] );
// Prepare column of strings
vtkStringArray* strArray = vtkStringArray::New();
strArray->SetNumberOfComponents( 1 );
strArray->SetName( columnNames[1] );
// Store first values
int v[2];
v[0] = static_cast<int>( vtkMath::Round( vtkMath::Gaussian() * args->stdev ) );
intArray->InsertNextValue( v[0] );
v[1] = 96 + vtkMath::Ceil( vtkMath::Random() * 26 );
char c = static_cast<char>( v[1] );
vtkStdString s( &c, 1 );
strArray->InsertNextValue( s );
// Initialize local extrema
int min_l[] = { v[0], v[1] };
int max_l[] = { v[0], v[1] };
// Continue up to nVals values have been generated
for ( int r = 1; r < args->nVals; ++ r )
{
// Store new values
v[0] = static_cast<int>( vtkMath::Round( vtkMath::Gaussian() * args->stdev ) );
intArray->InsertNextValue( v[0] );
v[1] = 96 + vtkMath::Ceil( vtkMath::Random() * 26 );
c = static_cast<char>( v[1] );
s = vtkStdString( &c, 1 );
strArray->InsertNextValue( s );
// Update local extrema
for ( int i = 0; i < nVariables; ++ i )
{
if ( v[i] < min_l[i] )
{
min_l[i] = v[i];
}
else if ( v[i] > max_l[i] )
{
max_l[i] = v[i];
}
} // i
} // r
// Create input table
vtkTable* inputData = vtkTable::New();
inputData->AddColumn( intArray );
inputData->AddColumn( strArray );
// Clean up
intArray->Delete();
strArray->Delete();
// Reduce extrema for all variables
int min_g[2];
int max_g[2];
for ( int i = 0; i < nVariables; ++ i )
{
com->AllReduce( &min_l[i],
&min_g[i],
1,
vtkCommunicator::MIN_OP );
com->AllReduce( &max_l[i],
&max_g[i],
1,
vtkCommunicator::MAX_OP );
} // i
if ( com->GetLocalProcessId() == args->ioRank )
{
cout << "\n## Generated pseudo-random samples with following ranges:"
<< "\n "
<< columnNames[0]
<< ": "
<< min_g[0]
<< " to "
<< max_g[0]
<< "\n "
<< columnNames[1]
<< ": "
<< static_cast<char>( min_g[1] )
<< " to "
<< static_cast<char>( max_g[1] )
<< "\n";
}
// ************************** Order Statistics **************************
// Synchronize and start clock
com->Barrier();
vtkTimerLog *timer=vtkTimerLog::New();
timer->StartTimer();
// Instantiate a parallel order statistics engine and set its ports
vtkPOrderStatistics* pos = vtkPOrderStatistics::New();
pos->SetInput( vtkStatisticsAlgorithm::INPUT_DATA, inputData );
vtkMultiBlockDataSet* outputModelDS = vtkMultiBlockDataSet::SafeDownCast( pos->GetOutputDataObject( vtkStatisticsAlgorithm::OUTPUT_MODEL ) );
// Select columns of interest
pos->AddColumn( columnNames[0] );
pos->AddColumn( columnNames[1] );
// Test (in parallel) with Learn, Derive, and Assess options turned on
pos->SetLearnOption( true );
pos->SetDeriveOption( true );
pos->SetAssessOption( false );
pos->SetTestOption( false );
pos->SetQuantize( args->quantize );
pos->SetMaximumHistogramSize( args->maxHistoSize );
pos->Update();
// Synchronize and stop clock
com->Barrier();
timer->StopTimer();
if ( com->GetLocalProcessId() == args->ioRank )
{
cout << "\n## Completed parallel calculation of order statistics (with assessment):\n"
<< " Wall time: "
<< timer->GetElapsedTime()
<< " sec.\n";
}
// Now perform verifications
vtkTable* outputHistogram = vtkTable::SafeDownCast( outputModelDS->GetBlock( 0 ) );
unsigned nbq = outputModelDS->GetNumberOfBlocks() - 1;
vtkTable* outputCard = vtkTable::SafeDownCast( outputModelDS->GetBlock( nbq - 1 ) );
vtkTable* outputQuantiles = vtkTable::SafeDownCast( outputModelDS->GetBlock( nbq ) );
// Verify that all processes have the same grand total and histograms size
if ( com->GetLocalProcessId() == args->ioRank )
{
cout << "\n## Verifying that all processes have the same grand total and histograms size.\n";
}
// Gather all cardinalities
int numProcs = controller->GetNumberOfProcesses();
int card_l = outputCard->GetValueByName( 0, "Cardinality" ).ToInt();
int* card_g = new int[numProcs];
com->AllGather( &card_l,
card_g,
1 );
// Known global cardinality
int testIntValue = args->nVals * numProcs;
// Print out and verify all cardinalities
if ( com->GetLocalProcessId() == args->ioRank )
{
for ( int i = 0; i < numProcs; ++ i )
{
cout << " On process "
<< i
<< ", cardinality = "
<< card_g[i]
<< ", histogram size = "
<< outputHistogram->GetNumberOfRows()
<< "\n";
if ( card_g[i] != testIntValue )
{
vtkGenericWarningMacro("Incorrect cardinality:"
<< card_g[i]
<< " <> "
<< testIntValue
<< ")");
*(args->retVal) = 1;
}
}
}
// Print out and verify global extrema
if ( com->GetLocalProcessId() == args->ioRank )
{
cout << "\n## Verifying that calculated global extrema are correct.\n";
int min_c = outputQuantiles->GetValueByName( 0,
columnNames[0] ).ToInt();
int max_c = outputQuantiles->GetValueByName( outputQuantiles->GetNumberOfRows() - 1 ,
columnNames[0] ).ToInt();
cout << " Calculated minimum = "
<< min_c
<< ", maximum = "
<< max_c
<< "\n";
if ( min_c != min_g[0] )
{
vtkGenericWarningMacro("Incorrect minimum.");
*(args->retVal) = 1;
}
if ( max_c != max_g[0] )
{
vtkGenericWarningMacro("Incorrect maximum.");
*(args->retVal) = 1;
}
}
// Clean up
delete [] card_g;
pos->Delete();
inputData->Delete();
timer->Delete();
}
//----------------------------------------------------------------------------
int main( int argc, char** argv )
{
// **************************** MPI Initialization ***************************
vtkMPIController* controller = vtkMPIController::New();
controller->Initialize( &argc, &argv );
// If an MPI controller was not created, terminate in error.
if ( ! controller->IsA( "vtkMPIController" ) )
{
vtkGenericWarningMacro("Failed to initialize a MPI controller.");
controller->Delete();
return 1;
}
vtkMPICommunicator* com = vtkMPICommunicator::SafeDownCast( controller->GetCommunicator() );
// ************************** Find an I/O node ********************************
int* ioPtr;
int ioRank;
int flag;
MPI_Attr_get( MPI_COMM_WORLD,
MPI_IO,
&ioPtr,
&flag );
if ( ( ! flag ) || ( *ioPtr == MPI_PROC_NULL ) )
{
// Getting MPI attributes did not return any I/O node found.
ioRank = MPI_PROC_NULL;
vtkGenericWarningMacro("No MPI I/O nodes found.");
// As no I/O node was found, we need an unambiguous way to report the problem.
// This is the only case when a testValue of -1 will be returned
controller->Finalize();
controller->Delete();
return -1;
}
else
{
if ( *ioPtr == MPI_ANY_SOURCE )
{
// Anyone can do the I/O trick--just pick node 0.
ioRank = 0;
}
else
{
// Only some nodes can do I/O. Make sure everyone agrees on the choice (min).
com->AllReduce( ioPtr,
&ioRank,
1,
vtkCommunicator::MIN_OP );
}
}
// **************************** Parse command line ***************************
// Set default argument values
int nVals = 100000;
double stdev = 50.;
bool quantize = false;
int maxHistoSize = 500;
// Initialize command line argument parser
vtksys::CommandLineArguments clArgs;
clArgs.Initialize( argc, argv );
clArgs.StoreUnusedArguments( false );
// Parse per-process cardinality of each pseudo-random sample
clArgs.AddArgument("--n-per-proc",
vtksys::CommandLineArguments::SPACE_ARGUMENT,
&nVals, "Per-process cardinality of each pseudo-random sample");
// Parse standard deviation of each pseudo-random sample
clArgs.AddArgument("--std-dev",
vtksys::CommandLineArguments::SPACE_ARGUMENT,
&stdev, "Standard deviation of each pseudo-random sample");
// Parse maximum histogram size
clArgs.AddArgument("--max-histo-size",
vtksys::CommandLineArguments::SPACE_ARGUMENT,
&maxHistoSize, "Maximum histogram size (when re-quantizing is allowed)");
// Parse whether quantization should be used (to reduce histogram size)
clArgs.AddArgument("--quantize",
vtksys::CommandLineArguments::NO_ARGUMENT,
&quantize, "Allow re-quantizing");
// If incorrect arguments were provided, provide some help and terminate in error.
if ( ! clArgs.Parse() )
{
if ( com->GetLocalProcessId() == ioRank )
{
cerr << "Usage: "
<< clArgs.GetHelp()
<< "\n";
}
controller->Finalize();
controller->Delete();
return 1;
}
// ************************** Initialize test *********************************
if ( com->GetLocalProcessId() == ioRank )
{
cout << "\n# Process "
<< ioRank
<< " will be the I/O node.\n";
}
// Parameters for regression test.
int testValue = 0;
RandomOrderStatisticsArgs args;
args.nVals = nVals;
args.stdev = stdev;
args.quantize = quantize;
args.maxHistoSize = maxHistoSize;
args.retVal = &testValue;
args.ioRank = ioRank;
// Check how many processes have been made available
int numProcs = controller->GetNumberOfProcesses();
if ( controller->GetLocalProcessId() == ioRank )
{
cout << "\n# Running test with "
<< numProcs
<< " processes and standard deviation = "
<< args.stdev
<< ".\n";
}
// Execute the function named "process" on both processes
controller->SetSingleMethod( RandomOrderStatistics, &args );
controller->SingleMethodExecute();
// Clean up and exit
if ( com->GetLocalProcessId() == ioRank )
{
cout << "\n# Test completed.\n\n";
}
controller->Finalize();
controller->Delete();
return testValue;
}
<|endoftext|>
|
<commit_before>//===-- PPCAsmBackend.cpp - PPC Assembler Backend -------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "MCTargetDesc/PPCMCTargetDesc.h"
#include "MCTargetDesc/PPCFixupKinds.h"
#include "llvm/MC/MCAsmBackend.h"
#include "llvm/MC/MCELFObjectWriter.h"
#include "llvm/MC/MCFixupKindInfo.h"
#include "llvm/MC/MCMachObjectWriter.h"
#include "llvm/MC/MCSectionMachO.h"
#include "llvm/MC/MCObjectWriter.h"
#include "llvm/MC/MCValue.h"
#include "llvm/Object/MachOFormat.h"
#include "llvm/Support/ELF.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/TargetRegistry.h"
using namespace llvm;
static unsigned adjustFixupValue(unsigned Kind, uint64_t Value) {
switch (Kind) {
default:
llvm_unreachable("Unknown fixup kind!");
case FK_Data_1:
case FK_Data_2:
case FK_Data_4:
case FK_Data_8:
case PPC::fixup_ppc_toc:
return Value;
case PPC::fixup_ppc_lo14:
case PPC::fixup_ppc_toc16_ds:
return (Value & 0xffff) << 2;
case PPC::fixup_ppc_brcond14:
return Value & 0xfffc;
case PPC::fixup_ppc_br24:
return Value & 0x3fffffc;
#if 0
case PPC::fixup_ppc_hi16:
return (Value >> 16) & 0xffff;
#endif
case PPC::fixup_ppc_ha16:
return ((Value >> 16) + ((Value & 0x8000) ? 1 : 0)) & 0xffff;
case PPC::fixup_ppc_lo16:
case PPC::fixup_ppc_toc16:
return Value & 0xffff;
}
}
namespace {
class PPCMachObjectWriter : public MCMachObjectTargetWriter {
public:
PPCMachObjectWriter(bool Is64Bit, uint32_t CPUType,
uint32_t CPUSubtype)
: MCMachObjectTargetWriter(Is64Bit, CPUType, CPUSubtype) {}
void RecordRelocation(MachObjectWriter *Writer,
const MCAssembler &Asm, const MCAsmLayout &Layout,
const MCFragment *Fragment, const MCFixup &Fixup,
MCValue Target, uint64_t &FixedValue) {}
};
class PPCAsmBackend : public MCAsmBackend {
const Target &TheTarget;
public:
PPCAsmBackend(const Target &T) : MCAsmBackend(), TheTarget(T) {}
unsigned getNumFixupKinds() const { return PPC::NumTargetFixupKinds; }
const MCFixupKindInfo &getFixupKindInfo(MCFixupKind Kind) const {
const static MCFixupKindInfo Infos[PPC::NumTargetFixupKinds] = {
// name offset bits flags
{ "fixup_ppc_br24", 6, 24, MCFixupKindInfo::FKF_IsPCRel },
{ "fixup_ppc_brcond14", 16, 14, MCFixupKindInfo::FKF_IsPCRel },
{ "fixup_ppc_lo16", 16, 16, 0 },
{ "fixup_ppc_ha16", 16, 16, 0 },
{ "fixup_ppc_lo14", 16, 14, 0 },
{ "fixup_ppc_toc", 0, 64, 0 },
{ "fixup_ppc_toc16", 16, 16, 0 },
{ "fixup_ppc_toc16_ds", 16, 14, 0 }
};
if (Kind < FirstTargetFixupKind)
return MCAsmBackend::getFixupKindInfo(Kind);
assert(unsigned(Kind - FirstTargetFixupKind) < getNumFixupKinds() &&
"Invalid kind!");
return Infos[Kind - FirstTargetFixupKind];
}
bool mayNeedRelaxation(const MCInst &Inst) const {
// FIXME.
return false;
}
bool fixupNeedsRelaxation(const MCFixup &Fixup,
uint64_t Value,
const MCInstFragment *DF,
const MCAsmLayout &Layout) const {
// FIXME.
llvm_unreachable("relaxInstruction() unimplemented");
}
void relaxInstruction(const MCInst &Inst, MCInst &Res) const {
// FIXME.
llvm_unreachable("relaxInstruction() unimplemented");
}
bool writeNopData(uint64_t Count, MCObjectWriter *OW) const {
// FIXME: Zero fill for now. That's not right, but at least will get the
// section size right.
for (uint64_t i = 0; i != Count; ++i)
OW->Write8(0);
return true;
}
unsigned getPointerSize() const {
StringRef Name = TheTarget.getName();
if (Name == "ppc64") return 8;
assert(Name == "ppc32" && "Unknown target name!");
return 4;
}
};
} // end anonymous namespace
// FIXME: This should be in a separate file.
namespace {
class DarwinPPCAsmBackend : public PPCAsmBackend {
public:
DarwinPPCAsmBackend(const Target &T) : PPCAsmBackend(T) { }
void applyFixup(const MCFixup &Fixup, char *Data, unsigned DataSize,
uint64_t Value) const {
llvm_unreachable("UNIMP");
}
MCObjectWriter *createObjectWriter(raw_ostream &OS) const {
bool is64 = getPointerSize() == 8;
return createMachObjectWriter(new PPCMachObjectWriter(
/*Is64Bit=*/is64,
(is64 ? object::mach::CTM_PowerPC64 :
object::mach::CTM_PowerPC),
object::mach::CSPPC_ALL),
OS, /*IsLittleEndian=*/false);
}
virtual bool doesSectionRequireSymbols(const MCSection &Section) const {
return false;
}
};
class ELFPPCAsmBackend : public PPCAsmBackend {
uint8_t OSABI;
public:
ELFPPCAsmBackend(const Target &T, uint8_t OSABI) :
PPCAsmBackend(T), OSABI(OSABI) { }
void applyFixup(const MCFixup &Fixup, char *Data, unsigned DataSize,
uint64_t Value) const {
Value = adjustFixupValue(Fixup.getKind(), Value);
if (!Value) return; // Doesn't change encoding.
unsigned Offset = Fixup.getOffset();
// For each byte of the fragment that the fixup touches, mask in the bits from
// the fixup value. The Value has been "split up" into the appropriate
// bitfields above.
for (unsigned i = 0; i != 4; ++i)
Data[Offset + i] |= uint8_t((Value >> ((4 - i - 1)*8)) & 0xff);
}
MCObjectWriter *createObjectWriter(raw_ostream &OS) const {
bool is64 = getPointerSize() == 8;
return createPPCELFObjectWriter(OS, is64, OSABI);
}
virtual bool doesSectionRequireSymbols(const MCSection &Section) const {
return false;
}
};
} // end anonymous namespace
MCAsmBackend *llvm::createPPCAsmBackend(const Target &T, StringRef TT, StringRef CPU) {
if (Triple(TT).isOSDarwin())
return new DarwinPPCAsmBackend(T);
uint8_t OSABI = MCELFObjectTargetWriter::getOSABI(Triple(TT).getOS());
return new ELFPPCAsmBackend(T, OSABI);
}
<commit_msg>PPC: Share applyFixup between ELF and Darwin.<commit_after>//===-- PPCAsmBackend.cpp - PPC Assembler Backend -------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "MCTargetDesc/PPCMCTargetDesc.h"
#include "MCTargetDesc/PPCFixupKinds.h"
#include "llvm/MC/MCAsmBackend.h"
#include "llvm/MC/MCELFObjectWriter.h"
#include "llvm/MC/MCFixupKindInfo.h"
#include "llvm/MC/MCMachObjectWriter.h"
#include "llvm/MC/MCSectionMachO.h"
#include "llvm/MC/MCObjectWriter.h"
#include "llvm/MC/MCValue.h"
#include "llvm/Object/MachOFormat.h"
#include "llvm/Support/ELF.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/TargetRegistry.h"
using namespace llvm;
static unsigned adjustFixupValue(unsigned Kind, uint64_t Value) {
switch (Kind) {
default:
llvm_unreachable("Unknown fixup kind!");
case FK_Data_1:
case FK_Data_2:
case FK_Data_4:
case FK_Data_8:
case PPC::fixup_ppc_toc:
return Value;
case PPC::fixup_ppc_lo14:
case PPC::fixup_ppc_toc16_ds:
return (Value & 0xffff) << 2;
case PPC::fixup_ppc_brcond14:
return Value & 0xfffc;
case PPC::fixup_ppc_br24:
return Value & 0x3fffffc;
#if 0
case PPC::fixup_ppc_hi16:
return (Value >> 16) & 0xffff;
#endif
case PPC::fixup_ppc_ha16:
return ((Value >> 16) + ((Value & 0x8000) ? 1 : 0)) & 0xffff;
case PPC::fixup_ppc_lo16:
case PPC::fixup_ppc_toc16:
return Value & 0xffff;
}
}
namespace {
class PPCMachObjectWriter : public MCMachObjectTargetWriter {
public:
PPCMachObjectWriter(bool Is64Bit, uint32_t CPUType,
uint32_t CPUSubtype)
: MCMachObjectTargetWriter(Is64Bit, CPUType, CPUSubtype) {}
void RecordRelocation(MachObjectWriter *Writer,
const MCAssembler &Asm, const MCAsmLayout &Layout,
const MCFragment *Fragment, const MCFixup &Fixup,
MCValue Target, uint64_t &FixedValue) {}
};
class PPCAsmBackend : public MCAsmBackend {
const Target &TheTarget;
public:
PPCAsmBackend(const Target &T) : MCAsmBackend(), TheTarget(T) {}
unsigned getNumFixupKinds() const { return PPC::NumTargetFixupKinds; }
const MCFixupKindInfo &getFixupKindInfo(MCFixupKind Kind) const {
const static MCFixupKindInfo Infos[PPC::NumTargetFixupKinds] = {
// name offset bits flags
{ "fixup_ppc_br24", 6, 24, MCFixupKindInfo::FKF_IsPCRel },
{ "fixup_ppc_brcond14", 16, 14, MCFixupKindInfo::FKF_IsPCRel },
{ "fixup_ppc_lo16", 16, 16, 0 },
{ "fixup_ppc_ha16", 16, 16, 0 },
{ "fixup_ppc_lo14", 16, 14, 0 },
{ "fixup_ppc_toc", 0, 64, 0 },
{ "fixup_ppc_toc16", 16, 16, 0 },
{ "fixup_ppc_toc16_ds", 16, 14, 0 }
};
if (Kind < FirstTargetFixupKind)
return MCAsmBackend::getFixupKindInfo(Kind);
assert(unsigned(Kind - FirstTargetFixupKind) < getNumFixupKinds() &&
"Invalid kind!");
return Infos[Kind - FirstTargetFixupKind];
}
void applyFixup(const MCFixup &Fixup, char *Data, unsigned DataSize,
uint64_t Value) const {
Value = adjustFixupValue(Fixup.getKind(), Value);
if (!Value) return; // Doesn't change encoding.
unsigned Offset = Fixup.getOffset();
// For each byte of the fragment that the fixup touches, mask in the bits
// from the fixup value. The Value has been "split up" into the appropriate
// bitfields above.
for (unsigned i = 0; i != 4; ++i)
Data[Offset + i] |= uint8_t((Value >> ((4 - i - 1)*8)) & 0xff);
}
bool mayNeedRelaxation(const MCInst &Inst) const {
// FIXME.
return false;
}
bool fixupNeedsRelaxation(const MCFixup &Fixup,
uint64_t Value,
const MCInstFragment *DF,
const MCAsmLayout &Layout) const {
// FIXME.
llvm_unreachable("relaxInstruction() unimplemented");
}
void relaxInstruction(const MCInst &Inst, MCInst &Res) const {
// FIXME.
llvm_unreachable("relaxInstruction() unimplemented");
}
bool writeNopData(uint64_t Count, MCObjectWriter *OW) const {
// FIXME: Zero fill for now. That's not right, but at least will get the
// section size right.
for (uint64_t i = 0; i != Count; ++i)
OW->Write8(0);
return true;
}
unsigned getPointerSize() const {
StringRef Name = TheTarget.getName();
if (Name == "ppc64") return 8;
assert(Name == "ppc32" && "Unknown target name!");
return 4;
}
};
} // end anonymous namespace
// FIXME: This should be in a separate file.
namespace {
class DarwinPPCAsmBackend : public PPCAsmBackend {
public:
DarwinPPCAsmBackend(const Target &T) : PPCAsmBackend(T) { }
MCObjectWriter *createObjectWriter(raw_ostream &OS) const {
bool is64 = getPointerSize() == 8;
return createMachObjectWriter(new PPCMachObjectWriter(
/*Is64Bit=*/is64,
(is64 ? object::mach::CTM_PowerPC64 :
object::mach::CTM_PowerPC),
object::mach::CSPPC_ALL),
OS, /*IsLittleEndian=*/false);
}
virtual bool doesSectionRequireSymbols(const MCSection &Section) const {
return false;
}
};
class ELFPPCAsmBackend : public PPCAsmBackend {
uint8_t OSABI;
public:
ELFPPCAsmBackend(const Target &T, uint8_t OSABI) :
PPCAsmBackend(T), OSABI(OSABI) { }
MCObjectWriter *createObjectWriter(raw_ostream &OS) const {
bool is64 = getPointerSize() == 8;
return createPPCELFObjectWriter(OS, is64, OSABI);
}
virtual bool doesSectionRequireSymbols(const MCSection &Section) const {
return false;
}
};
} // end anonymous namespace
MCAsmBackend *llvm::createPPCAsmBackend(const Target &T, StringRef TT, StringRef CPU) {
if (Triple(TT).isOSDarwin())
return new DarwinPPCAsmBackend(T);
uint8_t OSABI = MCELFObjectTargetWriter::getOSABI(Triple(TT).getOS());
return new ELFPPCAsmBackend(T, OSABI);
}
<|endoftext|>
|
<commit_before>/* main-test.cc KPilot
**
** Copyright (C) 2001 by Dan Pilone
**
** This is the main program for kpilotTest, which shows a SyncLog and
** exercises the KPilotDeviceLink class. It's intended to test if the
** Palm hardware and the KPilot software are functioning correctly to
** some extent.
*/
/*
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program in a file called COPYING; if not, write to
** the Free Software Foundation, Inc., 675 Mass Ave, Cambridge,
** MA 02139, USA.
*/
/*
** Bug reports and questions can be sent to [email protected].
*/
static const char *test_id =
"$Id$";
#include "options.h"
#include <stdlib.h>
#include <time.h>
#include <iostream.h>
#include <kapp.h>
#include <klocale.h>
#include <kaboutdata.h>
#include <kcmdlineargs.h>
#include <kservice.h>
#include <kservicetype.h>
#include <kuserprofile.h>
#include <klibloader.h>
#include "logWidget.h"
#include "kpilotConfig.h"
#include "hotSync.h"
#include "interactiveSync.h"
static KCmdLineOptions kpilotoptions[] = {
{"port <device>",
I18N_NOOP("Path to Pilot device node"),
"/dev/pilot"},
{"test", I18N_NOOP("List DBs (default)"), 0},
{"backup", I18N_NOOP("Backup instead of list DBs"), 0},
{"restore", I18N_NOOP("Restore Pilot from backup"), 0},
{ "list-conduits", I18N_NOOP("List available conduits"), 0},
{ "exec-conduit <filename>",
I18N_NOOP("Run conduit from desktop file <filename>"),
0 },
{0, 0, 0}
};
int syncTest(KCmdLineArgs *p)
{
FUNCTIONSETUP;
QString devicePath = p->getOption("port");
if (devicePath.isEmpty())
{
devicePath = "/dev/pilot";
}
KPilotDeviceLink::DeviceType deviceType =
KPilotDeviceLink::OldStyleUSB;
LogWidget *w = new LogWidget(0L);
w->resize(300, 300);
w->show();
w->setShowTime(true);
kapp->setMainWidget(w);
KPilotDeviceLink *t = KPilotDeviceLink::init(0, "deviceLink");
SyncAction *head = 0L;
SyncAction *tail = 0L;
if (p->isSet("backup"))
{
head = tail = new BackupAction(t);
}
else if (p->isSet("restore"))
{
head = new CheckUser(t, w);
SyncAction *l = new RestoreAction(t, w);
tail = new CleanupAction(t);
QObject::connect(head, SIGNAL(syncDone(SyncAction *)),
l, SLOT(exec()));
QObject::connect(l, SIGNAL(syncDone(SyncAction *)),
tail, SLOT(exec()));
}
else
{
head = tail = new TestLink(t);
}
QObject::connect(t, SIGNAL(logError(const QString &)),
w, SLOT(addError(const QString &)));
QObject::connect(t, SIGNAL(logMessage(const QString &)),
w, SLOT(addMessage(const QString &)));
QObject::connect(t, SIGNAL(deviceReady()), head, SLOT(exec()));
QObject::connect(tail, SIGNAL(syncDone(SyncAction *)),
w, SLOT(syncDone()));
QObject::connect(tail, SIGNAL(syncDone(SyncAction *)),
t, SLOT(close()));
t->reset(deviceType, devicePath);
return kapp->exec();
/* NOTREACHED */
(void) test_id;
}
int listConduits(KCmdLineArgs *p)
{
FUNCTIONSETUP;
KServiceTypeProfile::OfferList offers =
KServiceTypeProfile::offers("KPilotConduit");
// Now actually fill the two list boxes, just make
// sure that nothing gets listed in both.
//
//
QValueListIterator < KServiceOffer > availList(offers.begin());
while (availList != offers.end())
{
KSharedPtr < KService > o = (*availList).service();
cout << o->desktopEntryName() << endl;
cout << "\t" << o->name() << endl;
if (!o->library().isEmpty())
{
cout << "\tIn "
<< o->library()
<< endl;
}
++availList;
}
return 0;
}
int execConduit(KCmdLineArgs *p)
{
FUNCTIONSETUP;
// get --exec-conduit value
QString s = p->getOption("exec-conduit");
if (s.isEmpty()) return 1;
// query that service
KSharedPtr < KService > o = KService::serviceByDesktopName(s);
if (!o) return 1;
// load the lib
#ifdef DEBUG
DEBUGKPILOT << fname
<< ": Loading desktop "
<< s
<< " with lib "
<< o->library()
<< endl;
#endif
KLibFactory *f = KLibLoader::self()->factory(o->library());
if (!f)
{
kdWarning() << k_funcinfo
<< ": Can't load library "
<< o->library()
<< endl;
return 1;
}
QString devicePath = p->getOption("port");
if (devicePath.isEmpty())
{
devicePath = "/dev/pilot";
}
KPilotDeviceLink::DeviceType deviceType =
KPilotDeviceLink::OldStyleUSB;
LogWidget *w = new LogWidget(0L);
w->resize(300, 300);
w->show();
w->setShowTime(true);
kapp->setMainWidget(w);
KPilotDeviceLink *t = KPilotDeviceLink::init(0, "deviceLink");
SyncAction *head = 0L;
QStringList l;
l.append("test");
QObject *object = f->create(t,0L,"SyncAction",l);
if (!object)
{
kdWarning() << k_funcinfo
<< ": Can't create SyncAction."
<< endl;
return 1;
}
head = dynamic_cast<SyncAction *>(object);
if (!head)
{
kdWarning() << k_funcinfo
<< ": Can't cast to SyncAction."
<< endl;
return 1;
}
QObject::connect(t, SIGNAL(logError(const QString &)),
w, SLOT(addError(const QString &)));
QObject::connect(t, SIGNAL(logMessage(const QString &)),
w, SLOT(addMessage(const QString &)));
QObject::connect(t, SIGNAL(deviceReady()), head, SLOT(exec()));
QObject::connect(head, SIGNAL(syncDone(SyncAction *)),
w, SLOT(syncDone()));
QObject::connect(head, SIGNAL(syncDone(SyncAction *)),
t, SLOT(close()));
t->reset(deviceType, devicePath);
return kapp->exec();
}
int main(int argc, char **argv)
{
FUNCTIONSETUP;
KAboutData about("kpilotTest",
I18N_NOOP("KPilotTest"),
KPILOT_VERSION,
"KPilot Tester",
KAboutData::License_GPL, "(C) 2001, Adriaan de Groot");
about.addAuthor("Adriaan de Groot",
I18N_NOOP("KPilot Maintainer"),
"[email protected]", "http://www.cs.kun.nl/~adridg/kpilot/");
KCmdLineArgs::init(argc, argv, &about);
#ifdef DEBUG
KCmdLineArgs::addCmdLineOptions(debug_options, "debug", "debug");
#endif
KCmdLineArgs::addCmdLineOptions(kpilotoptions, "kpilottest", 0L,
"debug");
KApplication::addCmdLineOptions();
KCmdLineArgs *p = KCmdLineArgs::parsedArgs();
KApplication a;
KPilotConfig::getDebugLevel(p);
if (p->isSet("backup") || p->isSet("restore") || p->isSet("test"))
{
return syncTest(p);
}
if (p->isSet("list-conduits"))
{
return listConduits(p);
}
if (p->isSet("exec-conduit"))
{
return execConduit(p);
}
return 0;
}
// $Log$
// Revision 1.8 2001/09/29 16:26:18 adridg
// The big layout change
//
// Revision 1.7 2001/09/24 22:22:49 adridg
// Modified to handle new interactive SyncActions
//
// Revision 1.6 2001/09/24 10:43:19 cschumac
// Compile fixes.
//
// Revision 1.5 2001/09/23 21:42:35 adridg
// Factored out debugging options
//
// Revision 1.4 2001/09/23 18:28:52 adridg
// Adjusted tests to new .ui and config
//
// Revision 1.3 2001/09/16 13:37:48 adridg
// Large-scale restructuring
//
// Revision 1.2 2001/09/06 22:05:00 adridg
// Enforce singleton-ness
//
// Revision 1.1 2001/09/05 21:53:51 adridg
// Major cleanup and architectural changes. New applications kpilotTest
// and kpilotConfig are not installed by default but can be used to test
// the codebase. Note that nothing else will actually compile right now.
//
<commit_msg>Added --notest, --exec-conduit<commit_after>/* main-test.cc KPilot
**
** Copyright (C) 2001 by Dan Pilone
**
** This is the main program for kpilotTest, which shows a SyncLog and
** exercises the KPilotDeviceLink class. It's intended to test if the
** Palm hardware and the KPilot software are functioning correctly to
** some extent.
*/
/*
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program in a file called COPYING; if not, write to
** the Free Software Foundation, Inc., 675 Mass Ave, Cambridge,
** MA 02139, USA.
*/
/*
** Bug reports and questions can be sent to [email protected].
*/
static const char *test_id =
"$Id$";
#include "options.h"
#include <stdlib.h>
#include <time.h>
#include <iostream.h>
#include <kapp.h>
#include <klocale.h>
#include <kaboutdata.h>
#include <kcmdlineargs.h>
#include <kservice.h>
#include <kservicetype.h>
#include <kuserprofile.h>
#include <klibloader.h>
#include "logWidget.h"
#include "kpilotConfig.h"
#include "hotSync.h"
#include "interactiveSync.h"
static KCmdLineOptions kpilotoptions[] = {
{"port <device>",
I18N_NOOP("Path to Pilot device node"),
"/dev/pilot"},
{"list", I18N_NOOP("List DBs (default)"), 0},
{"backup", I18N_NOOP("Backup instead of list DBs"), 0},
{"restore", I18N_NOOP("Restore Pilot from backup"), 0},
{ "list-conduits", I18N_NOOP("List available conduits"), 0},
{ "exec-conduit <filename>",
I18N_NOOP("Run conduit from desktop file <filename>"),
0 },
{ "notest",
I18N_NOOP("*Really* run the conduit, not in test mode."),
0 } ,
{0, 0, 0}
};
int syncTest(KCmdLineArgs *p)
{
FUNCTIONSETUP;
QString devicePath = p->getOption("port");
if (devicePath.isEmpty())
{
devicePath = "/dev/pilot";
}
KPilotDeviceLink::DeviceType deviceType =
KPilotDeviceLink::OldStyleUSB;
LogWidget *w = new LogWidget(0L);
w->resize(300, 300);
w->show();
w->setShowTime(true);
kapp->setMainWidget(w);
KPilotDeviceLink *t = KPilotDeviceLink::init(0, "deviceLink");
SyncAction *head = 0L;
SyncAction *tail = 0L;
if (p->isSet("backup"))
{
head = tail = new BackupAction(t);
}
else if (p->isSet("restore"))
{
head = new CheckUser(t, w);
SyncAction *l = new RestoreAction(t, w);
tail = new CleanupAction(t);
QObject::connect(head, SIGNAL(syncDone(SyncAction *)),
l, SLOT(exec()));
QObject::connect(l, SIGNAL(syncDone(SyncAction *)),
tail, SLOT(exec()));
}
else
{
head = tail = new TestLink(t);
}
QObject::connect(t, SIGNAL(logError(const QString &)),
w, SLOT(addError(const QString &)));
QObject::connect(t, SIGNAL(logMessage(const QString &)),
w, SLOT(addMessage(const QString &)));
QObject::connect(t, SIGNAL(deviceReady()), head, SLOT(exec()));
QObject::connect(tail, SIGNAL(syncDone(SyncAction *)),
w, SLOT(syncDone()));
QObject::connect(tail, SIGNAL(syncDone(SyncAction *)),
t, SLOT(close()));
t->reset(deviceType, devicePath);
return kapp->exec();
/* NOTREACHED */
(void) test_id;
}
int listConduits(KCmdLineArgs *p)
{
FUNCTIONSETUP;
KServiceTypeProfile::OfferList offers =
KServiceTypeProfile::offers("KPilotConduit");
// Now actually fill the two list boxes, just make
// sure that nothing gets listed in both.
//
//
QValueListIterator < KServiceOffer > availList(offers.begin());
while (availList != offers.end())
{
KSharedPtr < KService > o = (*availList).service();
cout << o->desktopEntryName() << endl;
cout << "\t" << o->name() << endl;
if (!o->library().isEmpty())
{
cout << "\tIn "
<< o->library()
<< endl;
}
++availList;
}
return 0;
}
int execConduit(KCmdLineArgs *p)
{
FUNCTIONSETUP;
// get --exec-conduit value
QString s = p->getOption("exec-conduit");
if (s.isEmpty()) return 1;
// query that service
KSharedPtr < KService > o = KService::serviceByDesktopName(s);
if (!o) return 1;
// load the lib
#ifdef DEBUG
DEBUGKPILOT << fname
<< ": Loading desktop "
<< s
<< " with lib "
<< o->library()
<< endl;
#endif
KLibFactory *f = KLibLoader::self()->factory(o->library());
if (!f)
{
kdWarning() << k_funcinfo
<< ": Can't load library "
<< o->library()
<< endl;
return 1;
}
QString devicePath = p->getOption("port");
if (devicePath.isEmpty())
{
devicePath = "/dev/pilot";
}
KPilotDeviceLink::DeviceType deviceType =
KPilotDeviceLink::OldStyleUSB;
LogWidget *w = new LogWidget(0L);
w->resize(300, 300);
w->show();
w->setShowTime(true);
kapp->setMainWidget(w);
KPilotDeviceLink *t = KPilotDeviceLink::init(0, "deviceLink");
SyncAction *head = 0L;
QStringList l;
if (p->isSet("test"))
{
l.append("test");
}
QObject *object = f->create(t,0L,"SyncAction",l);
if (!object)
{
kdWarning() << k_funcinfo
<< ": Can't create SyncAction."
<< endl;
return 1;
}
head = dynamic_cast<SyncAction *>(object);
if (!head)
{
kdWarning() << k_funcinfo
<< ": Can't cast to SyncAction."
<< endl;
return 1;
}
QObject::connect(t, SIGNAL(logError(const QString &)),
w, SLOT(addError(const QString &)));
QObject::connect(t, SIGNAL(logMessage(const QString &)),
w, SLOT(addMessage(const QString &)));
QObject::connect(t, SIGNAL(deviceReady()), head, SLOT(exec()));
QObject::connect(head, SIGNAL(syncDone(SyncAction *)),
w, SLOT(syncDone()));
QObject::connect(head, SIGNAL(syncDone(SyncAction *)),
t, SLOT(close()));
t->reset(deviceType, devicePath);
return kapp->exec();
}
int main(int argc, char **argv)
{
FUNCTIONSETUP;
KAboutData about("kpilotTest",
I18N_NOOP("KPilotTest"),
KPILOT_VERSION,
"KPilot Tester",
KAboutData::License_GPL, "(C) 2001, Adriaan de Groot");
about.addAuthor("Adriaan de Groot",
I18N_NOOP("KPilot Maintainer"),
"[email protected]", "http://www.cs.kun.nl/~adridg/kpilot/");
KCmdLineArgs::init(argc, argv, &about);
#ifdef DEBUG
KCmdLineArgs::addCmdLineOptions(debug_options, "debug", "debug");
#endif
KCmdLineArgs::addCmdLineOptions(kpilotoptions, "kpilottest", 0L,
"debug");
KApplication::addCmdLineOptions();
KCmdLineArgs *p = KCmdLineArgs::parsedArgs();
KApplication a;
KPilotConfig::getDebugLevel(p);
if (p->isSet("backup") || p->isSet("restore") || p->isSet("list"))
{
return syncTest(p);
}
if (p->isSet("list-conduits"))
{
return listConduits(p);
}
if (p->isSet("exec-conduit"))
{
return execConduit(p);
}
return 0;
}
// $Log$
// Revision 1.9 2001/10/08 22:20:18 adridg
// Changeover to libkpilot, prepare for lib-based conduits
//
// Revision 1.8 2001/09/29 16:26:18 adridg
// The big layout change
//
// Revision 1.7 2001/09/24 22:22:49 adridg
// Modified to handle new interactive SyncActions
//
// Revision 1.6 2001/09/24 10:43:19 cschumac
// Compile fixes.
//
// Revision 1.5 2001/09/23 21:42:35 adridg
// Factored out debugging options
//
// Revision 1.4 2001/09/23 18:28:52 adridg
// Adjusted tests to new .ui and config
//
// Revision 1.3 2001/09/16 13:37:48 adridg
// Large-scale restructuring
//
// Revision 1.2 2001/09/06 22:05:00 adridg
// Enforce singleton-ness
//
// Revision 1.1 2001/09/05 21:53:51 adridg
// Major cleanup and architectural changes. New applications kpilotTest
// and kpilotConfig are not installed by default but can be used to test
// the codebase. Note that nothing else will actually compile right now.
//
<|endoftext|>
|
<commit_before>// Copyright 2009 Google 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 Google 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.
//
// Author: [email protected] (Vlad Losev)
//
// The Google C++ Testing Framework (Google Test)
//
// This file contains tests verifying correctness of data provided via
// UnitTest's public methods.
#include "gtest/gtest.h"
#include <string.h> // For strcmp.
#include <algorithm>
#include <sstream>
using ::testing::InitGoogleTest;
namespace testing {
namespace internal {
template <typename T>
struct LessByName {
bool operator()(const T* a, const T* b) {
return strcmp(a->name(), b->name()) < 0;
}
};
class UnitTestHelper {
public:
// Returns the array of pointers to all test cases sorted by the test case
// name. The caller is responsible for deleting the array.
static TestCase const** const GetSortedTestCases() {
UnitTest& unit_test = *UnitTest::GetInstance();
TestCase const** const test_cases =
new const TestCase*[unit_test.total_test_case_count()];
for (int i = 0; i < unit_test.total_test_case_count(); ++i)
test_cases[i] = unit_test.GetTestCase(i);
std::sort(test_cases,
test_cases + unit_test.total_test_case_count(),
LessByName<TestCase>());
return test_cases;
}
// Returns the test case by its name. The caller doesn't own the returned
// pointer.
static const TestCase* FindTestCase(const char* name) {
UnitTest& unit_test = *UnitTest::GetInstance();
for (int i = 0; i < unit_test.total_test_case_count(); ++i) {
const TestCase* test_case = unit_test.GetTestCase(i);
if (0 == strcmp(test_case->name(), name))
return test_case;
}
return NULL;
}
// Returns the array of pointers to all tests in a particular test case
// sorted by the test name. The caller is responsible for deleting the
// array.
static TestInfo const** const GetSortedTests(const TestCase* test_case) {
TestInfo const** const tests =
new const TestInfo*[test_case->total_test_count()];
for (int i = 0; i < test_case->total_test_count(); ++i)
tests[i] = test_case->GetTestInfo(i);
std::sort(tests, tests + test_case->total_test_count(),
LessByName<TestInfo>());
return tests;
}
};
#if GTEST_HAS_TYPED_TEST
template <typename T> class TestCaseWithCommentTest : public Test {};
TYPED_TEST_CASE(TestCaseWithCommentTest, Types<int>);
TYPED_TEST(TestCaseWithCommentTest, Dummy) {}
const int kTypedTestCases = 1;
const int kTypedTests = 1;
#else
const int kTypedTestCases = 0;
const int kTypedTests = 0;
#endif // GTEST_HAS_TYPED_TEST
// We can only test the accessors that do not change value while tests run.
// Since tests can be run in any order, the values the accessors that track
// test execution (such as failed_test_count) can not be predicted.
TEST(ApiTest, UnitTestImmutableAccessorsWork) {
UnitTest* unit_test = UnitTest::GetInstance();
ASSERT_EQ(2 + kTypedTestCases, unit_test->total_test_case_count());
EXPECT_EQ(1 + kTypedTestCases, unit_test->test_case_to_run_count());
EXPECT_EQ(2, unit_test->disabled_test_count());
EXPECT_EQ(5 + kTypedTests, unit_test->total_test_count());
EXPECT_EQ(3 + kTypedTests, unit_test->test_to_run_count());
const TestCase** const test_cases = UnitTestHelper::GetSortedTestCases();
EXPECT_STREQ("ApiTest", test_cases[0]->name());
EXPECT_STREQ("DISABLED_Test", test_cases[1]->name());
#if GTEST_HAS_TYPED_TEST
EXPECT_STREQ("TestCaseWithCommentTest/0", test_cases[2]->name());
#endif // GTEST_HAS_TYPED_TEST
delete[] test_cases;
// The following lines initiate actions to verify certain methods in
// FinalSuccessChecker::TearDown.
// Records a test property to verify TestResult::GetTestProperty().
RecordProperty("key", "value");
}
AssertionResult IsNull(const char* str) {
if (str != NULL) {
return testing::AssertionFailure() << "argument is " << str;
}
return AssertionSuccess();
}
TEST(ApiTest, TestCaseImmutableAccessorsWork) {
const TestCase* test_case = UnitTestHelper::FindTestCase("ApiTest");
ASSERT_TRUE(test_case != NULL);
EXPECT_STREQ("ApiTest", test_case->name());
EXPECT_TRUE(IsNull(test_case->type_param()));
EXPECT_TRUE(test_case->should_run());
EXPECT_EQ(1, test_case->disabled_test_count());
EXPECT_EQ(3, test_case->test_to_run_count());
ASSERT_EQ(4, test_case->total_test_count());
const TestInfo** tests = UnitTestHelper::GetSortedTests(test_case);
EXPECT_STREQ("DISABLED_Dummy1", tests[0]->name());
EXPECT_STREQ("ApiTest", tests[0]->test_case_name());
EXPECT_TRUE(IsNull(tests[0]->value_param()));
EXPECT_TRUE(IsNull(tests[0]->type_param()));
EXPECT_FALSE(tests[0]->should_run());
EXPECT_STREQ("TestCaseDisabledAccessorsWork", tests[1]->name());
EXPECT_STREQ("ApiTest", tests[1]->test_case_name());
EXPECT_TRUE(IsNull(tests[1]->value_param()));
EXPECT_TRUE(IsNull(tests[1]->type_param()));
EXPECT_TRUE(tests[1]->should_run());
EXPECT_STREQ("TestCaseImmutableAccessorsWork", tests[2]->name());
EXPECT_STREQ("ApiTest", tests[2]->test_case_name());
EXPECT_TRUE(IsNull(tests[2]->value_param()));
EXPECT_TRUE(IsNull(tests[2]->type_param()));
EXPECT_TRUE(tests[2]->should_run());
EXPECT_STREQ("UnitTestImmutableAccessorsWork", tests[3]->name());
EXPECT_STREQ("ApiTest", tests[3]->test_case_name());
EXPECT_TRUE(IsNull(tests[3]->value_param()));
EXPECT_TRUE(IsNull(tests[3]->type_param()));
EXPECT_TRUE(tests[3]->should_run());
delete[] tests;
tests = NULL;
#if GTEST_HAS_TYPED_TEST
test_case = UnitTestHelper::FindTestCase("TestCaseWithCommentTest/0");
ASSERT_TRUE(test_case != NULL);
EXPECT_STREQ("TestCaseWithCommentTest/0", test_case->name());
EXPECT_STREQ(GetTypeName<int>().c_str(), test_case->type_param());
EXPECT_TRUE(test_case->should_run());
EXPECT_EQ(0, test_case->disabled_test_count());
EXPECT_EQ(1, test_case->test_to_run_count());
ASSERT_EQ(1, test_case->total_test_count());
tests = UnitTestHelper::GetSortedTests(test_case);
EXPECT_STREQ("Dummy", tests[0]->name());
EXPECT_STREQ("TestCaseWithCommentTest/0", tests[0]->test_case_name());
EXPECT_TRUE(IsNull(tests[0]->value_param()));
EXPECT_STREQ(GetTypeName<int>().c_str(), tests[0]->type_param());
EXPECT_TRUE(tests[0]->should_run());
delete[] tests;
#endif // GTEST_HAS_TYPED_TEST
}
TEST(ApiTest, TestCaseDisabledAccessorsWork) {
const TestCase* test_case = UnitTestHelper::FindTestCase("DISABLED_Test");
ASSERT_TRUE(test_case != NULL);
EXPECT_STREQ("DISABLED_Test", test_case->name());
EXPECT_TRUE(IsNull(test_case->type_param()));
EXPECT_FALSE(test_case->should_run());
EXPECT_EQ(1, test_case->disabled_test_count());
EXPECT_EQ(0, test_case->test_to_run_count());
ASSERT_EQ(1, test_case->total_test_count());
const TestInfo* const test_info = test_case->GetTestInfo(0);
EXPECT_STREQ("Dummy2", test_info->name());
EXPECT_STREQ("DISABLED_Test", test_info->test_case_name());
EXPECT_TRUE(IsNull(test_info->value_param()));
EXPECT_TRUE(IsNull(test_info->type_param()));
EXPECT_FALSE(test_info->should_run());
}
// These two tests are here to provide support for testing
// test_case_to_run_count, disabled_test_count, and test_to_run_count.
TEST(ApiTest, DISABLED_Dummy1) {}
TEST(DISABLED_Test, Dummy2) {}
class FinalSuccessChecker : public Environment {
protected:
virtual void TearDown() {
UnitTest* unit_test = UnitTest::GetInstance();
EXPECT_EQ(1 + kTypedTestCases, unit_test->successful_test_case_count());
EXPECT_EQ(3 + kTypedTests, unit_test->successful_test_count());
EXPECT_EQ(0, unit_test->failed_test_case_count());
EXPECT_EQ(0, unit_test->failed_test_count());
EXPECT_TRUE(unit_test->Passed());
EXPECT_FALSE(unit_test->Failed());
ASSERT_EQ(2 + kTypedTestCases, unit_test->total_test_case_count());
const TestCase** const test_cases = UnitTestHelper::GetSortedTestCases();
EXPECT_STREQ("ApiTest", test_cases[0]->name());
EXPECT_TRUE(IsNull(test_cases[0]->type_param()));
EXPECT_TRUE(test_cases[0]->should_run());
EXPECT_EQ(1, test_cases[0]->disabled_test_count());
ASSERT_EQ(4, test_cases[0]->total_test_count());
EXPECT_EQ(3, test_cases[0]->successful_test_count());
EXPECT_EQ(0, test_cases[0]->failed_test_count());
EXPECT_TRUE(test_cases[0]->Passed());
EXPECT_FALSE(test_cases[0]->Failed());
EXPECT_STREQ("DISABLED_Test", test_cases[1]->name());
EXPECT_TRUE(IsNull(test_cases[1]->type_param()));
EXPECT_FALSE(test_cases[1]->should_run());
EXPECT_EQ(1, test_cases[1]->disabled_test_count());
ASSERT_EQ(1, test_cases[1]->total_test_count());
EXPECT_EQ(0, test_cases[1]->successful_test_count());
EXPECT_EQ(0, test_cases[1]->failed_test_count());
#if GTEST_HAS_TYPED_TEST
EXPECT_STREQ("TestCaseWithCommentTest/0", test_cases[2]->name());
EXPECT_STREQ(GetTypeName<int>().c_str(), test_cases[2]->type_param());
EXPECT_TRUE(test_cases[2]->should_run());
EXPECT_EQ(0, test_cases[2]->disabled_test_count());
ASSERT_EQ(1, test_cases[2]->total_test_count());
EXPECT_EQ(1, test_cases[2]->successful_test_count());
EXPECT_EQ(0, test_cases[2]->failed_test_count());
EXPECT_TRUE(test_cases[2]->Passed());
EXPECT_FALSE(test_cases[2]->Failed());
#endif // GTEST_HAS_TYPED_TEST
const TestCase* test_case = UnitTestHelper::FindTestCase("ApiTest");
const TestInfo** tests = UnitTestHelper::GetSortedTests(test_case);
EXPECT_STREQ("DISABLED_Dummy1", tests[0]->name());
EXPECT_STREQ("ApiTest", tests[0]->test_case_name());
EXPECT_FALSE(tests[0]->should_run());
EXPECT_STREQ("TestCaseDisabledAccessorsWork", tests[1]->name());
EXPECT_STREQ("ApiTest", tests[1]->test_case_name());
EXPECT_TRUE(IsNull(tests[1]->value_param()));
EXPECT_TRUE(IsNull(tests[1]->type_param()));
EXPECT_TRUE(tests[1]->should_run());
EXPECT_TRUE(tests[1]->result()->Passed());
EXPECT_EQ(0, tests[1]->result()->test_property_count());
EXPECT_STREQ("TestCaseImmutableAccessorsWork", tests[2]->name());
EXPECT_STREQ("ApiTest", tests[2]->test_case_name());
EXPECT_TRUE(IsNull(tests[2]->value_param()));
EXPECT_TRUE(IsNull(tests[2]->type_param()));
EXPECT_TRUE(tests[2]->should_run());
EXPECT_TRUE(tests[2]->result()->Passed());
EXPECT_EQ(0, tests[2]->result()->test_property_count());
EXPECT_STREQ("UnitTestImmutableAccessorsWork", tests[3]->name());
EXPECT_STREQ("ApiTest", tests[3]->test_case_name());
EXPECT_TRUE(IsNull(tests[3]->value_param()));
EXPECT_TRUE(IsNull(tests[3]->type_param()));
EXPECT_TRUE(tests[3]->should_run());
EXPECT_TRUE(tests[3]->result()->Passed());
EXPECT_EQ(1, tests[3]->result()->test_property_count());
const TestProperty& property = tests[3]->result()->GetTestProperty(0);
EXPECT_STREQ("key", property.key());
EXPECT_STREQ("value", property.value());
delete[] tests;
#if GTEST_HAS_TYPED_TEST
test_case = UnitTestHelper::FindTestCase("TestCaseWithCommentTest/0");
tests = UnitTestHelper::GetSortedTests(test_case);
EXPECT_STREQ("Dummy", tests[0]->name());
EXPECT_STREQ("TestCaseWithCommentTest/0", tests[0]->test_case_name());
EXPECT_TRUE(IsNull(tests[0]->value_param()));
EXPECT_STREQ(GetTypeName<int>().c_str(), tests[0]->type_param());
EXPECT_TRUE(tests[0]->should_run());
EXPECT_TRUE(tests[0]->result()->Passed());
EXPECT_EQ(0, tests[0]->result()->test_property_count());
delete[] tests;
#endif // GTEST_HAS_TYPED_TEST
delete[] test_cases;
}
};
} // namespace internal
} // namespace testing
int main(int argc, char **argv) {
InitGoogleTest(&argc, argv);
AddGlobalTestEnvironment(new testing::internal::FinalSuccessChecker());
return RUN_ALL_TESTS();
}
<commit_msg>Removes unused include directive.<commit_after>// Copyright 2009 Google 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 Google 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.
//
// Author: [email protected] (Vlad Losev)
//
// The Google C++ Testing Framework (Google Test)
//
// This file contains tests verifying correctness of data provided via
// UnitTest's public methods.
#include "gtest/gtest.h"
#include <string.h> // For strcmp.
#include <algorithm>
using ::testing::InitGoogleTest;
namespace testing {
namespace internal {
template <typename T>
struct LessByName {
bool operator()(const T* a, const T* b) {
return strcmp(a->name(), b->name()) < 0;
}
};
class UnitTestHelper {
public:
// Returns the array of pointers to all test cases sorted by the test case
// name. The caller is responsible for deleting the array.
static TestCase const** const GetSortedTestCases() {
UnitTest& unit_test = *UnitTest::GetInstance();
TestCase const** const test_cases =
new const TestCase*[unit_test.total_test_case_count()];
for (int i = 0; i < unit_test.total_test_case_count(); ++i)
test_cases[i] = unit_test.GetTestCase(i);
std::sort(test_cases,
test_cases + unit_test.total_test_case_count(),
LessByName<TestCase>());
return test_cases;
}
// Returns the test case by its name. The caller doesn't own the returned
// pointer.
static const TestCase* FindTestCase(const char* name) {
UnitTest& unit_test = *UnitTest::GetInstance();
for (int i = 0; i < unit_test.total_test_case_count(); ++i) {
const TestCase* test_case = unit_test.GetTestCase(i);
if (0 == strcmp(test_case->name(), name))
return test_case;
}
return NULL;
}
// Returns the array of pointers to all tests in a particular test case
// sorted by the test name. The caller is responsible for deleting the
// array.
static TestInfo const** const GetSortedTests(const TestCase* test_case) {
TestInfo const** const tests =
new const TestInfo*[test_case->total_test_count()];
for (int i = 0; i < test_case->total_test_count(); ++i)
tests[i] = test_case->GetTestInfo(i);
std::sort(tests, tests + test_case->total_test_count(),
LessByName<TestInfo>());
return tests;
}
};
#if GTEST_HAS_TYPED_TEST
template <typename T> class TestCaseWithCommentTest : public Test {};
TYPED_TEST_CASE(TestCaseWithCommentTest, Types<int>);
TYPED_TEST(TestCaseWithCommentTest, Dummy) {}
const int kTypedTestCases = 1;
const int kTypedTests = 1;
#else
const int kTypedTestCases = 0;
const int kTypedTests = 0;
#endif // GTEST_HAS_TYPED_TEST
// We can only test the accessors that do not change value while tests run.
// Since tests can be run in any order, the values the accessors that track
// test execution (such as failed_test_count) can not be predicted.
TEST(ApiTest, UnitTestImmutableAccessorsWork) {
UnitTest* unit_test = UnitTest::GetInstance();
ASSERT_EQ(2 + kTypedTestCases, unit_test->total_test_case_count());
EXPECT_EQ(1 + kTypedTestCases, unit_test->test_case_to_run_count());
EXPECT_EQ(2, unit_test->disabled_test_count());
EXPECT_EQ(5 + kTypedTests, unit_test->total_test_count());
EXPECT_EQ(3 + kTypedTests, unit_test->test_to_run_count());
const TestCase** const test_cases = UnitTestHelper::GetSortedTestCases();
EXPECT_STREQ("ApiTest", test_cases[0]->name());
EXPECT_STREQ("DISABLED_Test", test_cases[1]->name());
#if GTEST_HAS_TYPED_TEST
EXPECT_STREQ("TestCaseWithCommentTest/0", test_cases[2]->name());
#endif // GTEST_HAS_TYPED_TEST
delete[] test_cases;
// The following lines initiate actions to verify certain methods in
// FinalSuccessChecker::TearDown.
// Records a test property to verify TestResult::GetTestProperty().
RecordProperty("key", "value");
}
AssertionResult IsNull(const char* str) {
if (str != NULL) {
return testing::AssertionFailure() << "argument is " << str;
}
return AssertionSuccess();
}
TEST(ApiTest, TestCaseImmutableAccessorsWork) {
const TestCase* test_case = UnitTestHelper::FindTestCase("ApiTest");
ASSERT_TRUE(test_case != NULL);
EXPECT_STREQ("ApiTest", test_case->name());
EXPECT_TRUE(IsNull(test_case->type_param()));
EXPECT_TRUE(test_case->should_run());
EXPECT_EQ(1, test_case->disabled_test_count());
EXPECT_EQ(3, test_case->test_to_run_count());
ASSERT_EQ(4, test_case->total_test_count());
const TestInfo** tests = UnitTestHelper::GetSortedTests(test_case);
EXPECT_STREQ("DISABLED_Dummy1", tests[0]->name());
EXPECT_STREQ("ApiTest", tests[0]->test_case_name());
EXPECT_TRUE(IsNull(tests[0]->value_param()));
EXPECT_TRUE(IsNull(tests[0]->type_param()));
EXPECT_FALSE(tests[0]->should_run());
EXPECT_STREQ("TestCaseDisabledAccessorsWork", tests[1]->name());
EXPECT_STREQ("ApiTest", tests[1]->test_case_name());
EXPECT_TRUE(IsNull(tests[1]->value_param()));
EXPECT_TRUE(IsNull(tests[1]->type_param()));
EXPECT_TRUE(tests[1]->should_run());
EXPECT_STREQ("TestCaseImmutableAccessorsWork", tests[2]->name());
EXPECT_STREQ("ApiTest", tests[2]->test_case_name());
EXPECT_TRUE(IsNull(tests[2]->value_param()));
EXPECT_TRUE(IsNull(tests[2]->type_param()));
EXPECT_TRUE(tests[2]->should_run());
EXPECT_STREQ("UnitTestImmutableAccessorsWork", tests[3]->name());
EXPECT_STREQ("ApiTest", tests[3]->test_case_name());
EXPECT_TRUE(IsNull(tests[3]->value_param()));
EXPECT_TRUE(IsNull(tests[3]->type_param()));
EXPECT_TRUE(tests[3]->should_run());
delete[] tests;
tests = NULL;
#if GTEST_HAS_TYPED_TEST
test_case = UnitTestHelper::FindTestCase("TestCaseWithCommentTest/0");
ASSERT_TRUE(test_case != NULL);
EXPECT_STREQ("TestCaseWithCommentTest/0", test_case->name());
EXPECT_STREQ(GetTypeName<int>().c_str(), test_case->type_param());
EXPECT_TRUE(test_case->should_run());
EXPECT_EQ(0, test_case->disabled_test_count());
EXPECT_EQ(1, test_case->test_to_run_count());
ASSERT_EQ(1, test_case->total_test_count());
tests = UnitTestHelper::GetSortedTests(test_case);
EXPECT_STREQ("Dummy", tests[0]->name());
EXPECT_STREQ("TestCaseWithCommentTest/0", tests[0]->test_case_name());
EXPECT_TRUE(IsNull(tests[0]->value_param()));
EXPECT_STREQ(GetTypeName<int>().c_str(), tests[0]->type_param());
EXPECT_TRUE(tests[0]->should_run());
delete[] tests;
#endif // GTEST_HAS_TYPED_TEST
}
TEST(ApiTest, TestCaseDisabledAccessorsWork) {
const TestCase* test_case = UnitTestHelper::FindTestCase("DISABLED_Test");
ASSERT_TRUE(test_case != NULL);
EXPECT_STREQ("DISABLED_Test", test_case->name());
EXPECT_TRUE(IsNull(test_case->type_param()));
EXPECT_FALSE(test_case->should_run());
EXPECT_EQ(1, test_case->disabled_test_count());
EXPECT_EQ(0, test_case->test_to_run_count());
ASSERT_EQ(1, test_case->total_test_count());
const TestInfo* const test_info = test_case->GetTestInfo(0);
EXPECT_STREQ("Dummy2", test_info->name());
EXPECT_STREQ("DISABLED_Test", test_info->test_case_name());
EXPECT_TRUE(IsNull(test_info->value_param()));
EXPECT_TRUE(IsNull(test_info->type_param()));
EXPECT_FALSE(test_info->should_run());
}
// These two tests are here to provide support for testing
// test_case_to_run_count, disabled_test_count, and test_to_run_count.
TEST(ApiTest, DISABLED_Dummy1) {}
TEST(DISABLED_Test, Dummy2) {}
class FinalSuccessChecker : public Environment {
protected:
virtual void TearDown() {
UnitTest* unit_test = UnitTest::GetInstance();
EXPECT_EQ(1 + kTypedTestCases, unit_test->successful_test_case_count());
EXPECT_EQ(3 + kTypedTests, unit_test->successful_test_count());
EXPECT_EQ(0, unit_test->failed_test_case_count());
EXPECT_EQ(0, unit_test->failed_test_count());
EXPECT_TRUE(unit_test->Passed());
EXPECT_FALSE(unit_test->Failed());
ASSERT_EQ(2 + kTypedTestCases, unit_test->total_test_case_count());
const TestCase** const test_cases = UnitTestHelper::GetSortedTestCases();
EXPECT_STREQ("ApiTest", test_cases[0]->name());
EXPECT_TRUE(IsNull(test_cases[0]->type_param()));
EXPECT_TRUE(test_cases[0]->should_run());
EXPECT_EQ(1, test_cases[0]->disabled_test_count());
ASSERT_EQ(4, test_cases[0]->total_test_count());
EXPECT_EQ(3, test_cases[0]->successful_test_count());
EXPECT_EQ(0, test_cases[0]->failed_test_count());
EXPECT_TRUE(test_cases[0]->Passed());
EXPECT_FALSE(test_cases[0]->Failed());
EXPECT_STREQ("DISABLED_Test", test_cases[1]->name());
EXPECT_TRUE(IsNull(test_cases[1]->type_param()));
EXPECT_FALSE(test_cases[1]->should_run());
EXPECT_EQ(1, test_cases[1]->disabled_test_count());
ASSERT_EQ(1, test_cases[1]->total_test_count());
EXPECT_EQ(0, test_cases[1]->successful_test_count());
EXPECT_EQ(0, test_cases[1]->failed_test_count());
#if GTEST_HAS_TYPED_TEST
EXPECT_STREQ("TestCaseWithCommentTest/0", test_cases[2]->name());
EXPECT_STREQ(GetTypeName<int>().c_str(), test_cases[2]->type_param());
EXPECT_TRUE(test_cases[2]->should_run());
EXPECT_EQ(0, test_cases[2]->disabled_test_count());
ASSERT_EQ(1, test_cases[2]->total_test_count());
EXPECT_EQ(1, test_cases[2]->successful_test_count());
EXPECT_EQ(0, test_cases[2]->failed_test_count());
EXPECT_TRUE(test_cases[2]->Passed());
EXPECT_FALSE(test_cases[2]->Failed());
#endif // GTEST_HAS_TYPED_TEST
const TestCase* test_case = UnitTestHelper::FindTestCase("ApiTest");
const TestInfo** tests = UnitTestHelper::GetSortedTests(test_case);
EXPECT_STREQ("DISABLED_Dummy1", tests[0]->name());
EXPECT_STREQ("ApiTest", tests[0]->test_case_name());
EXPECT_FALSE(tests[0]->should_run());
EXPECT_STREQ("TestCaseDisabledAccessorsWork", tests[1]->name());
EXPECT_STREQ("ApiTest", tests[1]->test_case_name());
EXPECT_TRUE(IsNull(tests[1]->value_param()));
EXPECT_TRUE(IsNull(tests[1]->type_param()));
EXPECT_TRUE(tests[1]->should_run());
EXPECT_TRUE(tests[1]->result()->Passed());
EXPECT_EQ(0, tests[1]->result()->test_property_count());
EXPECT_STREQ("TestCaseImmutableAccessorsWork", tests[2]->name());
EXPECT_STREQ("ApiTest", tests[2]->test_case_name());
EXPECT_TRUE(IsNull(tests[2]->value_param()));
EXPECT_TRUE(IsNull(tests[2]->type_param()));
EXPECT_TRUE(tests[2]->should_run());
EXPECT_TRUE(tests[2]->result()->Passed());
EXPECT_EQ(0, tests[2]->result()->test_property_count());
EXPECT_STREQ("UnitTestImmutableAccessorsWork", tests[3]->name());
EXPECT_STREQ("ApiTest", tests[3]->test_case_name());
EXPECT_TRUE(IsNull(tests[3]->value_param()));
EXPECT_TRUE(IsNull(tests[3]->type_param()));
EXPECT_TRUE(tests[3]->should_run());
EXPECT_TRUE(tests[3]->result()->Passed());
EXPECT_EQ(1, tests[3]->result()->test_property_count());
const TestProperty& property = tests[3]->result()->GetTestProperty(0);
EXPECT_STREQ("key", property.key());
EXPECT_STREQ("value", property.value());
delete[] tests;
#if GTEST_HAS_TYPED_TEST
test_case = UnitTestHelper::FindTestCase("TestCaseWithCommentTest/0");
tests = UnitTestHelper::GetSortedTests(test_case);
EXPECT_STREQ("Dummy", tests[0]->name());
EXPECT_STREQ("TestCaseWithCommentTest/0", tests[0]->test_case_name());
EXPECT_TRUE(IsNull(tests[0]->value_param()));
EXPECT_STREQ(GetTypeName<int>().c_str(), tests[0]->type_param());
EXPECT_TRUE(tests[0]->should_run());
EXPECT_TRUE(tests[0]->result()->Passed());
EXPECT_EQ(0, tests[0]->result()->test_property_count());
delete[] tests;
#endif // GTEST_HAS_TYPED_TEST
delete[] test_cases;
}
};
} // namespace internal
} // namespace testing
int main(int argc, char **argv) {
InitGoogleTest(&argc, argv);
AddGlobalTestEnvironment(new testing::internal::FinalSuccessChecker());
return RUN_ALL_TESTS();
}
<|endoftext|>
|
<commit_before>
#define TRACE_SYMPLECTIC_PARTITIONED_RUNGE_KUTTA_INTEGRATOR
#include "integrators/symplectic_partitioned_runge_kutta_integrator.hpp"
#include <algorithm>
#include <vector>
#include "geometry/sign.hpp"
#include "glog/logging.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "testing_utilities/numerics.hpp"
using principia::testing_utilities::AbsoluteError;
using testing::Lt;
namespace principia {
namespace integrators {
namespace {
inline void compute_harmonic_oscillator_force(double const t,
std::vector<double> const& q,
std::vector<double>* result) {
(*result)[0] = -q[0];
}
inline void compute_harmonic_oscillator_velocity(std::vector<double> const& p,
std::vector<double>* result) {
(*result)[0] = p[0];
}
} // namespace
class SPRKTest : public testing::Test {
protected:
void SetUp() override {
google::LogToStderr();
}
SPRKIntegrator integrator_;
SPRKIntegrator::Parameters parameters_;
SPRKIntegrator::Solution solution_;
};
TEST_F(SPRKTest, HarmonicOscillator) {
parameters_.q0 = {1.0};
parameters_.p0 = {0.0};
parameters_.t0 = 0.0;
#ifdef _DEBUG
parameters_.tmax = 100.0;
#else
parameters_.tmax = 1000.0;
#endif
parameters_.Δt = 1.0E-4;
parameters_.coefficients = integrator_.Order5Optimal();
parameters_.sampling_period = 1;
integrator_.Solve(&compute_harmonic_oscillator_force,
&compute_harmonic_oscillator_velocity,
parameters_, &solution_);
double q_error = 0;
double p_error = 0;
for (size_t i = 0; i < solution_.time.quantities.size(); ++i) {
q_error = std::max(q_error,
std::abs(solution_.position[0].quantities[i] -
std::cos(solution_.time.quantities[i])));
p_error = std::max(p_error,
std::abs(solution_.momentum[0].quantities[i] +
std::sin(solution_.time.quantities[i])));
}
LOG(INFO) << "q_error = " << q_error;
LOG(INFO) << "p_error = " << p_error;
EXPECT_THAT(q_error, Lt(2E-16 * parameters_.tmax));
EXPECT_THAT(p_error, Lt(2E-16 * parameters_.tmax));
}
} // namespace integrators
} // namespace principia
<commit_msg>After pleroy's review.<commit_after>
#define TRACE_SYMPLECTIC_PARTITIONED_RUNGE_KUTTA_INTEGRATOR
#include "integrators/symplectic_partitioned_runge_kutta_integrator.hpp"
#include <algorithm>
#include <vector>
#include "geometry/sign.hpp"
#include "glog/logging.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "testing_utilities/numerics.hpp"
using principia::testing_utilities::AbsoluteError;
using testing::Lt;
namespace principia {
namespace integrators {
namespace {
inline void compute_harmonic_oscillator_force(double const t,
std::vector<double> const& q,
std::vector<double>* result) {
(*result)[0] = -q[0];
}
inline void compute_harmonic_oscillator_velocity(std::vector<double> const& p,
std::vector<double>* result) {
(*result)[0] = p[0];
}
} // namespace
class SPRKTest : public testing::Test {
public:
static void SetUpTestCase() {
google::LogToStderr();
}
protected:
void SetUp() override {}
SPRKIntegrator integrator_;
SPRKIntegrator::Parameters parameters_;
SPRKIntegrator::Solution solution_;
};
TEST_F(SPRKTest, HarmonicOscillator) {
parameters_.q0 = {1.0};
parameters_.p0 = {0.0};
parameters_.t0 = 0.0;
#ifdef _DEBUG
parameters_.tmax = 100.0;
#else
parameters_.tmax = 1000.0;
#endif
parameters_.Δt = 1.0E-4;
parameters_.coefficients = integrator_.Order5Optimal();
parameters_.sampling_period = 1;
integrator_.Solve(&compute_harmonic_oscillator_force,
&compute_harmonic_oscillator_velocity,
parameters_, &solution_);
double q_error = 0;
double p_error = 0;
for (size_t i = 0; i < solution_.time.quantities.size(); ++i) {
q_error = std::max(q_error,
std::abs(solution_.position[0].quantities[i] -
std::cos(solution_.time.quantities[i])));
p_error = std::max(p_error,
std::abs(solution_.momentum[0].quantities[i] +
std::sin(solution_.time.quantities[i])));
}
LOG(INFO) << "q_error = " << q_error;
LOG(INFO) << "p_error = " << p_error;
EXPECT_THAT(q_error, Lt(2E-16 * parameters_.tmax));
EXPECT_THAT(p_error, Lt(2E-16 * parameters_.tmax));
}
} // namespace integrators
} // namespace principia
<|endoftext|>
|
<commit_before>/*
This file is part of KitchenSync.
Copyright (c) 2004 Cornelius Schumacher <[email protected]>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*/
#include "remotekonnectorconfig.h"
#include "remotekonnector.h"
#include <libkcal/resourcelocal.h>
#include <kconfig.h>
#include <klocale.h>
#include <kabc/resourcefile.h>
#include <kmessagebox.h>
#include <kinputdialog.h>
#include <klineedit.h>
#include <qlabel.h>
#include <qlayout.h>
#include <qpushbutton.h>
using namespace KSync;
RemoteKonnectorConfig::RemoteKonnectorConfig( QWidget *parent )
: KRES::ConfigWidget( parent, 0 )
{
QBoxLayout *topLayout = new QVBoxLayout( this );
QPushButton *button = new QPushButton( i18n("Standard Setup..."), this );
topLayout->addWidget( button );
connect( button, SIGNAL( clicked() ), SLOT( setupStandard() ) );
// makes no sense... do we need it at all?
button->hide();
topLayout->addWidget( new QLabel( i18n("Calendar file:"), this ) );
mCalendarUrl = new KURLRequester( this );
mCalendarUrl->setMode( KFile::File );
topLayout->addWidget( mCalendarUrl );
topLayout->addSpacing( 4 );
topLayout->addWidget( new QLabel( i18n("Address book file:"), this ) );
mAddressBookUrl = new KURLRequester( this );
mAddressBookUrl->setMode( KFile::File );
topLayout->addWidget( mAddressBookUrl );
}
RemoteKonnectorConfig::~RemoteKonnectorConfig()
{
}
void RemoteKonnectorConfig::loadSettings( KRES::Resource *r )
{
RemoteKonnector *konnector = dynamic_cast<RemoteKonnector *>( r );
if ( konnector ) {
mCalendarUrl->setURL( konnector->calendarUrl() );
mAddressBookUrl->setURL( konnector->addressBookUrl() );
}
}
void RemoteKonnectorConfig::saveSettings( KRES::Resource *r )
{
RemoteKonnector *konnector = dynamic_cast<RemoteKonnector *>( r );
if ( konnector ) {
konnector->setCalendarUrl( mCalendarUrl->url() );
konnector->setAddressBookUrl( mAddressBookUrl->url() );
}
}
void RemoteKonnectorConfig::setupStandard()
{
}
#include "remotekonnectorconfig.moc"
<commit_msg>Enable the setup button again and ask for the remote host and user name to create the URLs for address book and calendar automatically.<commit_after>/*
This file is part of KitchenSync.
Copyright (c) 2004 Cornelius Schumacher <[email protected]>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*/
#include "remotekonnectorconfig.h"
#include "remotekonnector.h"
#include <libkcal/resourcelocal.h>
#include <kconfig.h>
#include <klocale.h>
#include <kabc/resourcefile.h>
#include <kmessagebox.h>
#include <kinputdialog.h>
#include <klineedit.h>
#include <qinputdialog.h>
#include <qlabel.h>
#include <qlayout.h>
#include <qpushbutton.h>
using namespace KSync;
RemoteKonnectorConfig::RemoteKonnectorConfig( QWidget *parent )
: KRES::ConfigWidget( parent, 0 )
{
QBoxLayout *topLayout = new QVBoxLayout( this );
QPushButton *button = new QPushButton( i18n("Standard Setup..."), this );
topLayout->addWidget( button );
connect( button, SIGNAL( clicked() ), SLOT( setupStandard() ) );
topLayout->addWidget( new QLabel( i18n("Calendar file:"), this ) );
mCalendarUrl = new KURLRequester( this );
mCalendarUrl->setMode( KFile::File );
topLayout->addWidget( mCalendarUrl );
topLayout->addSpacing( 4 );
topLayout->addWidget( new QLabel( i18n("Address book file:"), this ) );
mAddressBookUrl = new KURLRequester( this );
mAddressBookUrl->setMode( KFile::File );
topLayout->addWidget( mAddressBookUrl );
}
RemoteKonnectorConfig::~RemoteKonnectorConfig()
{
}
void RemoteKonnectorConfig::loadSettings( KRES::Resource *r )
{
RemoteKonnector *konnector = dynamic_cast<RemoteKonnector *>( r );
if ( konnector ) {
mCalendarUrl->setURL( konnector->calendarUrl() );
mAddressBookUrl->setURL( konnector->addressBookUrl() );
}
}
void RemoteKonnectorConfig::saveSettings( KRES::Resource *r )
{
RemoteKonnector *konnector = dynamic_cast<RemoteKonnector *>( r );
if ( konnector ) {
konnector->setCalendarUrl( mCalendarUrl->url() );
konnector->setAddressBookUrl( mAddressBookUrl->url() );
}
}
void RemoteKonnectorConfig::setupStandard()
{
bool ok = false;
QString hostname = QInputDialog::getText( i18n( "Remote Host" ), i18n( "Enter remote host name" ),
QLineEdit::Normal, QString::null, &ok, this );
if ( hostname.isEmpty() || !ok )
return;
QString username = QInputDialog::getText( i18n( "Remote User" ), i18n( "Enter remote user name" ),
QLineEdit::Normal, QString::null, &ok, this );
if ( username.isEmpty() || !ok )
return;
QString urlBase = "fish://" + hostname + "/~" + username + "/";
mCalendarUrl->setURL( urlBase + ".kde/share/apps/korganizer/std.ics" );
mAddressBookUrl->setURL( urlBase + ".kde/share/apps/kabc/std.vcf" );
}
#include "remotekonnectorconfig.moc"
<|endoftext|>
|
<commit_before>/*******************************************************************************
* ALMA - Atacama Large Millimiter Array
* (c) European Southern Observatory, 2005
*
* 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
*
* "@(#) $Id: testACSThreadJoinable.cpp,v 1.10 2009/08/26 13:54:58 bjeram Exp $"
*
* who when what
* -------- -------- ----------------------------------------------
* bjeram 2005-02-15 created
*/
#define NO_SHORT_LOG
#include "acsThreadManager.h"
#include "acsThread.h"
#include <logging.h>
#include "acsThreadTest.h"
static char *rcsId="@(#) $Id: testACSThreadJoinable.cpp,v 1.10 2009/08/26 13:54:58 bjeram Exp $";
static void *use_rcsId = ((void)&use_rcsId,(void *) &rcsId);
/**
@file
On my machine, this program will fail around 1510 threads.
Besides, if I add "join" in acsThreaBase destructor , this program
can run much longer ( more than 3500 threads till now ).
*/
#define MAX_THREADS 2000
/**
* This is just a minimal thread class that executes an empty loop
* at the specified sleepTime frequncy
*/
class FastACSThread :public ACS::Thread
{
public:
FastACSThread(const ACE_CString& name,
int i,
const ACS::TimeInterval& responseTime=ThreadBase::defaultResponseTime,
const ACS::TimeInterval& sleepTime=ThreadBase::defaultSleepTime,
bool del=false
) :
ACS::Thread(name, responseTime, sleepTime, del )
{
ACS_TRACE("FastACSThread::FastACSThread");
num = i;
}
FastACSThread(const ACE_CString& name,
int i,
const ACS::TimeInterval& responseTime,
const ACS::TimeInterval& sleepTime,
bool del,
const long _thrFlags
) :
ACS::Thread(name, responseTime, sleepTime, del, _thrFlags, 512)
{
ACS_TRACE("FastACSThread::FastACSThread");
num = i;
}
virtual ~FastACSThread()
{
// std::cout << pthread_self() << " deleted " << std::endl;
}
/**
* This is the method executed in the thread loop.
* It is just an empty method.
*/
virtual void runLoop()
{
/*
* we removed writing to stdout because on some machine the runLoop was not executed at all
* on some other was executed for some threads several (different number)
#ifndef MAKE_VXWORKS
std::cout << pthread_self() << " runLoop()" << std::endl;
#else
std::cout << taskIdSelf() << " runLoop()" << std::endl;
#endif
*/
}
int num;
};
int main(int argc, char *argv[])
{
/*
* Unset the ACS_LOG_STDOUT environment variable,
* to make sure only LM_INFO messages go on stdout.
* The test tat environment would otherwise
* set it to 0, slooding with messages.
* Under VxWorks we will "unset" it from the script.
*/
#ifndef MAKE_VXWORKS
unsetenv("ACS_LOG_STDOUT");
#endif
if (argc < 2)
{
printf ("Usage: %s # of threads\n",argv[0]);
return -1;
}
int numOfThread = atoi(argv[1]);
if (numOfThread > MAX_THREADS)
{
printf ("ERROR: # of threads should be less than %d\n", MAX_THREADS);
return -2;
}
LoggingProxy logger_m(0, 0, 31);
LoggingProxy::init(&logger_m);
ACS::ThreadManager tm;
int l = 0;
ACE_thread_t threadId;
ACE_thread_t threadIdVec[numOfThread];
/*
* In the first test we create and destroy numOfThread
* DETACHED threads.
* This should work without problems.
*/
ACS_SHORT_LOG(( LM_INFO, "===== 1 - create DETACHED threads"));
try
{
for( l=0; l<numOfThread; l++)
{
FastACSThread *a = tm.create<FastACSThread, int>("TestThreadA",
l,
5000000, /* 500ms */
1000000, /* 100ms */
false,
THR_NEW_LWP | THR_DETACHED);
// ACS_SHORT_LOG(( LM_INFO, "Progress: %ld thread created", l+1 ));
a->resume();
threadId = a->getThreadID();
// std::cout << threadId << " created " << std::endl;
tm.destroy(a);
}
}
catch(acsthreadErrType::CanNotCreateThreadExImpl)
{
ACS_SHORT_LOG(( LM_INFO, "acsthreadErrType::CanNotCreateThreadExImpl catched. Counter is: %ld", l ));
}
catch(...)
{
ACS_SHORT_LOG(( LM_INFO, "UNKNOWN exception catched, program stop" ));
}
ACS_SHORT_LOG(( LM_INFO, "Created threads: %ld", l ));
/*
* In the second test we TRY to create and destroy numOfThread
* JOINABLE threads, but we do not join them.
* This should fail with an exception when resources are exausted.
*/
ACS_SHORT_LOG(( LM_INFO, "===== 2 - create JOINABLE threads"));
try
{
for( l=0; l<numOfThread ; l++)
{
FastACSThread *a = tm.create<FastACSThread, int>("TestThreadA",
l,
5000000, /* 500ms */
1000000, /* 100ms */
false,
THR_NEW_LWP | THR_JOINABLE);
a->resume();
// ACS_SHORT_LOG(( LM_INFO, "Progress: %ld thread created", l+1 ));
threadIdVec[l] = a->getThreadID();
tm.destroy(a);
}
}
catch(acsthreadErrType::CanNotCreateThreadExImpl)
{
ACS_SHORT_LOG(( LM_INFO, "acsthreadErrType::CanNotCreateThreadExImpl catched. Counter is: %ld", l ));
}
catch(...)
{
ACS_SHORT_LOG(( LM_INFO, "UNKNOWN exception catched, program stop" ));
}
/*
* Then we try to join all threads we had managed to create.
*/
/***********************************************************
* GCH
* With this join, the test sefgault exiting at the end.
* If I comment it out, it does not segfault.
* This is very strange, but I cannot understand why!!!!
***********************************************************/
int totalCreated = l;
ACS_SHORT_LOG(( LM_INFO, "===== 3 - join the threads"));
for( l=0; l<totalCreated; l++)
{
ACE_thread_t tid = threadIdVec[l];
// ACE_Thread::join(tid);
tm.join(tid);
}
/*
* In the second test we TRY to create and destroy numOfThread
* JOINABLE threads, but we join them.
* This should not fail.
*/
ACS_SHORT_LOG(( LM_INFO, "===== 4 - create, destroy and JOIN threads"));
try
{
for( l=0; l<numOfThread; l++)
{
FastACSThread *a = tm.create<FastACSThread, int>("TestThreadA",
l,
5000000, /* 500ms */
1000000, /* 100ms */
false,
THR_NEW_LWP | THR_JOINABLE);
a->resume();
// ACS_SHORT_LOG(( LM_INFO, "Progress: %ld thread created", l+1 ));
threadId = a->getThreadID();
tm.destroy(a);
// ACE_Thread::join(threadId);
int retn = tm.join(threadId);
if( retn != 0 )
ACS_SHORT_LOG(( LM_INFO, "Join fail, return %d", retn ));
}
}
catch(acsthreadErrType::CanNotCreateThreadExImpl)
{
ACS_SHORT_LOG(( LM_INFO, "acsthreadErrType::CanNotCreateThreadExImpl catched. Counter is: %ld", l ));
}
catch(...)
{
ACS_SHORT_LOG(( LM_INFO, "UNKNOWN exception catched, program stop" ));
}
/*
* In the second test we TRY to create and destroy
* JOINABLE threads, but we join them.
* This should not fail.
*/
ACS_SHORT_LOG(( LM_INFO, "===== 5 - create, destroy and join a DETACHED thread"));
try {
FastACSThread *a = tm.create<FastACSThread, int>("TestThreadA",
l,
5000000, /* 500ms */
1000000, /* 100ms */
false,
THR_NEW_LWP | THR_DETACHED);
threadId = a->getThreadID();
tm.destroy(a);
int retn = tm.join(threadId);
if( retn != 0 )
ACS_SHORT_LOG(( LM_INFO, "Join fail, return %d, as expected", retn ));
}
catch(...)
{
ACS_SHORT_LOG(( LM_INFO, "UNKNOWN exception catched, program stop" ));
}
sleep(5);
ACS_SHORT_LOG(( LM_INFO, "Done" ));
return 0;
}
<commit_msg>Fixed Joinable test which gave a segmentation fault due to a too small stack size. Changed also the response time of threads to a greater one<commit_after>/*******************************************************************************
* ALMA - Atacama Large Millimiter Array
* (c) European Southern Observatory, 2005
*
* 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
*
* "@(#) $Id: testACSThreadJoinable.cpp,v 1.10 2009/08/26 13:54:58 bjeram Exp $"
*
* who when what
* -------- -------- ----------------------------------------------
* bjeram 2005-02-15 created
*/
#define NO_SHORT_LOG
#include "acsThreadManager.h"
#include "acsThread.h"
#include <logging.h>
#include "acsThreadTest.h"
static char *rcsId="@(#) $Id: testACSThreadJoinable.cpp,v 1.10 2009/08/26 13:54:58 bjeram Exp $";
static void *use_rcsId = ((void)&use_rcsId,(void *) &rcsId);
/**
@file
On my machine, this program will fail around 1510 threads.
Besides, if I add "join" in acsThreaBase destructor , this program
can run much longer ( more than 3500 threads till now ).
*/
#define MAX_THREADS 2000
/**
* This is just a minimal thread class that executes an empty loop
* at the specified sleepTime frequncy
*/
class FastACSThread :public ACS::Thread
{
public:
FastACSThread(const ACE_CString& name,
int i,
const ACS::TimeInterval& responseTime=ThreadBase::defaultResponseTime,
const ACS::TimeInterval& sleepTime=ThreadBase::defaultSleepTime,
bool del=false
) :
ACS::Thread(name, responseTime, sleepTime, del )
{
ACS_TRACE("FastACSThread::FastACSThread");
num = i;
}
FastACSThread(const ACE_CString& name,
int i,
const ACS::TimeInterval& responseTime,
const ACS::TimeInterval& sleepTime,
bool del,
const long _thrFlags
) :
ACS::Thread(name, responseTime, sleepTime, del, _thrFlags,0/* 25000*/)
{
ACS_TRACE("FastACSThread::FastACSThread");
num = i;
}
virtual ~FastACSThread()
{
// std::cout << pthread_self() << " deleted " << std::endl;
}
/**
* This is the method executed in the thread loop.
* It is just an empty method.
*/
virtual void runLoop()
{
/*
* we removed writing to stdout because on some machine the runLoop was not executed at all
* on some other was executed for some threads several (different number)
#ifndef MAKE_VXWORKS
std::cout << pthread_self() << " runLoop()" << std::endl;
#else
std::cout << taskIdSelf() << " runLoop()" << std::endl;
#endif
*/
}
int num;
};
int main(int argc, char *argv[])
{
/*
* Unset the ACS_LOG_STDOUT environment variable,
* to make sure only LM_INFO messages go on stdout.
* The test tat environment would otherwise
* set it to 0, slooding with messages.
* Under VxWorks we will "unset" it from the script.
*/
#ifndef MAKE_VXWORKS
unsetenv("ACS_LOG_STDOUT");
#endif
if (argc < 2)
{
printf ("Usage: %s # of threads\n",argv[0]);
return -1;
}
int numOfThread = atoi(argv[1]);
if (numOfThread > MAX_THREADS)
{
printf ("ERROR: # of threads should be less than %d\n", MAX_THREADS);
return -2;
}
LoggingProxy logger_m(0, 0, 31);
LoggingProxy::init(&logger_m);
ACS::ThreadManager tm;
int l = 0;
ACE_thread_t threadId;
ACE_thread_t threadIdVec[numOfThread];
/*
* In the first test we create and destroy numOfThread
* DETACHED threads.
* This should work without problems.
*/
ACS_SHORT_LOG(( LM_INFO, "===== 1 - create DETACHED threads"));
try
{
for( l=0; l<numOfThread; l++)
{
FastACSThread *a = tm.create<FastACSThread, int>("TestThreadA",
l,
30000000, /* 500ms */
1000000, /* 100ms */
false,
THR_NEW_LWP | THR_DETACHED);
// ACS_SHORT_LOG(( LM_INFO, "Progress: %ld thread created", l+1 ));
a->resume();
threadId = a->getThreadID();
// std::cout << threadId << " created " << std::endl;
tm.destroy(a);
}
}
catch(acsthreadErrType::CanNotCreateThreadExImpl)
{
ACS_SHORT_LOG(( LM_INFO, "acsthreadErrType::CanNotCreateThreadExImpl catched. Counter is: %ld", l ));
}
catch(...)
{
ACS_SHORT_LOG(( LM_INFO, "UNKNOWN exception catched, program stop" ));
}
ACS_SHORT_LOG(( LM_INFO, "Created threads: %ld", l ));
/*
* In the second test we TRY to create and destroy numOfThread
* JOINABLE threads, but we do not join them.
* This should fail with an exception when resources are exausted.
*/
ACS_SHORT_LOG(( LM_INFO, "===== 2 - create JOINABLE threads"));
try
{
for( l=0; l<numOfThread ; l++)
{
FastACSThread *a = tm.create<FastACSThread, int>("TestThreadA",
l,
30000000, /* 500ms */
1000000, /* 100ms */
false,
THR_NEW_LWP | THR_JOINABLE);
a->resume();
// ACS_SHORT_LOG(( LM_INFO, "Progress: %ld thread created", l+1 ));
threadIdVec[l] = a->getThreadID();
tm.destroy(a);
}
}
catch(acsthreadErrType::CanNotCreateThreadExImpl)
{
ACS_SHORT_LOG(( LM_INFO, "acsthreadErrType::CanNotCreateThreadExImpl catched. Counter is: %ld", l ));
}
catch(...)
{
ACS_SHORT_LOG(( LM_INFO, "UNKNOWN exception catched, program stop" ));
}
/*
* Then we try to join all threads we had managed to create.
*/
/***********************************************************
* GCH
* With this join, the test sefgault exiting at the end.
* If I comment it out, it does not segfault.
* This is very strange, but I cannot understand why!!!!
***********************************************************/
int totalCreated = l;
ACS_SHORT_LOG(( LM_INFO, "===== 3 - join the threads"));
for( l=0; l<totalCreated; l++)
{
ACE_thread_t tid = threadIdVec[l];
// ACE_Thread::join(tid);
tm.join(tid);
}
/*
* In the second test we TRY to create and destroy numOfThread
* JOINABLE threads, but we join them.
* This should not fail.
*/
ACS_SHORT_LOG(( LM_INFO, "===== 4 - create, destroy and JOIN threads"));
try
{
for( l=0; l<numOfThread; l++)
{
FastACSThread *a = tm.create<FastACSThread, int>("TestThreadA",
l,
30000000, /* 500ms */
1000000, /* 100ms */
false,
THR_NEW_LWP | THR_JOINABLE);
a->resume();
// ACS_SHORT_LOG(( LM_INFO, "Progress: %ld thread created", l+1 ));
threadId = a->getThreadID();
tm.destroy(a);
// ACE_Thread::join(threadId);
int retn = tm.join(threadId);
if( retn != 0 )
ACS_SHORT_LOG(( LM_INFO, "Join fail, return %d", retn ));
}
}
catch(acsthreadErrType::CanNotCreateThreadExImpl)
{
ACS_SHORT_LOG(( LM_INFO, "acsthreadErrType::CanNotCreateThreadExImpl catched. Counter is: %ld", l ));
}
catch(...)
{
ACS_SHORT_LOG(( LM_INFO, "UNKNOWN exception catched, program stop" ));
}
/*
* In the second test we TRY to create and destroy
* JOINABLE threads, but we join them.
* This should not fail.
*/
ACS_SHORT_LOG(( LM_INFO, "===== 5 - create, destroy and join a DETACHED thread"));
try {
FastACSThread *a = tm.create<FastACSThread, int>("TestThreadA",
l,
30000000, /* 500ms */
1000000, /* 100ms */
false,
THR_NEW_LWP | THR_DETACHED);
threadId = a->getThreadID();
tm.destroy(a);
int retn = tm.join(threadId);
if( retn != 0 )
ACS_SHORT_LOG(( LM_INFO, "Join fail, return %d, as expected", retn ));
}
catch(...)
{
ACS_SHORT_LOG(( LM_INFO, "UNKNOWN exception catched, program stop" ));
}
sleep(5);
ACS_SHORT_LOG(( LM_INFO, "Done" ));
return 0;
}
<|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 "otbWrapperApplicationFactory.h"
#include "otbMultiToMonoChannelExtractROI.h"
#include "otbGenericRSResampleImageFilter.h"
#include "otbGridResampleImageFilter.h"
#include "otbImportGeoInformationImageFilter.h"
#include "otbBCOInterpolateImageFunction.h"
#include "otbSimpleRcsPanSharpeningFusionImageFilter.h"
#include "itkFixedArray.h"
// Elevation handler
#include "otbWrapperElevationParametersHandler.h"
#include "otbPleiadesPToXSAffineTransformCalculator.h"
namespace otb
{
namespace Wrapper
{
class BundleToPerfectSensor : public Application
{
public:
/** Standard class typedefs. */
typedef BundleToPerfectSensor Self;
typedef Application Superclass;
typedef itk::SmartPointer<Self> Pointer;
typedef itk::SmartPointer<const Self> ConstPointer;
/** Standard macro */
itkNewMacro(Self);
itkTypeMacro(BundleToPerfectSensor, otb::Application);
private:
void DoInit() ITK_OVERRIDE
{
SetName("BundleToPerfectSensor");
SetDescription("Perform P+XS pansharpening");
// Documentation
SetDocName("Bundle to perfect sensor");
SetDocLongDescription("This application performs P+XS pansharpening. The default mode use Pan and XS sensor models to estimate the transformation to superimpose XS over Pan before the fusion (\"default mode\"). The application provides also a PHR mode for Pleiades images which does not use sensor models as Pan and XS products are already coregistered but only estimate an affine transformation to superimpose XS over the Pan.Note that this option is automatically activated in case Pleiades images are detected as input.");
SetDocLimitations("None");
SetDocAuthors("OTB-Team");
SetDocSeeAlso(" ");
AddDocTag(Tags::Geometry);
AddDocTag(Tags::Pansharpening);
AddParameter(ParameterType_InputImage, "inp", "Input PAN Image");
SetParameterDescription("inp"," Input panchromatic image.");
AddParameter(ParameterType_InputImage, "inxs", "Input XS Image");
SetParameterDescription("inxs"," Input XS image.");
AddParameter(ParameterType_OutputImage, "out", "Output image");
SetParameterDescription("out"," Output image.");
// Elevation
ElevationParametersHandler::AddElevationParameters(this, "elev");
// Superposition mode
AddParameter(ParameterType_Choice,"mode", "Mode");
SetParameterDescription("mode", "Superimposition mode");
AddChoice("mode.default", "Default mode");
SetParameterDescription("mode.default", "Default superimposition mode : "
"uses any projection reference or sensor model found in the images");
AddChoice("mode.phr", "Pleiades mode");
SetParameterDescription("mode.phr", "Pleiades superimposition mode, "
"designed for the case of a P+XS bundle in SENSOR geometry. It uses"
" a simple transform on the XS image : a scaling and a residual "
"translation.");
AddParameter(ParameterType_Float, "lms", "Spacing of the deformation field");
SetParameterDescription("lms"," Spacing of the deformation field. Default is 10 times the PAN image spacing.");
AddRAMParameter();
MandatoryOff("lms");
// Doc example parameter settings
SetDocExampleParameterValue("inp", "QB_Toulouse_Ortho_PAN.tif");
SetDocExampleParameterValue("inxs", "QB_Toulouse_Ortho_XS.tif");
SetDocExampleParameterValue("out", "BundleToPerfectSensor.png uchar");
}
void DoUpdateParameters() ITK_OVERRIDE
{
if(!HasUserValue("mode") && HasValue("inp") && HasValue("inxs") && otb::PleiadesPToXSAffineTransformCalculator::CanCompute(GetParameterImage("inp"),GetParameterImage("inxs")))
{
otbAppLogWARNING("Forcing PHR mode with PHR data. You need to add \"-mode default\" to force the default mode with PHR images.");
SetParameterString("mode","phr");
}
}
void DoExecute() ITK_OVERRIDE
{
FloatVectorImageType* panchroV = GetParameterImage("inp");
FloatVectorImageType* xs = GetParameterImage("inxs");
if ( panchroV->GetNumberOfComponentsPerPixel() != 1 )
{
itkExceptionMacro(<< "The panchromatic image must be a single channel image")
}
// Transform the PAN image to otb::Image
typedef otb::Image<FloatVectorImageType::InternalPixelType> InternalImageType;
typedef otb::MultiToMonoChannelExtractROI<float,float> ExtractFilterType;
ExtractFilterType::Pointer channelSelect = ExtractFilterType::New();
m_Ref.push_back(channelSelect.GetPointer());
channelSelect->SetChannel(1);
channelSelect->SetInput(panchroV);
channelSelect->UpdateOutputInformation();
InternalImageType::Pointer panchro = channelSelect->GetOutput();
typedef otb::BCOInterpolateImageFunction<FloatVectorImageType> InterpolatorType;
typedef otb::GenericRSResampleImageFilter<FloatVectorImageType, FloatVectorImageType> ResamplerType;
typedef otb::GridResampleImageFilter<FloatVectorImageType, FloatVectorImageType> BasicResamplerType;
typedef otb::ImportGeoInformationImageFilter<FloatVectorImageType,InternalImageType> ImportGeoInformationFilterType;
typedef otb::SimpleRcsPanSharpeningFusionImageFilter<InternalImageType, FloatVectorImageType, FloatVectorImageType> FusionFilterType;
// Resample filter
ResamplerType::Pointer resampler = ResamplerType::New();
m_Ref.push_back(resampler.GetPointer());
BasicResamplerType::Pointer basicResampler = BasicResamplerType::New();
m_Ref.push_back(basicResampler.GetPointer());
ImportGeoInformationFilterType::Pointer geoImport = ImportGeoInformationFilterType::New();
m_Ref.push_back(geoImport.GetPointer());
InterpolatorType::Pointer interpolator = InterpolatorType::New();
resampler->SetInterpolator(interpolator);
basicResampler->SetInterpolator(interpolator);
// Fusion filter
FusionFilterType::Pointer fusionFilter = FusionFilterType::New();
m_Ref.push_back(fusionFilter.GetPointer());
fusionFilter->SetPanInput(panchro);
// Setup the DEM Handler
otb::Wrapper::ElevationParametersHandler::SetupDEMHandlerFromElevationParameters(this,"elev");
// Set up output image information
FloatVectorImageType::SpacingType spacing = panchro->GetSpacing();
FloatVectorImageType::IndexType start = panchro->GetLargestPossibleRegion().GetIndex();
FloatVectorImageType::SizeType size = panchro->GetLargestPossibleRegion().GetSize();
FloatVectorImageType::PointType origin = panchro->GetOrigin();
FloatVectorImageType::PixelType defaultValue;
itk::NumericTraits<FloatVectorImageType::PixelType>::SetLength(defaultValue, xs->GetNumberOfComponentsPerPixel());
if(GetParameterString("mode") == "default")
{
otbAppLogINFO("Using the default mode");
if(IsParameterEnabled("lms") && HasValue("lms"))
{
double defScalarSpacing = GetParameterFloat("lms");
otbAppLogINFO(<< "Generating coarse deformation field (spacing="<<defScalarSpacing<<")" << std::endl);
FloatVectorImageType::SpacingType defSpacing;
defSpacing[0] = defScalarSpacing;
defSpacing[1] = defScalarSpacing;
resampler->SetDisplacementFieldSpacing(defSpacing);
}
else
{
FloatVectorImageType::SpacingType defSpacing;
defSpacing[0]=10*spacing[0];
defSpacing[1]=10*spacing[1];
resampler->SetDisplacementFieldSpacing(defSpacing);
}
resampler->SetInput(xs);
resampler->SetOutputOrigin(origin);
resampler->SetOutputSpacing(spacing);
resampler->SetOutputSize(size);
resampler->SetOutputStartIndex(start);
resampler->SetOutputKeywordList(panchro->GetImageKeywordlist());
resampler->SetOutputProjectionRef(panchro->GetProjectionRef());
resampler->SetEdgePaddingValue(defaultValue);
fusionFilter->SetXsInput(resampler->GetOutput());
}
else if(GetParameterString("mode")=="phr")
{
otbAppLogINFO("Using the PHR mode");
otb::PleiadesPToXSAffineTransformCalculator::TransformType::OffsetType offset
= otb::PleiadesPToXSAffineTransformCalculator::ComputeOffset(GetParameterImage("inp"),
GetParameterImage("inxs"));
origin+=offset;
origin[0]=origin[0]/4;
origin[1]=origin[1]/4;
basicResampler->SetOutputOrigin(origin);
basicResampler->SetInput(xs);
basicResampler->SetOutputOrigin(origin);
FloatVectorImageType::SpacingType xsSpacing = GetParameterImage("inxs")->GetSpacing();
xsSpacing*=0.25;
basicResampler->SetOutputSpacing(xsSpacing);
basicResampler->SetOutputSize(size);
basicResampler->SetOutputStartIndex(start);
basicResampler->SetEdgePaddingValue(defaultValue);
geoImport->SetInput(basicResampler->GetOutput());
geoImport->SetSource(panchro);
fusionFilter->SetXsInput(geoImport->GetOutput());
// Set the profRef & Keywordlist from Pan into the resampled XS image
basicResampler->UpdateOutputInformation();
itk::MetaDataDictionary& dict = basicResampler->GetOutput()->GetMetaDataDictionary();
itk::EncapsulateMetaData<std::string>(dict, MetaDataKey::ProjectionRefKey,
panchro->GetProjectionRef());
itk::EncapsulateMetaData<ImageKeywordlist>(dict, MetaDataKey::OSSIMKeywordlistKey,
panchro->GetImageKeywordlist());
}
else
{
otbAppLogWARNING("Unknown mode");
}
SetParameterOutputImage("out", fusionFilter->GetOutput());
}
std::vector<itk::ProcessObject::Pointer> m_Ref;
};
}
}
OTB_APPLICATION_EXPORT(otb::Wrapper::BundleToPerfectSensor)
<commit_msg>ENH: refactor BundleToPerfectSensor<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 "otbWrapperApplicationFactory.h"
#include "otbWrapperCompositeApplication.h"
namespace otb
{
namespace Wrapper
{
class BundleToPerfectSensor : public CompositeApplication
{
public:
/** Standard class typedefs. */
typedef BundleToPerfectSensor Self;
typedef Application Superclass;
typedef itk::SmartPointer<Self> Pointer;
typedef itk::SmartPointer<const Self> ConstPointer;
/** Standard macro */
itkNewMacro(Self);
itkTypeMacro(BundleToPerfectSensor, otb::Wrapper::CompositeApplication);
private:
void DoInit() ITK_OVERRIDE
{
SetName("BundleToPerfectSensor");
SetDescription("Perform P+XS pansharpening");
// Documentation
SetDocName("Bundle to perfect sensor");
SetDocLongDescription("This application performs P+XS pansharpening. The default mode use Pan and XS sensor models to estimate the transformation to superimpose XS over Pan before the fusion (\"default mode\"). The application provides also a PHR mode for Pleiades images which does not use sensor models as Pan and XS products are already coregistered but only estimate an affine transformation to superimpose XS over the Pan.Note that this option is automatically activated in case Pleiades images are detected as input.");
SetDocLimitations("None");
SetDocAuthors("OTB-Team");
SetDocSeeAlso(" ");
AddDocTag(Tags::Geometry);
AddDocTag(Tags::Pansharpening);
AddApplication("Superimpose", "superimpose", "Reproject XS onto Pan");
AddApplication("Pansharpening", "pansharp", "Fusion of XS and Pan");
ShareParameter("inp","superimpose.inr","Input PAN Image","Input panchromatic image.");
ShareParameter("inxs","superimpose.inm","Input XS Image","Input XS image.");
ShareParameter("out","pansharp.out");
ShareParameter("elev","superimpose.elev");
ShareParameter("mode","superimpose.mode");
ShareParameter("lms","superimpose.lms",
"Spacing of the deformation field",
"Spacing of the deformation field. Default is 10 times the PAN image spacing.");
ShareParameter("ram","superimpose.ram");
Connect("pansharp.inp","superimpose.inr");
Connect("pansharp.ram","superimpose.ram");
GetInternalApplication("superimpose")->SetParameterString("interpolator","bco");
GetInternalApplication("pansharp")->SetParameterString("method","rcs");
// Doc example parameter settings
SetDocExampleParameterValue("inp", "QB_Toulouse_Ortho_PAN.tif");
SetDocExampleParameterValue("inxs", "QB_Toulouse_Ortho_XS.tif");
SetDocExampleParameterValue("out", "BundleToPerfectSensor.png uchar");
}
void DoUpdateParameters() ITK_OVERRIDE
{
UpdateInternalParameters("superimpose");
}
void DoExecute() ITK_OVERRIDE
{
ExecuteInternal("superimpose");
GetInternalApplication("pansharp")->SetParameterInputImage("inxs",
GetInternalApplication("superimpose")->GetParameterOutputImage("out"));
ExecuteInternal("pansharp");
}
};
}
}
OTB_APPLICATION_EXPORT(otb::Wrapper::BundleToPerfectSensor)
<|endoftext|>
|
<commit_before>#include <DataFrame/FixedSizeString.h>
#include <DataFrame/MMap/ObjectVector.h>
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <vector>
#include <time.h>
#include <strings.h>
using namespace std;
using namespace hmdf;
// ----------------------------------------------------------------------------
class data_class {
public:
typedef unsigned int size_type;
typedef time_t time_type;
inline data_class () : counter (0) { name [0] = 0; }
inline data_class (const data_class &that) { *this = that; }
inline data_class &operator = (const data_class &rhs) {
if (this != &rhs) {
strcpy (name, rhs.name);
counter = rhs.counter;
}
return (*this);
}
bool operator == (const data_class &rhs) const {
return (! strcmp (name, rhs.name) && counter == rhs.counter);
}
void print () const { cout << "\tcounter = " << counter << endl; }
char name [64];
int counter;
};
// ----------------------------------------------------------------------------
static bool operator < (const data_class &lhs, const data_class &rhs) {
return (lhs.counter < rhs.counter);
}
// ----------------------------------------------------------------------------
#ifndef _WIN32
typedef MMapVector<data_class> MyObjBase;
static const size_t ITER_COUNT = 1000;
static const char *OBJECT_BASE_NAME = "./testfile";
#endif // _WIN32
// ----------------------------------------------------------------------------
int main (int argc, char *argv []) {
#ifndef _WIN32
cout.precision (20);
MyObjBase write_objbase (OBJECT_BASE_NAME);
write_objbase.reserve (ITER_COUNT * 2);
for (size_t i = 0; i < ITER_COUNT; ++i) {
FixedSizeString<63> str;
str.printf ("the number is %d", i);
data_class dc;
strcpy (dc.name, str.c_str ());
dc.counter = i;
write_objbase.push_back (dc);
if (i % 1000 == 0)
cout << "Inserted record number " << i << endl;
}
cout << "Inserted total of " << write_objbase.size ()
<< " records\n" << endl;
MyObjBase appd_object (OBJECT_BASE_NAME);
cout << "Erasing 100 - 900\n" << endl;
const MyObjBase::iterator eiter =
appd_object.erase (appd_object.begin() + 100,
appd_object.begin() + 900 + 1);
cout << "After erasing, we have " << appd_object.size ()
<< " objects left" << endl;
if (eiter == appd_object.end ())
cout << "Return iterator is the end iterator" << endl;
else
cout << "Return iterator is " << eiter->counter << endl;
size_t counter = 0;
for (MyObjBase::const_iterator citer = appd_object.begin ();
citer != appd_object.end (); ++citer)
if (++counter % 100 == 0)
citer->print ();
cout << endl;
cout << "Erasing 5\n" << endl;
const MyObjBase::iterator eiter2 =
appd_object.erase (appd_object.begin() + 5);
cout << "After erasing, we have " << appd_object.size ()
<< " objects left" << endl;
if (eiter2 == appd_object.end ())
cout << "Return iterator is the end iterator" << endl;
else
cout << "Return iterator is " << eiter2->counter << endl;
counter = 0;
for (MyObjBase::const_iterator citer = appd_object.begin ();
citer != appd_object.end (); ++citer)
if (++counter % 100 == 0)
citer->print ();
cout << endl;
cout << "Inserting 5\n" << endl;
data_class dc;
dc.counter = 5;
appd_object.insert (appd_object.begin() + 5, dc);
counter = 0;
for (MyObjBase::const_iterator citer = appd_object.begin ();
citer != appd_object.end (); ++citer)
if (++counter % 100 == 0)
citer->print ();
cout << endl;
cout << "Inserting -1\n" << endl;
dc.counter = -1;
appd_object.insert (appd_object.begin(), dc);
counter = 0;
for (MyObjBase::const_iterator citer = appd_object.begin ();
citer != appd_object.end (); ++citer)
if (++counter % 100 == 0)
citer->print ();
cout << endl;
cout << "Inserting 1000\n" << endl;
dc.counter = 1000;
appd_object.insert (appd_object.end(), dc);
counter = 0;
for (MyObjBase::const_iterator citer = appd_object.begin ();
citer != appd_object.end (); ++citer)
if (++counter % 100 == 0)
citer->print ();
cout << endl;
#endif // _WIN32
return (EXIT_SUCCESS);
}
// ----------------------------------------------------------------------------
// Local Variables:
// mode:C++
// tab-width:4
// c-basic-offset:4
// End:
<commit_msg>Windows compliation<commit_after>#include <DataFrame/FixedSizeString.h>
#include <DataFrame/MMap/ObjectVector.h>
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <vector>
#include <time.h>
using namespace std;
using namespace hmdf;
// ----------------------------------------------------------------------------
class data_class {
public:
typedef unsigned int size_type;
typedef time_t time_type;
inline data_class () : counter (0) { name [0] = 0; }
inline data_class (const data_class &that) { *this = that; }
inline data_class &operator = (const data_class &rhs) {
if (this != &rhs) {
strcpy (name, rhs.name);
counter = rhs.counter;
}
return (*this);
}
bool operator == (const data_class &rhs) const {
return (! strcmp (name, rhs.name) && counter == rhs.counter);
}
void print () const { cout << "\tcounter = " << counter << endl; }
char name [64];
int counter;
};
// ----------------------------------------------------------------------------
static bool operator < (const data_class &lhs, const data_class &rhs) {
return (lhs.counter < rhs.counter);
}
// ----------------------------------------------------------------------------
#ifndef _WIN32
typedef MMapVector<data_class> MyObjBase;
static const size_t ITER_COUNT = 1000;
static const char *OBJECT_BASE_NAME = "./testfile";
#endif // _WIN32
// ----------------------------------------------------------------------------
int main (int argc, char *argv []) {
#ifndef _WIN32
cout.precision (20);
MyObjBase write_objbase (OBJECT_BASE_NAME);
write_objbase.reserve (ITER_COUNT * 2);
for (size_t i = 0; i < ITER_COUNT; ++i) {
FixedSizeString<63> str;
str.printf ("the number is %d", i);
data_class dc;
strcpy (dc.name, str.c_str ());
dc.counter = i;
write_objbase.push_back (dc);
if (i % 1000 == 0)
cout << "Inserted record number " << i << endl;
}
cout << "Inserted total of " << write_objbase.size ()
<< " records\n" << endl;
MyObjBase appd_object (OBJECT_BASE_NAME);
cout << "Erasing 100 - 900\n" << endl;
const MyObjBase::iterator eiter =
appd_object.erase (appd_object.begin() + 100,
appd_object.begin() + 900 + 1);
cout << "After erasing, we have " << appd_object.size ()
<< " objects left" << endl;
if (eiter == appd_object.end ())
cout << "Return iterator is the end iterator" << endl;
else
cout << "Return iterator is " << eiter->counter << endl;
size_t counter = 0;
for (MyObjBase::const_iterator citer = appd_object.begin ();
citer != appd_object.end (); ++citer)
if (++counter % 100 == 0)
citer->print ();
cout << endl;
cout << "Erasing 5\n" << endl;
const MyObjBase::iterator eiter2 =
appd_object.erase (appd_object.begin() + 5);
cout << "After erasing, we have " << appd_object.size ()
<< " objects left" << endl;
if (eiter2 == appd_object.end ())
cout << "Return iterator is the end iterator" << endl;
else
cout << "Return iterator is " << eiter2->counter << endl;
counter = 0;
for (MyObjBase::const_iterator citer = appd_object.begin ();
citer != appd_object.end (); ++citer)
if (++counter % 100 == 0)
citer->print ();
cout << endl;
cout << "Inserting 5\n" << endl;
data_class dc;
dc.counter = 5;
appd_object.insert (appd_object.begin() + 5, dc);
counter = 0;
for (MyObjBase::const_iterator citer = appd_object.begin ();
citer != appd_object.end (); ++citer)
if (++counter % 100 == 0)
citer->print ();
cout << endl;
cout << "Inserting -1\n" << endl;
dc.counter = -1;
appd_object.insert (appd_object.begin(), dc);
counter = 0;
for (MyObjBase::const_iterator citer = appd_object.begin ();
citer != appd_object.end (); ++citer)
if (++counter % 100 == 0)
citer->print ();
cout << endl;
cout << "Inserting 1000\n" << endl;
dc.counter = 1000;
appd_object.insert (appd_object.end(), dc);
counter = 0;
for (MyObjBase::const_iterator citer = appd_object.begin ();
citer != appd_object.end (); ++citer)
if (++counter % 100 == 0)
citer->print ();
cout << endl;
#endif // _WIN32
return (EXIT_SUCCESS);
}
// ----------------------------------------------------------------------------
// Local Variables:
// mode:C++
// tab-width:4
// c-basic-offset:4
// End:
<|endoftext|>
|
<commit_before>#include <gtest/gtest.h>
// PUBLIC API
#include <disir/disir.h>
#include "test_helper.h"
// Test mold API with empty mold.
class ContextSectionTest : public testing::DisirTestWrapper
{
void SetUp()
{
DisirLogCurrentTestEnter ();
context = NULL;
context_mold = NULL;
context_keyval = NULL;
context_section = NULL;
status = dc_mold_begin (&context_mold);
ASSERT_STATUS (DISIR_STATUS_OK, status);
status = dc_begin (context_mold, DISIR_CONTEXT_SECTION, &context_section);
ASSERT_STATUS (DISIR_STATUS_OK, status);
}
void TearDown()
{
if (context)
{
status = dc_destroy (&context);
EXPECT_STATUS (DISIR_STATUS_OK, status);
}
if (context_mold)
{
status = dc_destroy (&context_mold);
EXPECT_STATUS (DISIR_STATUS_OK, status);
}
if (context_keyval)
{
status = dc_destroy (&context_keyval);
EXPECT_STATUS (DISIR_STATUS_OK, status);
}
DisirLogCurrentTestExit ();
}
public:
enum disir_status status;
struct disir_context *context;
struct disir_context *context_mold;
struct disir_context *context_section;
struct disir_context *context_keyval;
};
TEST_F (ContextSectionTest, context_type)
{
ASSERT_EQ (DISIR_CONTEXT_SECTION, dc_context_type (context_section));
}
TEST_F (ContextSectionTest, context_type_string)
{
ASSERT_STREQ ("SECTION", dc_context_type_string (context_section));
}
TEST_F (ContextSectionTest, finalizing_without_name_shall_fail)
{
status = dc_finalize (&context_section);
EXPECT_STATUS (DISIR_STATUS_INVALID_CONTEXT, status);
EXPECT_STREQ ("Missing name component for section.", dc_context_error (context_section));
}
TEST_F (ContextSectionTest, set_name_on_mold)
{
status = dc_set_name (context_section, "test_name", strlen ("test_name"));
EXPECT_STATUS (DISIR_STATUS_OK, status);
}
<commit_msg>test: section - free context in teardown<commit_after>#include <gtest/gtest.h>
// PUBLIC API
#include <disir/disir.h>
#include "test_helper.h"
// Test mold API with empty mold.
class ContextSectionTest : public testing::DisirTestWrapper
{
void SetUp()
{
DisirLogCurrentTestEnter ();
context = NULL;
context_mold = NULL;
context_keyval = NULL;
context_section = NULL;
status = dc_mold_begin (&context_mold);
ASSERT_STATUS (DISIR_STATUS_OK, status);
status = dc_begin (context_mold, DISIR_CONTEXT_SECTION, &context_section);
ASSERT_STATUS (DISIR_STATUS_OK, status);
}
void TearDown()
{
if (context)
{
status = dc_destroy (&context);
EXPECT_STATUS (DISIR_STATUS_OK, status);
}
if (context_mold)
{
status = dc_destroy (&context_mold);
EXPECT_STATUS (DISIR_STATUS_OK, status);
}
if (context_keyval)
{
status = dc_destroy (&context_keyval);
EXPECT_STATUS (DISIR_STATUS_OK, status);
}
if (context_section)
{
status = dc_destroy (&context_section);
EXPECT_STATUS (DISIR_STATUS_OK, status);
}
DisirLogCurrentTestExit ();
}
public:
enum disir_status status;
struct disir_context *context;
struct disir_context *context_mold;
struct disir_context *context_section;
struct disir_context *context_keyval;
};
TEST_F (ContextSectionTest, context_type)
{
ASSERT_EQ (DISIR_CONTEXT_SECTION, dc_context_type (context_section));
}
TEST_F (ContextSectionTest, context_type_string)
{
ASSERT_STREQ ("SECTION", dc_context_type_string (context_section));
}
TEST_F (ContextSectionTest, finalizing_without_name_shall_fail)
{
status = dc_finalize (&context_section);
EXPECT_STATUS (DISIR_STATUS_INVALID_CONTEXT, status);
EXPECT_STREQ ("Missing name component for section.", dc_context_error (context_section));
}
TEST_F (ContextSectionTest, set_name_on_mold)
{
status = dc_set_name (context_section, "test_name", strlen ("test_name"));
EXPECT_STATUS (DISIR_STATUS_OK, status);
}
<|endoftext|>
|
<commit_before>// runV0ChCorrelations.C
//
// AddTask for AliAnalysisTaskV0ChCorrelations task
//
AliAnalysisTaskV0ChCorrelations *AddTaskV0ChCorrelations(const char * outfilename,
const Bool_t bMCtruth=kFALSE,
Float_t DcaDToPV = 0.5,
Float_t DcaV0D = 0.1
)
{
// Creates a V0Ch correlations analysis task and adds it to the analysis manager.
// Get the pointer to the existing analysis manager via the static access method.
//==============================================================================
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
::Error("AddTaskV0ChCorrelations", "No analysis manager to connect to.");
return NULL;
}
// mc event handlerrunEx01.C
if(bMCtruth) {
AliMCEventHandler* mchandler = new AliMCEventHandler();
// Not reading track references
mchandler->SetReadTR(kFALSE);
mgr->SetMCtruthEventHandler(mchandler);
}
// create task
AliAnalysisTaskV0ChCorrelations* task = new AliAnalysisTaskV0ChCorrelations("V0ChCorrelations_task");
task->SetDcaDToPV(DcaDToPV);
task->SetDcaV0D(DcaV0D);
mgr->AddTask(task);
// Create ONLY the output containers for the data produced by the task.
// Get and connect other common input/output containers via the manager as below
//==============================================================================
TString outputFileName = AliAnalysisManager::GetCommonFileName();
outputFileName = "list.grid.v0ch.root";
// create containers for input/output
AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer();
AliAnalysisDataContainer *coutput1 = mgr->CreateContainer(outfilename, TList::Class(), AliAnalysisManager::kOutputContainer, outputFileName);
// connect input/output
mgr->ConnectInput(task, 0, cinput);
mgr->ConnectOutput(task, 1, coutput1);
// Return task pointer at the end
return task;
}
<commit_msg><commit_after>// runV0ChCorrelations.C
//
// AddTask for AliAnalysisTaskV0ChCorrelations task
//
AliAnalysisTaskV0ChCorrelations *AddTaskV0ChCorrelations(const Bool_t bMCtruth=kTRUE,
Float_t DcaDToPV = 0.5,
Float_t DcaV0D = 0.1
)
{
// Creates a V0Ch correlations analysis task and adds it to the analysis manager.
// Get the pointer to the existing analysis manager via the static access method.
//==============================================================================
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
::Error("AddTaskV0ChCorrelations", "No analysis manager to connect to.");
return NULL;
}
// mc event handlerrunEx01.C
/*
if(bMCtruth) {
cout << "I am here too! " << endl;
AliAODMCEventHandler* mchandler = new AliAODMCEventHandler();
// Not reading track references
mchandler->SetReadTR(kFALSE);
mgr->SetMCtruthEventHandler(mchandler);
}
*/
// create task
AliAnalysisTaskV0ChCorrelations* task = new AliAnalysisTaskV0ChCorrelations("V0ChCorrelations_task");
task->SetAnalysisMC(bMCtruth);
task->SetDcaDToPV(DcaDToPV);
task->SetDcaV0D(DcaV0D);
mgr->AddTask(task);
// Create ONLY the output containers for the data produced by the task.
// Get and connect other common input/output containers via the manager as below
//==============================================================================
TString outputFileName = AliAnalysisManager::GetCommonFileName();
//outputFileName = "list.grid.v0ch.root";
// create containers for input/output
AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer();
AliAnalysisDataContainer *coutput1 = mgr->CreateContainer("coutput1", TList::Class(), AliAnalysisManager::kOutputContainer, outputFileName);
// connect input/output
mgr->ConnectInput(task, 0, cinput);
mgr->ConnectOutput(task, 1, coutput1);
// Return task pointer at the end
return task;
}
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkGDCMImageIO.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
Portions of this code are covered under the VTK copyright.
See VTKCopyright.txt or http://www.kitware.com/VTKCopyright.htm 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 "itkGDCMImageIO.h"
#include "itkMetaDataObject.h"
#include "gdcm/src/gdcmValEntry.h" //internal of gdcm
#include "gdcm/src/gdcmFile.h"
#include "gdcm/src/gdcmHeader.h"
#include <fstream>
namespace itk
{
GDCMImageIO::GDCMImageIO()
{
this->SetNumberOfDimensions(3); //needed for getting the 3 coordinates of
// the origin, even if it is a 2D slice.
m_ByteOrder = LittleEndian; //default
m_FileType = Binary; //default...always true
m_RescaleSlope = 1.0;
m_RescaleIntercept = 0.0;
#if GDCM_MAJOR_VERSION == 0 && GDCM_MINOR_VERSION <= 5
m_GdcmHeader = NULL;
#endif
}
GDCMImageIO::~GDCMImageIO()
{
#if GDCM_MAJOR_VERSION == 0 && GDCM_MINOR_VERSION <= 5
delete m_GdcmHeader;
#endif
}
bool GDCMImageIO::OpenGDCMFileForReading(std::ifstream& os,
const char* filename)
{
// Make sure that we have a file to
if ( filename == "" )
{
itkExceptionMacro(<<"A FileName must be specified.");
return false;
}
// Close file from any previous image
if ( os.is_open() )
{
os.close();
}
// Open the new file for reading
itkDebugMacro(<< "Initialize: opening file " << filename);
// Actually open the file
os.open( filename, std::ios::in | std::ios::binary );
if ( os.fail() )
{
return false;
}
return true;
}
bool GDCMImageIO::OpenGDCMFileForWriting(std::ofstream& os,
const char* filename)
{
// Make sure that we have a file to
if ( filename == "" )
{
itkExceptionMacro(<<"A FileName must be specified.");
return false;
}
// Close file from any previous image
if ( os.is_open() )
{
os.close();
}
// Open the new file for writing
itkDebugMacro(<< "Initialize: opening file " << filename);
#ifdef __sgi
// Create the file. This is required on some older sgi's
std::ofstream tFile(filename,std::ios::out);
tFile.close();
#endif
// Actually open the file
os.open( filename, std::ios::out | std::ios::binary );
if( os.fail() )
{
itkExceptionMacro(<< "Could not open file for writing: " << filename);
return false;
}
return true;
}
// This method will only test if the header looks like a
// GDCM image file.
bool GDCMImageIO::CanReadFile(const char* filename)
{
std::ifstream file;
std::string fname(filename);
if( fname == "" )
{
itkDebugMacro(<<"No filename specified.");
return false;
}
bool extensionFound = false;
std::string::size_type sprPos = fname.rfind(".dcm"); //acr nema ??
if ((sprPos != std::string::npos)
&& (sprPos == fname.length() - 4))
{
extensionFound = true;
}
if( !extensionFound )
{
itkDebugMacro(<<"The filename extension is not recognized");
return false;
}
//Check for file existence:
if ( ! this->OpenGDCMFileForReading(file, filename))
{
return false;
}
// Check to see if its a valid dicom file gdcm is able to parse:
//We are parsing the header one time here:
#if GDCM_MAJOR_VERSION == 0 && GDCM_MINOR_VERSION <= 5
gdcmHeader GdcmHeader( fname );
#else
gdcm::Header GdcmHeader( fname );
#endif
if (!GdcmHeader.IsReadable())
{
itkExceptionMacro("Gdcm cannot parse file " << filename );
return false;
}
return true;
}
void GDCMImageIO::Read(void* buffer)
{
std::ifstream file;
//read header information file:
this->InternalReadImageInformation(file);
//Should I handle differently dicom lut ?
//GdcmHeader.HasLUT()
#if GDCM_MAJOR_VERSION == 0 && GDCM_MINOR_VERSION <= 5
if( !m_GdcmHeader )
{
m_GdcmHeader = new gdcmHeader( m_FileName );
}
#endif
#if GDCM_MAJOR_VERSION == 0 && GDCM_MINOR_VERSION <= 5
gdcmFile GdcmFile( m_FileName );
#else
gdcm::File GdcmFile( m_FileName );
#endif
size_t size = GdcmFile.GetImageDataSize();
//== this->GetImageSizeInComponents()
unsigned char *Source = (unsigned char*)GdcmFile.GetImageData();
memcpy(buffer, (void*)Source, size);
delete[] Source;
//closing files:
file.close();
}
void GDCMImageIO::InternalReadImageInformation(std::ifstream& file)
{
//read header
if ( ! this->OpenGDCMFileForReading(file, m_FileName.c_str()) )
{
itkExceptionMacro(<< "Cannot read requested file");
}
#if GDCM_MAJOR_VERSION == 0 && GDCM_MINOR_VERSION <= 5
gdcmHeader GdcmHeader( m_FileName );
#else
gdcm::Header GdcmHeader( m_FileName );
#endif
// We don't need to positionate the Endian related stuff (by using
// this->SetDataByteOrderToBigEndian() or SetDataByteOrderToLittleEndian()
// since the reading of the file is done by gdcm.
// But we do need to set up the data type for downstream filters:
std::string type = GdcmHeader.GetPixelType();
if( type == "8U")
{
SetPixelType(SCALAR);
SetComponentType(UCHAR);
}
else if( type == "8S")
{
SetPixelType(SCALAR);
SetComponentType(CHAR);
}
else if( type == "16U")
{
SetPixelType(SCALAR);
SetComponentType(USHORT);
}
else if( type == "16S")
{
SetPixelType(SCALAR);
SetComponentType(SHORT);
}
else if( type == "32U")
{
SetPixelType(SCALAR);
SetComponentType(UINT);
}
else if( type == "32S")
{
SetPixelType(SCALAR);
SetComponentType(INT);
}
else if ( type == "FD" )
{
//64 bits Double image
SetPixelType(SCALAR);
SetComponentType(DOUBLE);
}
else
{
itkExceptionMacro(<<"Unrecognized type:" << type << " in file " << m_FileName);
}
// set values in case we don't find them
m_Dimensions[0] = GdcmHeader.GetXSize();
m_Dimensions[1] = GdcmHeader.GetYSize();
m_Dimensions[2] = GdcmHeader.GetZSize();
m_Spacing[0] = GdcmHeader.GetXSpacing();
m_Spacing[1] = GdcmHeader.GetYSpacing();
m_Spacing[2] = GdcmHeader.GetZSpacing();
m_Origin[0] = GdcmHeader.GetXOrigin();
m_Origin[1] = GdcmHeader.GetYOrigin();
m_Origin[2] = GdcmHeader.GetZOrigin();
//For grayscale image :
m_RescaleSlope = GdcmHeader.GetRescaleSlope();
m_RescaleIntercept = GdcmHeader.GetRescaleIntercept();
//Now copying the gdcm dictionary to the itk dictionary:
MetaDataDictionary & dico = this->GetMetaDataDictionary();
#if GDCM_MAJOR_VERSION == 0 && GDCM_MINOR_VERSION <= 5
TagDocEntryHT & nameHt = GdcmHeader.GetEntry();
for (TagDocEntryHT::iterator tag = nameHt.begin(); tag != nameHt.end(); ++tag)
#else
const gdcm::TagDocEntryHT &nameHt = GdcmHeader.GetTagHT();
for (gdcm::TagDocEntryHT::const_iterator tag = nameHt.begin(); tag != nameHt.end(); ++tag)
#endif
{
// Do not copy field from private (unknown) dictionary.
// In the longer term we might want to (but we need the Private dictionary
// from manufacturer)
if (tag->second->GetVR().find("SQ") == 0)
{
// skip DICOM SeQuence, otherwise following cast will crash
continue;
}
#if GDCM_MAJOR_VERSION == 0 && GDCM_MINOR_VERSION <= 5
std::string temp = ((gdcmValEntry*)(tag->second))->GetValue();
#else
std::string temp = ((gdcm::ValEntry*)(tag->second))->GetValue();
#endif
if( tag->second->GetName() != "unkn"
&& temp.find( "gdcm::NotLoaded" ) != 0
&& temp.find( "gdcm::Loaded" ) != 0 )
{
EncapsulateMetaData<std::string>(dico, tag->second->GetName(),
#if GDCM_MAJOR_VERSION == 0 && GDCM_MINOR_VERSION <= 5
((gdcmValEntry*)(tag->second))->GetValue() );
#else
((gdcm::ValEntry*)(tag->second))->GetValue() );
#endif
}
}
}
void GDCMImageIO::ReadImageInformation()
{
std::ifstream file;
this->InternalReadImageInformation(file);
}
bool GDCMImageIO::CanWriteFile(const char* name)
{
std::string filename = name;
if( filename == "" )
{
itkDebugMacro(<<"No filename specified.");
return false;
}
bool extensionFound = false;
std::string::size_type sprPos = filename.rfind(".dcm");
if ((sprPos != std::string::npos)
&& (sprPos == filename.length() - 4))
{
extensionFound = true;
}
if( !extensionFound )
{
itkDebugMacro(<<"The filename extension is not recognized");
return false;
}
return true;
}
void GDCMImageIO::WriteImageInformation()
{
}
void GDCMImageIO::Write(const void* buffer)
{
std::ofstream file;
if ( !this->OpenGDCMFileForWriting(file, m_FileName.c_str()) )
{
return;
}
file.close();
const unsigned long numberOfBytes = this->GetImageSizeInBytes();
#if GDCM_MAJOR_VERSION == 0 && GDCM_MINOR_VERSION <= 5
gdcmFile *myGdcmFile = new gdcmFile( m_GdcmHeader );
myGdcmFile->GetImageData(); //API problem
m_GdcmHeader->SetEntryVoidAreaByNumber( (void*)buffer,
m_GdcmHeader->GetGrPixel(), m_GdcmHeader->GetNumPixel()); //Another API problem
myGdcmFile->SetImageData((void*)buffer, numberOfBytes );
myGdcmFile->WriteDcmExplVR( m_FileName );
delete myGdcmFile;
#else
gdcm::Header *myGdcmHeader = new gdcm::Header();
gdcm::File *myGdcmFile = new gdcm::File( myGdcmHeader );
MetaDataDictionary & dict = this->GetMetaDataDictionary();
// Using real iterators (instead of the GetKeys() method)
itk::MetaDataDictionary::ConstIterator itr = dict.Begin();
itk::MetaDataDictionary::ConstIterator end = dict.End();
std::string value;
while( itr != end )
{
const std::string &key = itr->first; //Needed for bcc32
ExposeMetaData<std::string>(dict, key, value);
// Convert DICOM name to DICOM (group,element)
#if GDCM_MAJOR_VERSION == 0 && GDCM_MINOR_VERSION <= 5
gdcmDictEntry *dictEntry =
#else
gdcm::DictEntry *dictEntry =
#endif
myGdcmHeader->GetPubDict()->GetDictEntryByName(itr->first);
// Anything that has been change in the MetaData Dict will be pushed
// into the DICOM header:
myGdcmHeader->ReplaceOrCreateByNumber( value, dictEntry->GetGroup(),
dictEntry->GetElement());
++itr;
}
// Handle the bitDepth:
std::string bitsAllocated;
std::string bitsStored;
std::string highBit;
std::string pixelRep;
switch (this->GetComponentType())
{
case CHAR:
bitsAllocated = "8"; // Bits Allocated
bitsStored = "8"; // Bits Stored
highBit = "7"; // High Bit
// 8bits DICOM cannot be signed
pixelRep = "0"; //Pixel Representation
break;
case UCHAR:
bitsAllocated = "8"; // Bits Allocated
bitsStored = "8"; // Bits Stored
highBit = "7"; // High Bit
pixelRep = "0"; //Pixel Representation
break;
case SHORT:
bitsAllocated = "16"; // Bits Allocated
bitsStored = "16"; // Bits Stored
highBit = "15"; // High Bit
pixelRep = "1"; //Pixel Representation
break;
case USHORT:
bitsAllocated = "16"; // Bits Allocated
bitsStored = "16"; // Bits Stored
highBit = "15"; // High Bit
pixelRep = "0"; //Pixel Representation
break;
default:
itkExceptionMacro(<<"DICOM does not support this component type");
}
// Write component specific information in the header:
myGdcmHeader->ReplaceOrCreateByNumber( bitsAllocated, 0x0028, 0x0100 ); //Bits Allocated
myGdcmHeader->ReplaceOrCreateByNumber( bitsStored, 0x0028, 0x0101 ); //Bits Stored
myGdcmHeader->ReplaceOrCreateByNumber( highBit, 0x0028, 0x0102 ); //High Bit
myGdcmHeader->ReplaceOrCreateByNumber( pixelRep, 0x0028, 0x0103 ); //Pixel Representation
//copy data from buffer to DICOM buffer
// The current gdcm API does not allow anything fancy, you have to go lower level
uint8_t* imageData = (uint8_t*)buffer;
// Here we are passsing directly a pointer, this should
myGdcmHeader->ReplaceOrCreateByNumber( imageData, numberOfBytes, 0x7fe0, 0x0010, "PXL" );
myGdcmFile->WriteDcmExplVR( m_FileName );
delete myGdcmFile;
delete myGdcmHeader;
#endif
}
void GDCMImageIO::PrintSelf(std::ostream& os, Indent indent) const
{
Superclass::PrintSelf(os, indent);
os << indent << "RescaleSlope: " << m_RescaleSlope << "\n";
os << indent << "RescaleIntercept: " << m_RescaleIntercept << "\n";
}
} // end namespace itk
<commit_msg>ENH: Can not copy binary field for now.<commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkGDCMImageIO.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
Portions of this code are covered under the VTK copyright.
See VTKCopyright.txt or http://www.kitware.com/VTKCopyright.htm 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 "itkGDCMImageIO.h"
#include "itkMetaDataObject.h"
#include "gdcm/src/gdcmValEntry.h" //internal of gdcm
#include "gdcm/src/gdcmFile.h"
#include "gdcm/src/gdcmHeader.h"
#include <fstream>
namespace itk
{
GDCMImageIO::GDCMImageIO()
{
this->SetNumberOfDimensions(3); //needed for getting the 3 coordinates of
// the origin, even if it is a 2D slice.
m_ByteOrder = LittleEndian; //default
m_FileType = Binary; //default...always true
m_RescaleSlope = 1.0;
m_RescaleIntercept = 0.0;
#if GDCM_MAJOR_VERSION == 0 && GDCM_MINOR_VERSION <= 5
m_GdcmHeader = NULL;
#endif
}
GDCMImageIO::~GDCMImageIO()
{
#if GDCM_MAJOR_VERSION == 0 && GDCM_MINOR_VERSION <= 5
delete m_GdcmHeader;
#endif
}
bool GDCMImageIO::OpenGDCMFileForReading(std::ifstream& os,
const char* filename)
{
// Make sure that we have a file to
if ( filename == "" )
{
itkExceptionMacro(<<"A FileName must be specified.");
return false;
}
// Close file from any previous image
if ( os.is_open() )
{
os.close();
}
// Open the new file for reading
itkDebugMacro(<< "Initialize: opening file " << filename);
// Actually open the file
os.open( filename, std::ios::in | std::ios::binary );
if ( os.fail() )
{
return false;
}
return true;
}
bool GDCMImageIO::OpenGDCMFileForWriting(std::ofstream& os,
const char* filename)
{
// Make sure that we have a file to
if ( filename == "" )
{
itkExceptionMacro(<<"A FileName must be specified.");
return false;
}
// Close file from any previous image
if ( os.is_open() )
{
os.close();
}
// Open the new file for writing
itkDebugMacro(<< "Initialize: opening file " << filename);
#ifdef __sgi
// Create the file. This is required on some older sgi's
std::ofstream tFile(filename,std::ios::out);
tFile.close();
#endif
// Actually open the file
os.open( filename, std::ios::out | std::ios::binary );
if( os.fail() )
{
itkExceptionMacro(<< "Could not open file for writing: " << filename);
return false;
}
return true;
}
// This method will only test if the header looks like a
// GDCM image file.
bool GDCMImageIO::CanReadFile(const char* filename)
{
std::ifstream file;
std::string fname(filename);
if( fname == "" )
{
itkDebugMacro(<<"No filename specified.");
return false;
}
bool extensionFound = false;
std::string::size_type sprPos = fname.rfind(".dcm"); //acr nema ??
if ((sprPos != std::string::npos)
&& (sprPos == fname.length() - 4))
{
extensionFound = true;
}
if( !extensionFound )
{
itkDebugMacro(<<"The filename extension is not recognized");
return false;
}
//Check for file existence:
if ( ! this->OpenGDCMFileForReading(file, filename))
{
return false;
}
// Check to see if its a valid dicom file gdcm is able to parse:
//We are parsing the header one time here:
#if GDCM_MAJOR_VERSION == 0 && GDCM_MINOR_VERSION <= 5
gdcmHeader GdcmHeader( fname );
#else
gdcm::Header GdcmHeader( fname );
#endif
if (!GdcmHeader.IsReadable())
{
itkExceptionMacro("Gdcm cannot parse file " << filename );
return false;
}
return true;
}
void GDCMImageIO::Read(void* buffer)
{
std::ifstream file;
//read header information file:
this->InternalReadImageInformation(file);
//Should I handle differently dicom lut ?
//GdcmHeader.HasLUT()
#if GDCM_MAJOR_VERSION == 0 && GDCM_MINOR_VERSION <= 5
if( !m_GdcmHeader )
{
m_GdcmHeader = new gdcmHeader( m_FileName );
}
#endif
#if GDCM_MAJOR_VERSION == 0 && GDCM_MINOR_VERSION <= 5
gdcmFile GdcmFile( m_FileName );
#else
gdcm::File GdcmFile( m_FileName );
#endif
size_t size = GdcmFile.GetImageDataSize();
//== this->GetImageSizeInComponents()
unsigned char *Source = (unsigned char*)GdcmFile.GetImageData();
memcpy(buffer, (void*)Source, size);
delete[] Source;
//closing files:
file.close();
}
void GDCMImageIO::InternalReadImageInformation(std::ifstream& file)
{
//read header
if ( ! this->OpenGDCMFileForReading(file, m_FileName.c_str()) )
{
itkExceptionMacro(<< "Cannot read requested file");
}
#if GDCM_MAJOR_VERSION == 0 && GDCM_MINOR_VERSION <= 5
gdcmHeader GdcmHeader( m_FileName );
#else
gdcm::Header GdcmHeader( m_FileName );
#endif
// We don't need to positionate the Endian related stuff (by using
// this->SetDataByteOrderToBigEndian() or SetDataByteOrderToLittleEndian()
// since the reading of the file is done by gdcm.
// But we do need to set up the data type for downstream filters:
std::string type = GdcmHeader.GetPixelType();
if( type == "8U")
{
SetPixelType(SCALAR);
SetComponentType(UCHAR);
}
else if( type == "8S")
{
SetPixelType(SCALAR);
SetComponentType(CHAR);
}
else if( type == "16U")
{
SetPixelType(SCALAR);
SetComponentType(USHORT);
}
else if( type == "16S")
{
SetPixelType(SCALAR);
SetComponentType(SHORT);
}
else if( type == "32U")
{
SetPixelType(SCALAR);
SetComponentType(UINT);
}
else if( type == "32S")
{
SetPixelType(SCALAR);
SetComponentType(INT);
}
else if ( type == "FD" )
{
//64 bits Double image
SetPixelType(SCALAR);
SetComponentType(DOUBLE);
}
else
{
itkExceptionMacro(<<"Unrecognized type:" << type << " in file " << m_FileName);
}
// set values in case we don't find them
m_Dimensions[0] = GdcmHeader.GetXSize();
m_Dimensions[1] = GdcmHeader.GetYSize();
m_Dimensions[2] = GdcmHeader.GetZSize();
m_Spacing[0] = GdcmHeader.GetXSpacing();
m_Spacing[1] = GdcmHeader.GetYSpacing();
m_Spacing[2] = GdcmHeader.GetZSpacing();
m_Origin[0] = GdcmHeader.GetXOrigin();
m_Origin[1] = GdcmHeader.GetYOrigin();
m_Origin[2] = GdcmHeader.GetZOrigin();
//For grayscale image :
m_RescaleSlope = GdcmHeader.GetRescaleSlope();
m_RescaleIntercept = GdcmHeader.GetRescaleIntercept();
//Now copying the gdcm dictionary to the itk dictionary:
MetaDataDictionary & dico = this->GetMetaDataDictionary();
#if GDCM_MAJOR_VERSION == 0 && GDCM_MINOR_VERSION <= 5
TagDocEntryHT & nameHt = GdcmHeader.GetEntry();
for (TagDocEntryHT::iterator tag = nameHt.begin(); tag != nameHt.end(); ++tag)
#else
const gdcm::TagDocEntryHT &nameHt = GdcmHeader.GetTagHT();
for (gdcm::TagDocEntryHT::const_iterator tag = nameHt.begin(); tag != nameHt.end(); ++tag)
#endif
{
// Do not copy field from private (unknown) dictionary.
// In the longer term we might want to (but we need the Private dictionary
// from manufacturer)
if (tag->second->GetVR().find("SQ") == 0)
{
// skip DICOM SeQuence, otherwise following cast will crash
continue;
}
#if GDCM_MAJOR_VERSION == 0 && GDCM_MINOR_VERSION <= 5
std::string temp = ((gdcmValEntry*)(tag->second))->GetValue();
#else
std::string temp = ((gdcm::ValEntry*)(tag->second))->GetValue();
#endif
if( tag->second->GetName() != "unkn"
&& temp.find( "gdcm::NotLoaded" ) != 0
&& temp.find( "gdcm::Binary" ) != 0
&& temp.find( "gdcm::Loaded" ) != 0 )
{
EncapsulateMetaData<std::string>(dico, tag->second->GetName(),
#if GDCM_MAJOR_VERSION == 0 && GDCM_MINOR_VERSION <= 5
((gdcmValEntry*)(tag->second))->GetValue() );
#else
((gdcm::ValEntry*)(tag->second))->GetValue() );
#endif
}
}
}
void GDCMImageIO::ReadImageInformation()
{
std::ifstream file;
this->InternalReadImageInformation(file);
}
bool GDCMImageIO::CanWriteFile(const char* name)
{
std::string filename = name;
if( filename == "" )
{
itkDebugMacro(<<"No filename specified.");
return false;
}
bool extensionFound = false;
std::string::size_type sprPos = filename.rfind(".dcm");
if ((sprPos != std::string::npos)
&& (sprPos == filename.length() - 4))
{
extensionFound = true;
}
if( !extensionFound )
{
itkDebugMacro(<<"The filename extension is not recognized");
return false;
}
return true;
}
void GDCMImageIO::WriteImageInformation()
{
}
void GDCMImageIO::Write(const void* buffer)
{
std::ofstream file;
if ( !this->OpenGDCMFileForWriting(file, m_FileName.c_str()) )
{
return;
}
file.close();
const unsigned long numberOfBytes = this->GetImageSizeInBytes();
#if GDCM_MAJOR_VERSION == 0 && GDCM_MINOR_VERSION <= 5
gdcmFile *myGdcmFile = new gdcmFile( m_GdcmHeader );
myGdcmFile->GetImageData(); //API problem
m_GdcmHeader->SetEntryVoidAreaByNumber( (void*)buffer,
m_GdcmHeader->GetGrPixel(), m_GdcmHeader->GetNumPixel()); //Another API problem
myGdcmFile->SetImageData((void*)buffer, numberOfBytes );
myGdcmFile->WriteDcmExplVR( m_FileName );
delete myGdcmFile;
#else
gdcm::Header *myGdcmHeader = new gdcm::Header();
gdcm::File *myGdcmFile = new gdcm::File( myGdcmHeader );
MetaDataDictionary & dict = this->GetMetaDataDictionary();
// Using real iterators (instead of the GetKeys() method)
itk::MetaDataDictionary::ConstIterator itr = dict.Begin();
itk::MetaDataDictionary::ConstIterator end = dict.End();
std::string value;
while( itr != end )
{
const std::string &key = itr->first; //Needed for bcc32
ExposeMetaData<std::string>(dict, key, value);
// Convert DICOM name to DICOM (group,element)
#if GDCM_MAJOR_VERSION == 0 && GDCM_MINOR_VERSION <= 5
gdcmDictEntry *dictEntry =
#else
gdcm::DictEntry *dictEntry =
#endif
myGdcmHeader->GetPubDict()->GetDictEntryByName(itr->first);
// Anything that has been change in the MetaData Dict will be pushed
// into the DICOM header:
myGdcmHeader->ReplaceOrCreateByNumber( value, dictEntry->GetGroup(),
dictEntry->GetElement());
++itr;
}
// Handle the bitDepth:
std::string bitsAllocated;
std::string bitsStored;
std::string highBit;
std::string pixelRep;
switch (this->GetComponentType())
{
case CHAR:
bitsAllocated = "8"; // Bits Allocated
bitsStored = "8"; // Bits Stored
highBit = "7"; // High Bit
// 8bits DICOM cannot be signed
pixelRep = "0"; //Pixel Representation
break;
case UCHAR:
bitsAllocated = "8"; // Bits Allocated
bitsStored = "8"; // Bits Stored
highBit = "7"; // High Bit
pixelRep = "0"; //Pixel Representation
break;
case SHORT:
bitsAllocated = "16"; // Bits Allocated
bitsStored = "16"; // Bits Stored
highBit = "15"; // High Bit
pixelRep = "1"; //Pixel Representation
break;
case USHORT:
bitsAllocated = "16"; // Bits Allocated
bitsStored = "16"; // Bits Stored
highBit = "15"; // High Bit
pixelRep = "0"; //Pixel Representation
break;
default:
itkExceptionMacro(<<"DICOM does not support this component type");
}
// Write component specific information in the header:
myGdcmHeader->ReplaceOrCreateByNumber( bitsAllocated, 0x0028, 0x0100 ); //Bits Allocated
myGdcmHeader->ReplaceOrCreateByNumber( bitsStored, 0x0028, 0x0101 ); //Bits Stored
myGdcmHeader->ReplaceOrCreateByNumber( highBit, 0x0028, 0x0102 ); //High Bit
myGdcmHeader->ReplaceOrCreateByNumber( pixelRep, 0x0028, 0x0103 ); //Pixel Representation
//copy data from buffer to DICOM buffer
// The current gdcm API does not allow anything fancy, you have to go lower level
uint8_t* imageData = (uint8_t*)buffer;
// Here we are passsing directly a pointer, this should
myGdcmHeader->ReplaceOrCreateByNumber( imageData, numberOfBytes, 0x7fe0, 0x0010, "PXL" );
myGdcmFile->WriteDcmExplVR( m_FileName );
delete myGdcmFile;
delete myGdcmHeader;
#endif
}
void GDCMImageIO::PrintSelf(std::ostream& os, Indent indent) const
{
Superclass::PrintSelf(os, indent);
os << indent << "RescaleSlope: " << m_RescaleSlope << "\n";
os << indent << "RescaleIntercept: " << m_RescaleIntercept << "\n";
}
} // end namespace itk
<|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.
*/
#ifndef __PROC_UTILS_HPP__
#define __PROC_UTILS_HPP__
#include <list>
#include <string>
#include <sys/time.h>
#include "common/try.hpp"
namespace mesos {
namespace internal {
namespace monitoring {
struct ProcessStats {
std::string pid;
std::string ppid;
std::string pgrp;
std::string session;
double cpuTime; // total time in milliseconds.
double startTime; // in milliseconds since epoch.
double memUsage; // current usage in bytes.
};
// Reads from proc and returns a list of all processes running on the
// system.
Try<std::list<std::string> > getAllPids();
// Retrieves resource usage and metadata for a process. Takes the PID of
// the process to query and returns a ProcessStats struct containing the
// retrieved info.
Try<ProcessStats> getProcessStats(const std::string& pid);
// Retrieves the system boot time (in milliseconds since epoch).
Try<double> getBootTime();
// Retrieves the start time (in milliseconds since epoch) of the process
// with the given PID.
Try<double> getStartTime(const std::string& pid);
// Retrieves the current system time (in milliseconds since epoch).
inline double getCurrentTime()
{
timeval ctime;
gettimeofday(&ctime, NULL);
return (ctime.tv_sec * 1000.0 + ctime.tv_usec / 1000.0);
}
} // namespace monitoring {
} // namespace internal {
} // namespace mesos {
#endif // __PROC_UTILS_HPP__
<commit_msg>Commenting improvements.<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.
*/
#ifndef __PROC_UTILS_HPP__
#define __PROC_UTILS_HPP__
#include <list>
#include <string>
#include <sys/time.h>
#include "common/try.hpp"
namespace mesos {
namespace internal {
namespace monitoring {
struct ProcessStats {
std::string pid;
std::string ppid;
std::string pgrp;
std::string session;
double cpuTime; // Total time in milliseconds.
double startTime; // Timestamp in milliseconds since epoch.
double memUsage; // Current usage in bytes.
};
// Reads from proc and returns a list of all processes running on the
// system.
Try<std::list<std::string> > getAllPids();
// Retrieves resource usage and metadata for a process. Takes the PID of
// the process to query and returns a ProcessStats struct containing the
// retrieved info.
Try<ProcessStats> getProcessStats(const std::string& pid);
// Retrieves the system boot time (in milliseconds since epoch).
Try<double> getBootTime();
// Retrieves the start time (in milliseconds since epoch) of the process
// with the given PID.
Try<double> getStartTime(const std::string& pid);
// Retrieves the current system time (in milliseconds since epoch).
inline double getCurrentTime()
{
timeval ctime;
gettimeofday(&ctime, NULL);
return (ctime.tv_sec * 1000.0 + ctime.tv_usec / 1000.0);
}
} // namespace monitoring {
} // namespace internal {
} // namespace mesos {
#endif // __PROC_UTILS_HPP__
<|endoftext|>
|
<commit_before>// RUN: llvm-profdata merge %S/Inputs/regionMarkers.proftext -o %t.profdata
int main() { // CHECK-NOT: Marker at [[@LINE]]:12
int x = 0;
if (x) { // CHECK-NOT: Marker at [[@LINE]]:10
x = 0;
} else { // CHECK-NOT: Marker at [[@LINE]]:10
x = 1;
}
// CHECK-NOT: Marker at [[@LINE+2]]:19
// CHECK: Marker at [[@LINE+1]]:28 = 111M
for (int i = 0; i < 100; ++i) { // CHECK-NOT: Marker at [[@LINE]]:33
x = 1;
}
// CHECK-NOT: Marker at [[@LINE+1]]:16
x = x < 10 ? x + 1 : x - 1; // CHECK: Marker at [[@LINE]]:24 = 0
x = x > 10 ?
x - 1: // CHECK-NOT: Marker at [[@LINE]]:9
x + 1; // CHECK-NOT: Marker at [[@LINE]]:9
return 0;
}
// RUN: llvm-cov show %S/Inputs/regionMarkers.covmapping -instr-profile %t.profdata -show-regions -dump -path-equivalence=/Users/bogner/code/llvm/test/tools,%S/.. %s 2>&1 | FileCheck %s
// RUN: llvm-cov show %S/Inputs/regionMarkers.covmapping -instr-profile %t.profdata -show-regions -format=html -dump -path-equivalence=/Users/bogner/code/llvm/test/tools,%S/.. %s 2>&1 | FileCheck %s
// RUN: llvm-cov export %S/Inputs/regionMarkers.covmapping -instr-profile %t.profdata 2>&1 | FileCheck %S/Inputs/regionMarkers.json
<commit_msg>[llvm-cov] Fix a -path-equivalence bug in a test<commit_after>// RUN: llvm-profdata merge %S/Inputs/regionMarkers.proftext -o %t.profdata
int main() { // CHECK-NOT: Marker at [[@LINE]]:12
int x = 0;
if (x) { // CHECK-NOT: Marker at [[@LINE]]:10
x = 0;
} else { // CHECK-NOT: Marker at [[@LINE]]:10
x = 1;
}
// CHECK-NOT: Marker at [[@LINE+2]]:19
// CHECK: Marker at [[@LINE+1]]:28 = 111M
for (int i = 0; i < 100; ++i) { // CHECK-NOT: Marker at [[@LINE]]:33
x = 1;
}
// CHECK-NOT: Marker at [[@LINE+1]]:16
x = x < 10 ? x + 1 : x - 1; // CHECK: Marker at [[@LINE]]:24 = 0
x = x > 10 ?
x - 1: // CHECK-NOT: Marker at [[@LINE]]:9
x + 1; // CHECK-NOT: Marker at [[@LINE]]:9
return 0;
}
// RUN: llvm-cov show %S/Inputs/regionMarkers.covmapping -instr-profile %t.profdata -show-regions -dump -path-equivalence=/tmp,%S/ %s 2>&1 | FileCheck %s
// RUN: llvm-cov show %S/Inputs/regionMarkers.covmapping -instr-profile %t.profdata -show-regions -format=html -dump -path-equivalence=/tmp,%S %s 2>&1 | FileCheck %s
// RUN: llvm-cov export %S/Inputs/regionMarkers.covmapping -instr-profile %t.profdata 2>&1 | FileCheck %S/Inputs/regionMarkers.json
<|endoftext|>
|
<commit_before>#include "evpp/inner_pre.h"
#include "evpp/libevent_headers.h"
#include "evpp/sockets.h"
namespace evpp {
EVPP_EXPORT std::string strerror(int e) {
#ifdef H_OS_WINDOWS
LPVOID lpMsgBuf = NULL;
::FormatMessageA(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, e, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&lpMsgBuf, 0, NULL);
if (lpMsgBuf) {
std::string s = (char*)lpMsgBuf;
LocalFree(lpMsgBuf);
return s;
}
return std::string();
#else
char buf[1024] = {};
return std::string(strerror_r(e, buf, sizeof buf));
#endif
}
int CreateNonblockingSocket() {
int serrno = 0;
int on = 1;
/* Create listen socket */
int fd = ::socket(AF_INET, SOCK_STREAM, 0);
serrno = errno;
if (fd == -1) {
LOG_ERROR << "socket error " << strerror(serrno);
return INVALID_SOCKET;
}
if (evutil_make_socket_nonblocking(fd) < 0)
goto out;
#ifndef H_OS_WINDOWS
if (fcntl(fd, F_SETFD, 1) == -1) {
serrno = errno;
LOG_FATAL << "fcntl(F_SETFD)" << strerror(serrno);
goto out;
}
#endif
::setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (const char*)&on, sizeof(on));
::setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char*)&on, sizeof(on));
return fd;
out:
EVUTIL_CLOSESOCKET(fd);
return INVALID_SOCKET;
}
struct sockaddr_in ParseFromIPPort(const char* address/*ip:port*/) {
struct sockaddr_in addr;
memset(&addr, 0, sizeof(addr));
std::string a = address;
size_t index = a.rfind(':');
if (index == std::string::npos) {
LOG_FATAL << "Address specified error [" << address << "]";
}
addr.sin_family = AF_INET;
addr.sin_port = ::htons(::atoi(&a[index + 1]));
a[index] = '\0';
if (::inet_pton(AF_INET, a.data(), &addr.sin_addr) <= 0) {
int serrno = errno;
LOG_ERROR << "ParseFromIPPort " << strerror(serrno);
}
//TODO add ipv6 support
return addr;
}
struct sockaddr_in GetLocalAddr(int sockfd) {
struct sockaddr_in laddr;
memset(&laddr, 0, sizeof laddr);
socklen_t addrlen = static_cast<socklen_t>(sizeof laddr);
if (::getsockname(sockfd, sockaddr_cast(&laddr), &addrlen) < 0) {
LOG_ERROR << "GetLocalAddr:" << strerror(errno);
memset(&laddr, 0, sizeof laddr);
}
return laddr;
}
std::string ToIPPort(const struct sockaddr_storage* ss) {
std::string saddr;
int port = 0;
if (ss->ss_family == AF_INET) {
struct sockaddr_in* addr4 = const_cast<struct sockaddr_in*>(sockaddr_in_cast(ss));
char buf[INET_ADDRSTRLEN] = {};
const char* addr = ::inet_ntop(ss->ss_family, &addr4->sin_addr, buf, INET_ADDRSTRLEN);
if (addr) {
saddr = addr;
}
port = ::ntohs(addr4->sin_port);
} else if (ss->ss_family == AF_INET6) {
struct sockaddr_in6* addr6 = const_cast<struct sockaddr_in6*>(sockaddr_in6_cast(ss));
char buf[INET6_ADDRSTRLEN] = {};
const char* addr = ::inet_ntop(ss->ss_family, &addr6->sin6_addr, buf, INET6_ADDRSTRLEN);
if (addr) {
saddr = addr;
}
port = ::ntohs(addr6->sin6_port);
} else {
LOG_ERROR << "unknown socket family connected";
return std::string();
}
if (!saddr.empty()) {
char buf[16] = {};
snprintf(buf, sizeof(buf), "%d", port);
saddr.append(":", 1).append(buf);
}
return saddr;
}
void SetKeepAlive(int fd) {
int on = 1;
int rc = ::setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (const char*)&on, sizeof(on));
assert(rc == 0);
}
}
#ifdef H_OS_WINDOWS
int readv(int sockfd, struct iovec *iov, int iovcnt) {
DWORD readn = 0;
DWORD flags = 0;
if (::WSARecv(sockfd, iov, iovcnt, &readn, &flags, NULL, NULL) == 0) {
return readn;
}
return -1;
}
#endif
<commit_msg>Modify the debug log<commit_after>#include "evpp/inner_pre.h"
#include "evpp/libevent_headers.h"
#include "evpp/sockets.h"
namespace evpp {
EVPP_EXPORT std::string strerror(int e) {
#ifdef H_OS_WINDOWS
LPVOID lpMsgBuf = NULL;
::FormatMessageA(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, e, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&lpMsgBuf, 0, NULL);
if (lpMsgBuf) {
std::string s = (char*)lpMsgBuf;
LocalFree(lpMsgBuf);
return s;
}
return std::string();
#else
char buf[1024] = {};
return std::string(strerror_r(e, buf, sizeof buf));
#endif
}
int CreateNonblockingSocket() {
int serrno = 0;
int on = 1;
/* Create listen socket */
int fd = ::socket(AF_INET, SOCK_STREAM, 0);
serrno = errno;
if (fd == -1) {
LOG_ERROR << "socket error " << strerror(serrno);
return INVALID_SOCKET;
}
if (evutil_make_socket_nonblocking(fd) < 0)
goto out;
#ifndef H_OS_WINDOWS
if (fcntl(fd, F_SETFD, 1) == -1) {
serrno = errno;
LOG_FATAL << "fcntl(F_SETFD)" << strerror(serrno);
goto out;
}
#endif
::setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (const char*)&on, sizeof(on));
::setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char*)&on, sizeof(on));
return fd;
out:
EVUTIL_CLOSESOCKET(fd);
return INVALID_SOCKET;
}
struct sockaddr_in ParseFromIPPort(const char* address/*ip:port*/) {
struct sockaddr_in addr;
memset(&addr, 0, sizeof(addr));
std::string a = address;
size_t index = a.rfind(':');
if (index == std::string::npos) {
LOG_FATAL << "Address specified error [" << address << "]";
}
addr.sin_family = AF_INET;
addr.sin_port = ::htons(::atoi(&a[index + 1]));
a[index] = '\0';
if (::inet_pton(AF_INET, a.data(), &addr.sin_addr) <= 0) {
int serrno = errno;
if (serrno == 0) {
LOG_INFO << "[" << a.data() << "] is not a IP address. Maybe it is a hostname.";
} else {
LOG_ERROR << "ParseFromIPPort " << strerror(serrno);
}
}
//TODO add ipv6 support
return addr;
}
struct sockaddr_in GetLocalAddr(int sockfd) {
struct sockaddr_in laddr;
memset(&laddr, 0, sizeof laddr);
socklen_t addrlen = static_cast<socklen_t>(sizeof laddr);
if (::getsockname(sockfd, sockaddr_cast(&laddr), &addrlen) < 0) {
LOG_ERROR << "GetLocalAddr:" << strerror(errno);
memset(&laddr, 0, sizeof laddr);
}
return laddr;
}
std::string ToIPPort(const struct sockaddr_storage* ss) {
std::string saddr;
int port = 0;
if (ss->ss_family == AF_INET) {
struct sockaddr_in* addr4 = const_cast<struct sockaddr_in*>(sockaddr_in_cast(ss));
char buf[INET_ADDRSTRLEN] = {};
const char* addr = ::inet_ntop(ss->ss_family, &addr4->sin_addr, buf, INET_ADDRSTRLEN);
if (addr) {
saddr = addr;
}
port = ::ntohs(addr4->sin_port);
} else if (ss->ss_family == AF_INET6) {
struct sockaddr_in6* addr6 = const_cast<struct sockaddr_in6*>(sockaddr_in6_cast(ss));
char buf[INET6_ADDRSTRLEN] = {};
const char* addr = ::inet_ntop(ss->ss_family, &addr6->sin6_addr, buf, INET6_ADDRSTRLEN);
if (addr) {
saddr = addr;
}
port = ::ntohs(addr6->sin6_port);
} else {
LOG_ERROR << "unknown socket family connected";
return std::string();
}
if (!saddr.empty()) {
char buf[16] = {};
snprintf(buf, sizeof(buf), "%d", port);
saddr.append(":", 1).append(buf);
}
return saddr;
}
void SetKeepAlive(int fd) {
int on = 1;
int rc = ::setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (const char*)&on, sizeof(on));
assert(rc == 0);
}
}
#ifdef H_OS_WINDOWS
int readv(int sockfd, struct iovec *iov, int iovcnt) {
DWORD readn = 0;
DWORD flags = 0;
if (::WSARecv(sockfd, iov, iovcnt, &readn, &flags, NULL, NULL) == 0) {
return readn;
}
return -1;
}
#endif
<|endoftext|>
|
<commit_before>// Copyright 2015 Open Source Robotics Foundation, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <gtest/gtest.h>
#include "./memory_tools.hpp"
/* Tests the allocation checking tools.
*/
TEST(TestMemoryTools, test_allocation_checking_tools) {
size_t unexpected_mallocs = 0;
auto on_unexpected_malloc = (
[&unexpected_mallocs]() {
unexpected_mallocs++;
});
set_on_unexpected_malloc_callback(on_unexpected_malloc);
size_t unexpected_reallocs = 0;
auto on_unexpected_realloc = (
[&unexpected_reallocs]() {
unexpected_reallocs++;
});
set_on_unexpected_realloc_callback(on_unexpected_realloc);
size_t unexpected_frees = 0;
auto on_unexpected_free = (
[&unexpected_frees]() {
unexpected_frees++;
});
set_on_unexpected_free_callback(on_unexpected_free);
void * mem = nullptr;
void * remem = nullptr;
// First try before enabling, should have no effect.
mem = malloc(1024);
ASSERT_NE(nullptr, mem);
remem = realloc(mem, 2048);
ASSERT_NE(nullptr, remem);
free(remem);
EXPECT_EQ(0u, unexpected_mallocs);
EXPECT_EQ(0u, unexpected_reallocs);
EXPECT_EQ(0u, unexpected_frees);
// Enable checking, but no assert, should have no effect.
start_memory_checking();
mem = malloc(1024);
ASSERT_NE(nullptr, mem);
remem = realloc(mem, 2048);
ASSERT_NE(nullptr, remem);
free(remem);
EXPECT_EQ(0u, unexpected_mallocs);
EXPECT_EQ(0u, unexpected_reallocs);
EXPECT_EQ(0u, unexpected_frees);
// Enable no_* asserts, should increment all once.
assert_no_malloc_begin();
assert_no_realloc_begin();
assert_no_free_begin();
mem = malloc(1024);
assert_no_malloc_end();
ASSERT_NE(nullptr, mem);
remem = realloc(mem, 2048);
assert_no_realloc_end();
ASSERT_NE(nullptr, remem);
free(remem);
assert_no_free_end();
EXPECT_EQ(1u, unexpected_mallocs);
EXPECT_EQ(1u, unexpected_reallocs);
EXPECT_EQ(1u, unexpected_frees);
// Enable on malloc assert, only malloc should increment.
assert_no_malloc_begin();
mem = malloc(1024);
assert_no_malloc_end();
ASSERT_NE(nullptr, mem);
remem = realloc(mem, 2048);
ASSERT_NE(nullptr, remem);
free(remem);
EXPECT_EQ(2u, unexpected_mallocs);
EXPECT_EQ(1u, unexpected_reallocs);
EXPECT_EQ(1u, unexpected_frees);
// Enable on realloc assert, only realloc should increment.
assert_no_realloc_begin();
mem = malloc(1024);
ASSERT_NE(nullptr, mem);
remem = realloc(mem, 2048);
assert_no_realloc_end();
ASSERT_NE(nullptr, remem);
free(remem);
EXPECT_EQ(2u, unexpected_mallocs);
EXPECT_EQ(2u, unexpected_reallocs);
EXPECT_EQ(1u, unexpected_frees);
// Enable on free assert, only free should increment.
assert_no_free_begin();
mem = malloc(1024);
ASSERT_NE(nullptr, mem);
remem = realloc(mem, 2048);
ASSERT_NE(nullptr, remem);
free(remem);
assert_no_free_end();
EXPECT_EQ(2u, unexpected_mallocs);
EXPECT_EQ(2u, unexpected_reallocs);
EXPECT_EQ(2u, unexpected_frees);
// Go again, after disabling asserts, should have no effect.
mem = malloc(1024);
ASSERT_NE(nullptr, mem);
remem = realloc(mem, 2048);
ASSERT_NE(nullptr, remem);
free(remem);
EXPECT_EQ(2u, unexpected_mallocs);
EXPECT_EQ(2u, unexpected_reallocs);
EXPECT_EQ(2u, unexpected_frees);
// Go once more after disabling everything, should have no effect.
stop_memory_checking();
mem = malloc(1024);
ASSERT_NE(nullptr, mem);
remem = realloc(mem, 2048);
ASSERT_NE(nullptr, remem);
free(remem);
EXPECT_EQ(2u, unexpected_mallocs);
EXPECT_EQ(2u, unexpected_reallocs);
EXPECT_EQ(2u, unexpected_frees);
}
<commit_msg>update style (#93)<commit_after>// Copyright 2015 Open Source Robotics Foundation, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <gtest/gtest.h>
#include "./memory_tools.hpp"
/* Tests the allocation checking tools.
*/
TEST(TestMemoryTools, test_allocation_checking_tools) {
size_t unexpected_mallocs = 0;
auto on_unexpected_malloc =
[&unexpected_mallocs]() {
unexpected_mallocs++;
};
set_on_unexpected_malloc_callback(on_unexpected_malloc);
size_t unexpected_reallocs = 0;
auto on_unexpected_realloc =
[&unexpected_reallocs]() {
unexpected_reallocs++;
};
set_on_unexpected_realloc_callback(on_unexpected_realloc);
size_t unexpected_frees = 0;
auto on_unexpected_free =
[&unexpected_frees]() {
unexpected_frees++;
};
set_on_unexpected_free_callback(on_unexpected_free);
void * mem = nullptr;
void * remem = nullptr;
// First try before enabling, should have no effect.
mem = malloc(1024);
ASSERT_NE(nullptr, mem);
remem = realloc(mem, 2048);
ASSERT_NE(nullptr, remem);
free(remem);
EXPECT_EQ(0u, unexpected_mallocs);
EXPECT_EQ(0u, unexpected_reallocs);
EXPECT_EQ(0u, unexpected_frees);
// Enable checking, but no assert, should have no effect.
start_memory_checking();
mem = malloc(1024);
ASSERT_NE(nullptr, mem);
remem = realloc(mem, 2048);
ASSERT_NE(nullptr, remem);
free(remem);
EXPECT_EQ(0u, unexpected_mallocs);
EXPECT_EQ(0u, unexpected_reallocs);
EXPECT_EQ(0u, unexpected_frees);
// Enable no_* asserts, should increment all once.
assert_no_malloc_begin();
assert_no_realloc_begin();
assert_no_free_begin();
mem = malloc(1024);
assert_no_malloc_end();
ASSERT_NE(nullptr, mem);
remem = realloc(mem, 2048);
assert_no_realloc_end();
ASSERT_NE(nullptr, remem);
free(remem);
assert_no_free_end();
EXPECT_EQ(1u, unexpected_mallocs);
EXPECT_EQ(1u, unexpected_reallocs);
EXPECT_EQ(1u, unexpected_frees);
// Enable on malloc assert, only malloc should increment.
assert_no_malloc_begin();
mem = malloc(1024);
assert_no_malloc_end();
ASSERT_NE(nullptr, mem);
remem = realloc(mem, 2048);
ASSERT_NE(nullptr, remem);
free(remem);
EXPECT_EQ(2u, unexpected_mallocs);
EXPECT_EQ(1u, unexpected_reallocs);
EXPECT_EQ(1u, unexpected_frees);
// Enable on realloc assert, only realloc should increment.
assert_no_realloc_begin();
mem = malloc(1024);
ASSERT_NE(nullptr, mem);
remem = realloc(mem, 2048);
assert_no_realloc_end();
ASSERT_NE(nullptr, remem);
free(remem);
EXPECT_EQ(2u, unexpected_mallocs);
EXPECT_EQ(2u, unexpected_reallocs);
EXPECT_EQ(1u, unexpected_frees);
// Enable on free assert, only free should increment.
assert_no_free_begin();
mem = malloc(1024);
ASSERT_NE(nullptr, mem);
remem = realloc(mem, 2048);
ASSERT_NE(nullptr, remem);
free(remem);
assert_no_free_end();
EXPECT_EQ(2u, unexpected_mallocs);
EXPECT_EQ(2u, unexpected_reallocs);
EXPECT_EQ(2u, unexpected_frees);
// Go again, after disabling asserts, should have no effect.
mem = malloc(1024);
ASSERT_NE(nullptr, mem);
remem = realloc(mem, 2048);
ASSERT_NE(nullptr, remem);
free(remem);
EXPECT_EQ(2u, unexpected_mallocs);
EXPECT_EQ(2u, unexpected_reallocs);
EXPECT_EQ(2u, unexpected_frees);
// Go once more after disabling everything, should have no effect.
stop_memory_checking();
mem = malloc(1024);
ASSERT_NE(nullptr, mem);
remem = realloc(mem, 2048);
ASSERT_NE(nullptr, remem);
free(remem);
EXPECT_EQ(2u, unexpected_mallocs);
EXPECT_EQ(2u, unexpected_reallocs);
EXPECT_EQ(2u, unexpected_frees);
}
<|endoftext|>
|
<commit_before>//-----------------------------------------------
//
// This file is part of the Siv3D Engine.
//
// Copyright (c) 2008-2021 Ryo Suzuki
// Copyright (c) 2016-2021 OpenSiv3D Project
//
// Licensed under the MIT License.
//
//-----------------------------------------------
# include <Siv3D/Dialog.hpp>
namespace s3d
{
Optional<FilePath> OpenFile(const Array<FileFilter>& filters, const FilePathView defaultPath, const StringView title)
{
// [Siv3D ToDo]
return (none);
}
Array<FilePath> OpenFiles(const Array<FileFilter>& filters, const FilePathView defaultPath, const StringView title)
{
// [Siv3D ToDo]
return{};
}
Optional<FilePath> SaveFile(const Array<FileFilter>& filters, const FilePathView defaultPath, const StringView title)
{
// [Siv3D ToDo]
return (none);
}
Optional<FilePath> SelectFolder(const FilePathView defaultPath, const StringView title)
{
// [Siv3D ToDo]
return (none);
}
}
<commit_msg>[Linux] fix<commit_after>//-----------------------------------------------
//
// This file is part of the Siv3D Engine.
//
// Copyright (c) 2008-2021 Ryo Suzuki
// Copyright (c) 2016-2021 OpenSiv3D Project
//
// Licensed under the MIT License.
//
//-----------------------------------------------
# include <Siv3D/Dialog.hpp>
namespace s3d
{
namespace Dialog
{
Optional<FilePath> OpenFile(const Array<FileFilter>& filters, const FilePathView defaultPath, const StringView title)
{
// [Siv3D ToDo]
return (none);
}
Array<FilePath> OpenFiles(const Array<FileFilter>& filters, const FilePathView defaultPath, const StringView title)
{
// [Siv3D ToDo]
return{};
}
Optional<FilePath> SaveFile(const Array<FileFilter>& filters, const FilePathView defaultPath, const StringView title)
{
// [Siv3D ToDo]
return (none);
}
Optional<FilePath> SelectFolder(const FilePathView defaultPath, const StringView title)
{
// [Siv3D ToDo]
return (none);
}
}
}
<|endoftext|>
|
<commit_before>/*
ESP8266WiFiMesh.cpp - Mesh network node
Sets up a Mesh Node which acts as a router, creating a Mesh Network with other nodes. All information
is passed in both directions, but it is up to the user what the data sent is and how it is dealt with.
Copyright (c) 2015 Julian Fell. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <WiFiServer.h>
#include "ESP8266WiFiMesh.h"
#define SSID_PREFIX "Mesh_Node"
#define SERVER_IP_ADDR "192.168.4.1"
#define SERVER_PORT 4011
ESP8266WiFiMesh::ESP8266WiFiMesh(uint32_t chip_id, std::function<String(String)> handler)
: _server(SERVER_PORT)
{
_chip_id = chip_id;
_ssid = String( String( SSID_PREFIX ) + String( _chip_id ) );
_ssid_prefix = String( SSID_PREFIX );
_handler = handler;
}
void ESP8266WiFiMesh::begin()
{
WiFi.mode(WIFI_AP_STA);
WiFi.softAP( _ssid.c_str() );
_server.begin();
}
/**
* Wait for a WiFiClient to connect
*
* @returns: True if the client is ready, false otherwise.
*
*/
bool ESP8266WiFiMesh::waitForClient(WiFiClient curr_client, int max_wait)
{
int wait = max_wait;
while(curr_client.connected() && !curr_client.available() && wait--)
delay(3);
/* Return false if the client isn't ready to communicate */
if (WiFi.status() == WL_DISCONNECTED || !curr_client.connected())
return false;
return true;
}
/**
* Send the supplied message then read back the other node's response
* and pass that to the user-supplied handler.
*
* @target_ssid The name of the AP the other node has set up.
* @message The string to send to the node.
* @returns: True if the exchange was a succes, false otherwise.
*
*/
bool ESP8266WiFiMesh::exchangeInfo(String message, WiFiClient curr_client)
{
curr_client.println( message.c_str() );
if (!waitForClient(curr_client, 1000))
return false;
String response = curr_client.readStringUntil('\r');
curr_client.readStringUntil('\n');
if (response.length() <= 2)
return false;
/* Pass data to user callback */
_handler(response);
return true;
}
/**
* Connect to the AP at ssid, send them a message then disconnect.
*
* @target_ssid The name of the AP the other node has set up.
* @message The string to send to the node.
*
*/
void WiFiMesh::connectToNode(String target_ssid, String message)
{
WiFiClient curr_client;
WiFi.begin( target_ssid.c_str() );
int wait = 1500;
while((WiFi.status() == WL_DISCONNECTED) && wait--)
delay(3);
/* If the connection timed out */
if (WiFi.status() != 3)
return;
/* Connect to the node's server */
if (!curr_client.connect(SERVER_IP_ADDR, SERVER_PORT))
return;
if (!exchangeInfo(message, curr_client))
return;
curr_client.stop();
WiFi.disconnect();
}
void ESP8266WiFiMesh::attemptScan(String message)
{
/* Scan for APs */
int n = WiFi.scanNetworks();
for (int i = 0; i < n; ++i) {
String current_ssid = WiFi.SSID(i);
int index = current_ssid.indexOf( _ssid_prefix );
uint32_t target_chip_id = (current_ssid.substring(index + _ssid_prefix.length())).toInt();
/* Connect to any _suitable_ APs which contain _ssid_prefix */
if (index >= 0 && (target_chip_id < _chip_id)) {
WiFi.mode(WIFI_STA);
delay(100);
connectToNode(current_ssid, message);
WiFi.mode(WIFI_AP_STA);
delay(100);
}
}
}
void ESP8266WiFiMesh::acceptRequest()
{
while (true) {
_client = _server.available();
if (!_client)
break;
if (!waitForClient(_client, 1500)) {
continue;
}
/* Read in request and pass it to the supplied handler */
String request = _client.readStringUntil('\r');
_client.readStringUntil('\n');
String response = _handler(request);
/* Send the response back to the client */
if (_client.connected())
_client.println(response);
}
}<commit_msg>missing part of class name WiFiMesh -> ESP8266WiFiMesh<commit_after>/*
ESP8266WiFiMesh.cpp - Mesh network node
Sets up a Mesh Node which acts as a router, creating a Mesh Network with other nodes. All information
is passed in both directions, but it is up to the user what the data sent is and how it is dealt with.
Copyright (c) 2015 Julian Fell. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <WiFiServer.h>
#include "ESP8266WiFiMesh.h"
#define SSID_PREFIX "Mesh_Node"
#define SERVER_IP_ADDR "192.168.4.1"
#define SERVER_PORT 4011
ESP8266WiFiMesh::ESP8266WiFiMesh(uint32_t chip_id, std::function<String(String)> handler)
: _server(SERVER_PORT)
{
_chip_id = chip_id;
_ssid = String( String( SSID_PREFIX ) + String( _chip_id ) );
_ssid_prefix = String( SSID_PREFIX );
_handler = handler;
}
void ESP8266WiFiMesh::begin()
{
WiFi.mode(WIFI_AP_STA);
WiFi.softAP( _ssid.c_str() );
_server.begin();
}
/**
* Wait for a WiFiClient to connect
*
* @returns: True if the client is ready, false otherwise.
*
*/
bool ESP8266WiFiMesh::waitForClient(WiFiClient curr_client, int max_wait)
{
int wait = max_wait;
while(curr_client.connected() && !curr_client.available() && wait--)
delay(3);
/* Return false if the client isn't ready to communicate */
if (WiFi.status() == WL_DISCONNECTED || !curr_client.connected())
return false;
return true;
}
/**
* Send the supplied message then read back the other node's response
* and pass that to the user-supplied handler.
*
* @target_ssid The name of the AP the other node has set up.
* @message The string to send to the node.
* @returns: True if the exchange was a succes, false otherwise.
*
*/
bool ESP8266WiFiMesh::exchangeInfo(String message, WiFiClient curr_client)
{
curr_client.println( message.c_str() );
if (!waitForClient(curr_client, 1000))
return false;
String response = curr_client.readStringUntil('\r');
curr_client.readStringUntil('\n');
if (response.length() <= 2)
return false;
/* Pass data to user callback */
_handler(response);
return true;
}
/**
* Connect to the AP at ssid, send them a message then disconnect.
*
* @target_ssid The name of the AP the other node has set up.
* @message The string to send to the node.
*
*/
void ESP8266WiFiMesh::connectToNode(String target_ssid, String message)
{
WiFiClient curr_client;
WiFi.begin( target_ssid.c_str() );
int wait = 1500;
while((WiFi.status() == WL_DISCONNECTED) && wait--)
delay(3);
/* If the connection timed out */
if (WiFi.status() != 3)
return;
/* Connect to the node's server */
if (!curr_client.connect(SERVER_IP_ADDR, SERVER_PORT))
return;
if (!exchangeInfo(message, curr_client))
return;
curr_client.stop();
WiFi.disconnect();
}
void ESP8266WiFiMesh::attemptScan(String message)
{
/* Scan for APs */
int n = WiFi.scanNetworks();
for (int i = 0; i < n; ++i) {
String current_ssid = WiFi.SSID(i);
int index = current_ssid.indexOf( _ssid_prefix );
uint32_t target_chip_id = (current_ssid.substring(index + _ssid_prefix.length())).toInt();
/* Connect to any _suitable_ APs which contain _ssid_prefix */
if (index >= 0 && (target_chip_id < _chip_id)) {
WiFi.mode(WIFI_STA);
delay(100);
connectToNode(current_ssid, message);
WiFi.mode(WIFI_AP_STA);
delay(100);
}
}
}
void ESP8266WiFiMesh::acceptRequest()
{
while (true) {
_client = _server.available();
if (!_client)
break;
if (!waitForClient(_client, 1500)) {
continue;
}
/* Read in request and pass it to the supplied handler */
String request = _client.readStringUntil('\r');
_client.readStringUntil('\n');
String response = _handler(request);
/* Send the response back to the client */
if (_client.connected())
_client.println(response);
}
}
<|endoftext|>
|
<commit_before>#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <cmath>
#include <limits>
using namespace std;
#include <LibUtilities/Foundations/NodalUtil.h>
#include "LibUtilities/Foundations/Foundations.hpp"
#include <LibUtilities/BasicUtils/NekManager.hpp>
#include <LibUtilities/Foundations/Points.h>
#include <LibUtilities/Foundations/GaussPoints.h>
#include <LibUtilities/Foundations/PolyEPoints.h>
#include <LibUtilities/Foundations/Basis.h>
#include <LibUtilities/Foundations/NodalTriFekete.h>
#include <LibUtilities/Foundations/ManagerAccess.h>
using namespace Nektar;
using namespace boost;
using namespace Nektar::LibUtilities;
int main(int argc, char *argv[]){
// Argument check: Display a help message if the count is wrong
if(argc != 3){
cerr << "Usage: NodalTriFeketeDemo Points2D-Type nPtsPerSide" << endl;
cerr << "Where type is an integer value which dictates the basis as:\n";
for(int i=0; i<SIZE_PointsType; ++i){
cerr << setw(30) << PointsTypeMap[i] << " =" << i << endl;
}
cerr << "Note type = 1 ~ 14 are for one dimensional basis, and 15 and 16 are for two dimensional basis " << endl;
cerr << "\n Example: NodalTriFeketeDemo 16 3" << endl;
cerr << "\n\t Tests 2D NodalTriFekete on 3 points per side" << endl;
return 1; // Aborts main() function
}
// Read in the type for the points from the caller
PointsType pointsType = (PointsType) atoi(argv[1]);
if(pointsType == eNoPointsType){
cerr << "pointsType = " << pointsType << endl;
cerr << "PointsTypeMap[" <<pointsType<< "]=" << PointsTypeMap[pointsType] << endl;
ErrorUtil::Error(ErrorUtil::efatal,__FILE__, __LINE__,
"No Points Type requested",0);
}
// Read in the number of points per side at which the function will be evaluated
int nPtsPerSide = atoi(argv[2]);
// Show the set up to the user
cout << "Points Type: " << PointsTypeMap[pointsType] << endl;
cout << "Number of points per side: " << nPtsPerSide << endl;
// Display the example test function to the user
if( pointsType == eNodalTriFekete){
cout << "Uniform grid on a Triangle points" << endl;
}
int degree = nPtsPerSide-1;
boost::shared_ptr<Points<NekDouble> > points = PointsManager()[PointsKey(nPtsPerSide, pointsType)];
NodalTriFekete *ntf = dynamic_cast<NodalTriFekete*>(points.get());
ConstArray<OneD, NekDouble> ax, ay;
ntf->GetPoints(ax,ay);
NekVector<NekDouble> x = toVector(ax), y = toVector(ay);
// /////////////////////////////////////////////
// Test Interpolation
//
// Make a uniform grid on the triangle
int nGridPtsPerSide = 5, nGridPts = nGridPtsPerSide * (nGridPtsPerSide + 1) / 2;
Array<OneD, NekDouble> axi(nGridPts), ayi(nGridPts);
for( int i = 0, n = 0; i < nGridPtsPerSide; ++i ) {
for( int j = 0; j < nGridPtsPerSide - i; ++j, ++n ) {
axi[n] = -1.0 + 2.0*j / (nGridPtsPerSide - 1);
ayi[n] = -1.0 + 2.0*i / (nGridPtsPerSide - 1);
}
}
NekVector<NekDouble> xi = toVector(axi), yi = toVector(ayi);
boost::shared_ptr<NekMatrix<NekDouble> > Iptr = ntf->GetI(axi, ayi);
const NekMatrix<NekDouble> & I = *Iptr;
NekMatrix<NekDouble> Vnn = getMonomialVandermonde(x, y);
NekMatrix<NekDouble> Vmn = getMonomialVandermonde(xi, yi, degree);
NekMatrix<NekDouble> VmnTilde = I * Vnn;
NekMatrix<NekDouble> E(xi.GetRows(), x.GetRows());
NekMatrix<NekDouble> relativeError(getSize(xi), getSize(x));
long double epsilon = 1e-15;
for( int i = 0; i < int(xi.GetRows()); ++i ) {
for( int j = 0; j < int(x.GetRows()); ++j ) {
E(i,j) = LibUtilities::round(1e16 * fabs(VmnTilde(i,j) - Vmn(i,j)))/1e16;
// Compute relative error
relativeError(i,j) = (Vmn(i,j) - VmnTilde(i,j))/Vmn(i,j);
if( fabs(Vmn(i,j)) < numeric_limits<double>::epsilon() ) {
relativeError(i,j) = Vmn(i,j) - VmnTilde(i,j);
}
}
}
cout << "------------------------------- NodalTriFekete Interpolation Test -------------------------------" << endl;
cout << "\n Result of NumericInterpolation = \n" << VmnTilde << endl;
cout << "\n Result of I matrix = \n" << I << endl;
cout << "\n epsilon = \n" << epsilon << endl;
cout << "\n relativeError : Interpolation = \n" << relativeError << endl;
cout << "\n Error : abs(NumericInterpolation - exact) = \n" << E << endl;
cout << "---------------------------------- End of Interpolation Test ------------------------------------" << endl;
// /////////////////////////////////////////////
// Test X Derivative
//
boost::shared_ptr<NekMatrix<NekDouble> > Dptr = points->GetD();
const NekMatrix<NekDouble> & D = *Dptr;
NekMatrix<NekDouble> Vx = getXDerivativeOfMonomialVandermonde(x, y);
NekMatrix<NekDouble> NumericXDerivative = D * Vnn;
NekMatrix<NekDouble> Error(x.GetRows(), y.GetRows());
NekMatrix<NekDouble> relativeErrorDx(x.GetRows(), y.GetRows());
long double epsilonDx = 1e-14;
for(int i=0; i< int(x.GetRows()); ++i ){
for(int j=0; j< int(y.GetRows()); ++j){
Error(i,j) = LibUtilities::round(1e15 * fabs(NumericXDerivative(i,j) - Vx(i, j)))/1e15;
// Compute relative error
relativeErrorDx(i,j) = (Vx(i,j) - NumericXDerivative(i,j))/Vx(i,j);
if( fabs(Vx(i,j)) < numeric_limits<double>::epsilon() ) {
relativeErrorDx(i,j) = Vx(i,j) - NumericXDerivative(i,j);
}
}
}
cout << "------------------ NodalTriFekete X Derivative Floating Point Error Precision ---------------------------" << endl;
cout << "\n Result of NumericXDerivative = \n" << NumericXDerivative << endl;
cout << "\n Result of D matrix = \n" << D << endl;
cout << "epsilon = \n" << epsilonDx <<endl;
cout << "\n relativeError : X Derivative = \n" << relativeErrorDx << endl;
cout << "\n Error : abs(exact - NumericXDerivative) = \n" << Error << endl;
cout << "\n --------------- End of Testing X Derivative Matrix --------------------------" << endl;
// /////////////////////////////////////////////
// Test Integral
//
const ConstArray<OneD,NekDouble> &W = points->GetW();
NekVector<NekDouble> Vwi = getIntegralOfMonomialVandermonde(degree);
NekVector<NekDouble> NumericIntegral = getTranspose(Vnn) * toVector(W);
NekVector<NekDouble> ErrorIntegral = NumericIntegral - Vwi;
NekVector<NekDouble> relativeErrorIntegral(getSize(x));
long double epsilonIntegral = 1e-16;
for(int i=0; i<int(x.GetRows()); ++i){
relativeErrorIntegral(i) = (Vwi(i) - NumericIntegral(i))/Vwi(i);
if(fabs(Vwi(i)) < epsilonIntegral){
relativeErrorIntegral(i) = (Vwi(i) - NumericIntegral(i));
}
}
cout << "------------------------------- NodalTriFekete Integral Test -------------------------------" << endl;
cout << "\n Result of NumericIntegral = \n" << NumericIntegral << endl;
cout << "epsilon = \n" << epsilonIntegral << endl;
cout << "\n relativeError : Integral = \n" << relativeErrorIntegral << endl;
cout << "\n ErrorIntegral : (NumericIntegral - exact) = \n" << ErrorIntegral << endl;
cout << "\n W = \n" << toVector(W) << endl;
cout << "------------------------------- End of Integral Test ---------------------------------------" << endl;
}
<commit_msg>Conform to Coding Style Standard<commit_after>#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <cmath>
#include <limits>
using namespace std;
#include <LibUtilities/Foundations/NodalUtil.h>
#include <LibUtilities/Foundations/NodalTriFekete.h>
#include "LibUtilities/Foundations/Foundations.hpp"
#include <LibUtilities/BasicUtils/NekManager.hpp>
#include <LibUtilities/Foundations/Points.h>
#include <LibUtilities/Foundations/GaussPoints.h>
#include <LibUtilities/Foundations/PolyEPoints.h>
#include <LibUtilities/Foundations/Basis.h>
#include <LibUtilities/Foundations/ManagerAccess.h>
using namespace Nektar;
using namespace boost;
using namespace Nektar::LibUtilities;
int main(int argc, char *argv[]){
// Argument check: Display a help message if the count is wrong
if(argc != 3){
cerr << "Usage: NodalTriFeketeDemo Points2D-Type nPtsPerSide" << endl;
cerr << "Where type is an integer value which dictates the basis as:\n";
for(int i=0; i<SIZE_PointsType; ++i){
cerr << setw(30) << PointsTypeMap[i] << " =" << i << endl;
}
cerr << "Note type = 1 ~ 14 are for one dimensional basis, and 15 and 16 are for two dimensional basis " << endl;
cerr << "\n Example: NodalTriFeketeDemo 16 3" << endl;
cerr << "\n\t Tests 2D NodalTriFekete on 3 points per side" << endl;
return 1; // Aborts main() function
}
// Read in the type for the points from the caller
PointsType pointsType = (PointsType) atoi(argv[1]);
if(pointsType == eNoPointsType){
cerr << "pointsType = " << pointsType << endl;
cerr << "PointsTypeMap[" <<pointsType<< "]=" << PointsTypeMap[pointsType] << endl;
ErrorUtil::Error(ErrorUtil::efatal,__FILE__, __LINE__,
"No Points Type requested",0);
}
// Read in the number of points per side at which the function will be evaluated
int nPtsPerSide = atoi(argv[2]);
// Show the set up to the user
cout << "Points Type: " << PointsTypeMap[pointsType] << endl;
cout << "Number of points per side: " << nPtsPerSide << endl;
// Display the example test function to the user
if( pointsType == eNodalTriFekete){
cout << "Uniform grid on a Triangle points" << endl;
}
int degree = nPtsPerSide-1;
boost::shared_ptr<Points<NekDouble> > points = PointsManager()[PointsKey(nPtsPerSide, pointsType)];
NodalTriFekete *ntf = dynamic_cast<NodalTriFekete*>(points.get());
ConstArray<OneD, NekDouble> ax, ay;
ntf->GetPoints(ax,ay);
NekVector<NekDouble> x = ToVector(ax), y = ToVector(ay);
// /////////////////////////////////////////////
// Test Interpolation
//
// Make a uniform grid on the triangle
int nGridPtsPerSide = 5, nGridPts = nGridPtsPerSide * (nGridPtsPerSide + 1) / 2;
Array<OneD, NekDouble> axi(nGridPts), ayi(nGridPts);
for( int i = 0, n = 0; i < nGridPtsPerSide; ++i ) {
for( int j = 0; j < nGridPtsPerSide - i; ++j, ++n ) {
axi[n] = -1.0 + 2.0*j / (nGridPtsPerSide - 1);
ayi[n] = -1.0 + 2.0*i / (nGridPtsPerSide - 1);
}
}
NekVector<NekDouble> xi = ToVector(axi), yi = ToVector(ayi);
boost::shared_ptr<NekMatrix<NekDouble> > Iptr = ntf->GetI(axi, ayi);
const NekMatrix<NekDouble> & interpMat = *Iptr;
NekMatrix<NekDouble> matVnn = GetMonomialVandermonde(x, y);
NekMatrix<NekDouble> matVmn = GetMonomialVandermonde(xi, yi, degree);
NekMatrix<NekDouble> matVmnTilde = interpMat * matVnn;
NekMatrix<NekDouble> err(xi.GetRows(), x.GetRows());
NekMatrix<NekDouble> relativeError(GetSize(xi), GetSize(x));
long double epsilon = 1e-15;
for( int i = 0; i < int(xi.GetRows()); ++i ) {
for( int j = 0; j < int(x.GetRows()); ++j ) {
err(i,j) = LibUtilities::MakeRound(1e16 * fabs(matVmnTilde(i,j) - matVmn(i,j)))/1e16;
// Compute relative error
relativeError(i,j) = (matVmn(i,j) - matVmnTilde(i,j))/matVmn(i,j);
if( fabs(matVmn(i,j)) < numeric_limits<double>::epsilon() ) {
relativeError(i,j) = matVmn(i,j) - matVmnTilde(i,j);
}
}
}
cout << "------------------------------- NodalTriFekete Interpolation Test -------------------------------" << endl;
cout << "\n Result of NumericInterpolation = \n" << matVmnTilde << endl;
cout << "\n Result of I matrix = \n" << interpMat << endl;
cout << "\n epsilon = \n" << epsilon << endl;
cout << "\n relativeError : Interpolation = \n" << relativeError << endl;
cout << "\n Error : abs(NumericInterpolation - exact) = \n" << err << endl;
cout << "---------------------------------- End of Interpolation Test ------------------------------------" << endl;
// /////////////////////////////////////////////
// Test X Derivative
//
boost::shared_ptr<NekMatrix<NekDouble> > Dptr = points->GetD();
const NekMatrix<NekDouble> & derivativeMat = *Dptr;
NekMatrix<NekDouble> matVx = GetXDerivativeOfMonomialVandermonde(x, y);
NekMatrix<NekDouble> numericXDerivative = derivativeMat * matVnn;
NekMatrix<NekDouble> error(x.GetRows(), y.GetRows());
NekMatrix<NekDouble> relativeErrorDx(x.GetRows(), y.GetRows());
long double epsilonDx = 1e-14;
for(int i=0; i< int(x.GetRows()); ++i ){
for(int j=0; j< int(y.GetRows()); ++j){
error(i,j) = LibUtilities::MakeRound(1e15 * fabs(numericXDerivative(i,j) - matVx(i, j)))/1e15;
// Compute relative error
relativeErrorDx(i,j) = (matVx(i,j) - numericXDerivative(i,j))/matVx(i,j);
if( fabs(matVx(i,j)) < numeric_limits<double>::epsilon() ) {
relativeErrorDx(i,j) = matVx(i,j) - numericXDerivative(i,j);
}
}
}
cout << "------------------ NodalTriFekete X Derivative Floating Point Error Precision ---------------------------" << endl;
cout << "\n Result of NumericXDerivative = \n" << numericXDerivative << endl;
cout << "\n Result of D matrix = \n" << derivativeMat << endl;
cout << "epsilon = \n" << epsilonDx <<endl;
cout << "\n relativeError : X Derivative = \n" << relativeErrorDx << endl;
cout << "\n Error : abs(exact - NumericXDerivative) = \n" << error << endl;
cout << "\n --------------- End of Testing X Derivative Matrix --------------------------" << endl;
// /////////////////////////////////////////////
// Test Integral
//
const ConstArray<OneD,NekDouble> &weight = points->GetW();
NekVector<NekDouble> integMVandermonde = GetIntegralOfMonomialVandermonde(degree);
NekVector<NekDouble> numericIntegral = GetTranspose(matVnn) * ToVector(weight);
NekVector<NekDouble> errorIntegral = numericIntegral - integMVandermonde;
NekVector<NekDouble> relativeErrorIntegral(GetSize(x));
long double epsilonIntegral = 1e-16;
for(int i=0; i<int(x.GetRows()); ++i){
relativeErrorIntegral(i) = (integMVandermonde(i) - numericIntegral(i))/integMVandermonde(i);
if(fabs(integMVandermonde(i)) < epsilonIntegral){
relativeErrorIntegral(i) = (integMVandermonde(i) - numericIntegral(i));
}
}
cout << "------------------------------- NodalTriFekete Integral Test -------------------------------" << endl;
cout << "\n Result of NumericIntegral = \n" << numericIntegral << endl;
cout << "epsilon = \n" << epsilonIntegral << endl;
cout << "\n relativeError : Integral = \n" << relativeErrorIntegral << endl;
cout << "\n ErrorIntegral : (NumericIntegral - exact) = \n" << errorIntegral << endl;
cout << "\n W = \n" << ToVector(weight) << endl;
cout << "------------------------------- End of Integral Test ---------------------------------------" << endl;
}
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.